Module: Devise::Models::TokenAuthenticatable

Defined in:
lib/devise/models/token_authenticatable.rb

Overview

Token Authenticatable Module, responsible for generate authentication token and validating authenticity of a user while signing in using an authentication token (say follows an URL).

Configuration:

You can overwrite configuration values by setting in globally in Devise (Devise.setup), using devise method, or overwriting the respective instance method.

token_authentication_key - Defines name of the authentication token params key. E.g. /users/sign_in?some_key=…

Examples:

User.authenticate_with_token(:auth_token => '123456789')           # returns authenticated user or nil
User.find(1).valid_authentication_token?('rI1t6PKQ8yP7VetgwdybB')  # returns true/false

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



21
22
23
24
25
26
# File 'lib/devise/models/token_authenticatable.rb', line 21

def self.included(base)
  base.class_eval do
    extend ClassMethods
    before_save :ensure_authentication_token
  end
end

Instance Method Details

#ensure_authentication_tokenObject

Generate authentication token unless already exists.



40
41
42
# File 'lib/devise/models/token_authenticatable.rb', line 40

def ensure_authentication_token
  self.reset_authentication_token if self.authentication_token.blank?
end

#ensure_authentication_token!Object

Generate authentication token unless already exists and save the record.



45
46
47
# File 'lib/devise/models/token_authenticatable.rb', line 45

def ensure_authentication_token!
  self.reset_authentication_token! if self.authentication_token.blank?
end

#reset_authentication_tokenObject

Generate new authentication token (a.k.a. “single access token”).



29
30
31
# File 'lib/devise/models/token_authenticatable.rb', line 29

def reset_authentication_token
  self.authentication_token = self.class.authentication_token
end

#reset_authentication_token!Object

Generate new authentication token and save the record.



34
35
36
37
# File 'lib/devise/models/token_authenticatable.rb', line 34

def reset_authentication_token!
  reset_authentication_token
  self.save
end

#valid_authentication_token?(incoming_auth_token) ⇒ Boolean

Verifies whether an incoming_authentication_token (i.e. from single access URL) is the user authentication token.

Returns:

  • (Boolean)


51
52
53
# File 'lib/devise/models/token_authenticatable.rb', line 51

def valid_authentication_token?(incoming_auth_token)
  incoming_auth_token.present? && incoming_auth_token == self.authentication_token
end