Class: JsonWebToken

Inherits:
Object
  • Object
show all
Defined in:
lib/json_web_token.rb

Class Method Summary collapse

Class Method Details

.decode(token) ⇒ Object



10
11
12
13
14
15
16
17
# File 'lib/json_web_token.rb', line 10

def decode(token)
  # Check if the passed token is present and valid into the UsedToken 
  raise "Token is invalidated by new login" unless UsedToken.exists?(token: token, valid: true)
  body = ::JWT.decode(token, ::Rails.application.credentials.dig(:secret_key_base).presence||ENV["SECRET_KEY_BASE"])[0]
  ::HashWithIndifferentAccess.new body
rescue
  nil
end

.encode(payload, expiry = 15.minutes.from_now.to_i) ⇒ Object



3
4
5
6
7
8
# File 'lib/json_web_token.rb', line 3

def encode(payload, expiry = 15.minutes.from_now.to_i)
  result = ::JWT.encode(payload.merge(exp: expiry), ::Rails.application.credentials.dig(:secret_key_base).presence||ENV["SECRET_KEY_BASE"])
  # Store the created token into the DB for later checks if is invalid
  UsedToken.create(token: result, user_id: payload[:user_id])
  result
end