Module: Agilib::TokenAuthenticationHandlerMethods

Extended by:
ActiveSupport::Concern
Defined in:
lib/agilib/token_authenticatable/token_authentication_handler.rb

Instance Method Summary collapse

Instance Method Details

#authenticate_user_from_token!Object

For this example, we are simply using token authentication via parameters. However, anyone could use Rails’s token authentication features to get the token from a header.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/agilib/token_authenticatable/token_authentication_handler.rb', line 19

def authenticate_user_from_token!
  param_user_token    = params[Agilib::TokenAuthenticatable.auth_params[:user_token]]
  param_email_token   = params[Agilib::TokenAuthenticatable.auth_params[:user_email]]

  # Set the authentication token params if not already present,
  # see http://stackoverflow.com/questions/11017348/rails-api-authentication-by-headers-token
  if user_token = param_user_token.blank? && request.headers["X-User-Token"]
    param_user_token = user_token
  end
  if user_email = params[Agilib::TokenAuthenticatable.auth_params[:user_email]].blank? && request.headers["X-User-Email"]
    param_email_token = user_email
  end

  user_email = param_email_token.presence
  # See https://github.com/ryanb/cancan/blob/1.6.10/lib/cancan/controller_resource.rb#L108-L111
  if User.respond_to? "find_by"
    user = user_email && User.find_by(email: user_email)
  elsif User.respond_to? "find_by_email"
    user = user_email && User.find_by_email(user_email)
  end

  # Notice how we use Devise.secure_compare to compare the token
  # in the database with the token given in the params, mitigating
  # timing attacks.
  if user && Devise.secure_compare(user.authentication_token, param_user_token)
    # Notice we are passing store false, so the user is not
    # actually stored in the session and a token is needed
    # for every request. If you want the token to work as a
    # sign in token, you can simply remove store: false.
     user, store: false
  end
end