Class: HaveAPI::Authentication::Token::Provider
- Defined in:
- lib/haveapi/authentication/token/provider.rb
Overview
Provider for token authentication. This class has to be subclassed and implemented.
Token auth contains resource token. User can request a token by calling action Resources::Token::Request. Returned token is then used for authenticating the user. Client sends the token with each request in configured #http_header or #query_parameter.
Token can be revoked by calling Resources::Token::Revoke.
Example usage:
Token model:
class ApiToken < ActiveRecord::Base
belongs_to :user
validates :user_id, :token, presence: true
validates :token, length: {is: 100}
enum lifetime: %i(fixed renewable_manual renewable_auto permanent)
def renew
self.valid_to = Time.now + interval
end
end
Authentication provider:
class MyTokenAuth < HaveAPI::Authentication::Token::Provider
protected
def save_token(request, user, token, lifetime, interval)
user.tokens << ::Token.new(token: token, lifetime: lifetime,
valid_to: (lifetime != 'permanent' ? Time.now + interval : nil),
interval: interval, label: request.user_agent)
end
def revoke_token(request, user, token)
user.tokens.delete(token: token)
end
def renew_token(request, user, token)
t = ::Token.find_by(user: user, token: token)
if t.lifetime.start_with('renewable')
t.renew
t.save
t.valid_to
end
end
def find_user_by_credentials(request, username, password)
::User.find_by(login: username, password: password)
end
def find_user_by_token(request, token)
t = ::Token.find_by(token: token)
if t
# Renew the token if needed
if t.lifetime == 'renewable_auto'
t.renew
t.save
end
t.user # return the user
end
end
end
Finally put the provider in the authentication chain:
api = HaveAPI.new(...)
...
api.auth_chain << MyTokenAuth
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
Methods inherited from Base
Constructor Details
This class inherits a constructor from HaveAPI::Authentication::Base
Instance Method Details
#authenticate(request) ⇒ Object
89 90 91 92 93 |
# File 'lib/haveapi/authentication/token/provider.rb', line 89 def authenticate(request) t = token(request) t && find_user_by_token(request, t) end |
#describe ⇒ Object
99 100 101 102 103 104 |
# File 'lib/haveapi/authentication/token/provider.rb', line 99 def describe { http_header: http_header, query_parameter: query_parameter, } end |
#setup ⇒ Object
82 83 84 85 86 87 |
# File 'lib/haveapi/authentication/token/provider.rb', line 82 def setup Resources::Token.token_instance ||= {} Resources::Token.token_instance[@version] = self @server.allow_header(http_header) end |
#token(request) ⇒ Object
95 96 97 |
# File 'lib/haveapi/authentication/token/provider.rb', line 95 def token(request) request[query_parameter] || request.env[header_to_env] end |