Sha256: 31a0cfe85cf6fb6c4f9ffb4996cb6b9ea1609ad9f43041b8f5e00b1b18fcc535

Contents?: true

Size: 1.49 KB

Versions: 3

Compression:

Stored size: 1.49 KB

Contents

# frozen_string_literal: true

module SolidusJwt
  module Spree
    module UserDecorator
      def self.prepended(base)
        base.extend ClassMethods
        base.has_many :auth_tokens, class_name: 'SolidusJwt::Token'
      end

      module ClassMethods
        ##
        # Find user based on subject claim in
        # our json web token
        # @see https://tools.ietf.org/html/rfc7519#section-4.1.2
        #
        # @example get user token
        #   payload = SolidusJwt.decode(token).first
        #   user = Spree::User.for_jwt(payload['sub'])
        #
        # @param sub [string] The subject claim of jwt
        # @return [Spree.user_class, NilClass] If a match is found, returns the user,
        #   otherwise, returns nil
        #
        def for_jwt(sub)
          find_by(id: sub)
        end
      end

      ##
      # Generate a json web token
      # @see https://github.com/jwt/ruby-jwt
      # @return [String]
      #
      def generate_jwt(expires_in: nil)
        SolidusJwt.encode(payload: as_jwt_payload, expires_in: expires_in)
      end
      alias generate_jwt_token generate_jwt

      ##
      # Serializes user attributes to hash and applies
      # the sub jwt claim.
      #
      # @return [Hash] The payload for json web token
      #
      def as_jwt_payload
        options = SolidusJwt::Config.jwt_options
        claims = { sub: id }

        as_json(options)
          .merge(claims)
          .as_json
      end

      ::Spree.user_class.prepend self
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
solidus_jwt-1.2.2 app/decorators/models/solidus_jwt/spree/user_decorator.rb
solidus_jwt-1.2.1 app/decorators/models/solidus_jwt/spree/user_decorator.rb
solidus_jwt-1.2.0 app/decorators/models/solidus_jwt/spree/user_decorator.rb