module Jm81auth::Models::AuthToken::ClassMethods

Public Instance Methods

config() click to toggle source

@return [Configuration]

# File lib/jm81auth/models/auth_token.rb, line 114
def config
  Jm81auth.config
end
decode(token) click to toggle source

Decode a JWT token and get AuthToken based on stored ID.

@see encoded @param token [String] JWT encoded hash with AuthToken#id @raise [DecodeError] auth_token_id is missing or no AuthToken found. @return [AuthToken]

# File lib/jm81auth/models/auth_token.rb, line 63
def decode token
  payload = JWT.decode(
    token, config.jwt_secret, config.jwt_algorithm
  ).first

  if self.respond_to? :[]
    auth_token = self[payload['auth_token_id']]
  else
    auth_token = find payload['auth_token_id']
  end

  if payload['auth_token_id'].nil?
    raise DecodeError, "auth_token_id missing: #{payload}"
  elsif auth_token.nil?
    raise DecodeError, "auth_token_id not found: #{payload}"
  end

  auth_token
end
encode(value) click to toggle source

Encode a value using jwt_secret and jwt_algorithm.

@param value [Hash, Array] @return [String] Encoded value

# File lib/jm81auth/models/auth_token.rb, line 87
def encode value
  JWT.encode value, config.jwt_secret, config.jwt_algorithm
end
use(token) click to toggle source

Decode a JWT token and get AuthToken based on stored ID. If an open AuthToken is found, update its last_used_at value.

@see decode @param token [String] JWT encoded hash with AuthToken#id @raise [DecodeError] auth_token_id is missing or no AuthToken found. @return [AuthToken]

# File lib/jm81auth/models/auth_token.rb, line 98
def use token
  auth_token = decode token

  if auth_token && !auth_token.expired?
    if respond_to? :update_attributes!
      auth_token.update_attributes! last_used_at: Time.now
    else
      auth_token.update last_used_at: Time.now
    end
    auth_token
  else
    nil
  end
end