Sha256: 8c138183e21b64be1641ea71aa3e31bfbb73498ec0d177da5852bf06cea6b156

Contents?: true

Size: 1.08 KB

Versions: 12

Compression:

Stored size: 1.08 KB

Contents

require "jwt"

class Card
  module Auth
    # methods for setting current account
    module Token
      SECRET_KEY = Rails.application.secrets.secret_key_base.to_s

      class << self
        def encode user_id, extra_payload={}
          payload = { user_id: user_id, exp: expiration }.merge(extra_payload)

          JWT.encode payload, SECRET_KEY
        end

        # returns Hash if valid, String error message if not

        def validate! token
          payload = decode token
          raise Card::Error::PermissionDenied, payload if payload.is_a? String

          payload
        end

        def decode token
          decoded = JWT.decode(token, SECRET_KEY)[0]
          HashWithIndifferentAccess.new decoded
        rescue JWT::DecodeError => e
          e.message
        end

        def expiration
          Card.config.token_expiry.from_now.to_i
        end
      end

      # set the current user based on token
      def signin_with_token token
        payload = Token.validate! token
        signin payload[:anonymous] ? Card::AnonymousID : payload[:user_id]
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
card-1.104.2 lib/card/auth/token.rb
card-1.104.1 lib/card/auth/token.rb
card-1.104.0 lib/card/auth/token.rb
card-1.103.4 lib/card/auth/token.rb
card-1.103.3 lib/card/auth/token.rb
card-1.103.2 lib/card/auth/token.rb
card-1.103.1 lib/card/auth/token.rb
card-1.103.0 lib/card/auth/token.rb
card-1.101.7 lib/card/auth/token.rb
card-1.102.0 lib/card/auth/token.rb
card-1.101.6 lib/card/auth/token.rb
card-1.101.5 lib/card/auth/token.rb