Module: Sorcery::Model::Submodules::Jwt::ClassMethods

Defined in:
lib/sorcery/model/submodules/jwt.rb

Instance Method Summary collapse

Instance Method Details

#decode_token(token) ⇒ Array<(Hash, Hash)>

Decodes and verifies a JWT with the configured secret and algorithm.

Parameters:

  • token (String, nil) —

    the JWT

Returns:

  • (Array<(Hash, Hash)>) —

    payload and header, as returned by jwt

Raises:

  • (JWT::DecodeError) —

    if the signature, algorithm, or exp fail



53
54
55
56
57
# File 'lib/sorcery/model/submodules/jwt.rb', line 53

def decode_token(token)
  options = { algorithm: @sorcery_config.jwt_algorithm }
  options[:exp_leeway] = @sorcery_config.exp_leeway if @sorcery_config.exp_leeway
  JWT.decode(token, @sorcery_config.jwt_secret, true, options)
end

#issue_token(payload) ⇒ String

Encodes a JWT for a user, adding the exp and iat claims. Any claim in the payload except exp and iat is preserved.

Parameters:

  • payload (Hash) —

    claims to encode; must include "id" and "email" for the token to authenticate via the controller submodule

Returns:

  • (String) —

    the signed JWT



42
43
44
45
46
# File 'lib/sorcery/model/submodules/jwt.rb', line 42

def issue_token(payload)
  now = Time.now.to_i
  exp_payload = payload.merge(iat: now, exp: now + @sorcery_config.session_expiry)
  JWT.encode(exp_payload, @sorcery_config.jwt_secret, @sorcery_config.jwt_algorithm)
end

#token_valid?(token) ⇒ Boolean

Returns whether a JWT is validly signed and unexpired.

Parameters:

  • token (String, nil)

Returns:

  • (Boolean)


63
64
65
66
67
# File 'lib/sorcery/model/submodules/jwt.rb', line 63

def token_valid?(token)
  !!decode_token(token)
rescue JWT::DecodeError, JWT::ExpiredSignature
  false
end