Sha256: 97b5ecaefc530bc10880f2ef75cd766d82c399f8f19ad08b660a1116093c24e0

Contents?: true

Size: 1 KB

Versions: 3

Compression:

Stored size: 1 KB

Contents

# frozen_string_literal: true

class User::Token
  class Creation < ApplicationService
    input do
      attribute :user
      attribute :executed_at, :time, default: -> { ::Time.current }

      validates :user, presence: true, type: ::User
      validates :executed_at, presence: true
    end

    def call(attributes)
      Given(attributes)
        .and_then(:validate_token_existence)
        .and_then(:create_token)
        .and_expose(:token_created, %i[token])
    end

    private

    def validate_token_existence(user:, **)
      user.token.nil? ? Continue() : Failure(:token_already_exists)
    end

    def create_token(user:, executed_at:, **)
      token = user.create_token(
        access_token: ::SecureRandom.hex(24),
        refresh_token: ::SecureRandom.hex(24),
        access_token_expires_at: executed_at + 15.days,
        refresh_token_expires_at: executed_at + 30.days
      )

      token.persisted? ? Continue(token:) : Failure(:token_creation_failed, **token.errors.messages)
    end
  end
end

Version data entries

3 entries across 3 versions & 2 rubygems

Version Path
solid-result-2.0.0 examples/service_objects/app/services/user/token/creation.rb
bcdd-result-1.1.0 examples/service_objects/app/services/user/token/creation.rb
bcdd-result-1.0.0 examples/service_objects/app/services/user/token/creation.rb