Module: Card::Auth::Token

Included in:
Card::Auth
Defined in:
lib/card/auth/token.rb

Overview

methods for setting current account

Constant Summary collapse

SECRET_KEY =
Rails.application.secrets.secret_key_base.to_s

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.decode(token) ⇒ Object



25
26
27
28
29
30
# File 'lib/card/auth/token.rb', line 25

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

.encode(user_id, extra_payload = {}) ⇒ Object



10
11
12
13
14
# File 'lib/card/auth/token.rb', line 10

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

  JWT.encode payload, SECRET_KEY
end

.expirationObject



32
33
34
# File 'lib/card/auth/token.rb', line 32

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

.validate!(token) ⇒ Object

returns Hash if valid, String error message if not



18
19
20
21
22
23
# File 'lib/card/auth/token.rb', line 18

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

  payload
end

Instance Method Details

#signin_with_token(token) ⇒ Object

set the current user based on token



38
39
40
41
# File 'lib/card/auth/token.rb', line 38

def  token
  payload = Token.validate! token
   payload[:anonymous] ? Card::AnonymousID : payload[:user_id]
end