Module: SimpleTokenAuthentication::ActsAsTokenAuthenticationHandlerMethods
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/simple_token_authentication/acts_as_token_authentication_handler.rb
Class Method Summary collapse
Instance Method Summary collapse
- #authenticate_entity! ⇒ Object
-
#authenticate_entity_from_token! ⇒ Object
For this example, we are simply using token authentication via parameters.
Class Method Details
.set_entity(entity) ⇒ Object
60 61 62 |
# File 'lib/simple_token_authentication/acts_as_token_authentication_handler.rb', line 60 def self.set_entity entity @@entity = entity end |
Instance Method Details
#authenticate_entity! ⇒ Object
16 17 18 19 |
# File 'lib/simple_token_authentication/acts_as_token_authentication_handler.rb', line 16 def authenticate_entity! # Caution: entity should be a singular camel-cased name but could be pluralized or underscored. self.method("authenticate_#{@@entity.name.singularize.underscore}!".to_sym).call end |
#authenticate_entity_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.
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 51 52 53 54 55 56 57 58 |
# File 'lib/simple_token_authentication/acts_as_token_authentication_handler.rb', line 25 def authenticate_entity_from_token! # Set the authentication token params if not already present, # see http://stackoverflow.com/questions/11017348/rails-api-authentication-by-headers-token params_token_name = "#{@@entity.name.singularize.underscore}_token".to_sym params_email_name = "#{@@entity.name.singularize.underscore}_email".to_sym header_token_name = "X-#{@@entity.name.singularize.camelize}-Token" header_email_name = "X-#{@@entity.name.singularize.camelize}-Email" if token = params[params_token_name].blank? && request.headers[header_token_name] params[params_token_name] = token end if email = params[params_email_name].blank? && request.headers[header_email_name] params[params_email_name] = email end email = params[params_email_name].presence # See https://github.com/ryanb/cancan/blob/1.6.10/lib/cancan/controller_resource.rb#L108-L111 entity = nil if @@entity.respond_to? "find_by" entity = email && @@entity.find_by(email: email) elsif @@entity.respond_to? "find_by_email" entity = email && @@entity.find_by_email(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 entity && Devise.secure_compare(entity.authentication_token, params[params_token_name]) # Notice we are passing store false, so the entity 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. sign_in entity, store: false end end |