Module: Jm81auth::Models::AuthToken::ClassMethods

Defined in:
lib/jm81auth/models/auth_token.rb

Instance Method Summary collapse

Instance Method Details

#configConfiguration

Returns:



114
115
116
# File 'lib/jm81auth/models/auth_token.rb', line 114

def config
  Jm81auth.config
end

#decode(token) ⇒ AuthToken

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

Parameters:

  • token (String)

    JWT encoded hash with AuthToken#id

Returns:

Raises:

  • (DecodeError)

    auth_token_id is missing or no AuthToken found.

See Also:



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# 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) ⇒ String

Encode a value using jwt_secret and jwt_algorithm.

Parameters:

  • value (Hash, Array)

Returns:

  • (String)

    Encoded value



87
88
89
# File 'lib/jm81auth/models/auth_token.rb', line 87

def encode value
  JWT.encode value, config.jwt_secret, config.jwt_algorithm
end

#use(token) ⇒ AuthToken

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

Parameters:

  • token (String)

    JWT encoded hash with AuthToken#id

Returns:

Raises:

  • (DecodeError)

    auth_token_id is missing or no AuthToken found.

See Also:



98
99
100
101
102
103
104
105
106
107
108
109
110
111
# 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