Module: AuthJwt::ControllerAdditions::InstanceMethods
- Defined in:
- lib/auth_jwt/controller_additions.rb
Overview
InstanceMethods to be included
Instance Attribute Summary collapse
-
#current_user ⇒ Object
readonly
The current user or nil if not authenticated.
Instance Method Summary collapse
-
#login_user(credentials) ⇒ Object
Sets up a method to check a user credentials.
-
#require_auth ⇒ Object
Sets up a method to check if the user is authenticated.
Instance Attribute Details
#current_user ⇒ Object (readonly)
The current user or nil if not authenticated
14 15 16 |
# File 'lib/auth_jwt/controller_additions.rb', line 14 def current_user @current_user end |
Instance Method Details
#login_user(credentials) ⇒ Object
Sets up a method to check a user credentials
return the authenticated user or raise AuthJwt::Unauthorized
“‘ruby
class AnyController < ApplicationController
def login
login_user(credentials)
end
end
“‘
28 29 30 31 32 33 34 35 36 37 38 39 40 |
# File 'lib/auth_jwt/controller_additions.rb', line 28 def login_user(credentials) user_class = AuthJwt.configuration.user_class.constantize login_field = AuthJwt.configuration.login_field.to_sym password_field = AuthJwt.configuration.password_field.to_sym user = user_class.find_by(login_field => credentials[login_field]) if user fail AuthJwt::Unauthorized, 'Invalid credentials' unless user.authenticate(credentials[password_field]) @current_user = user else fail AuthJwt::Unauthorized, 'Invalid user' end end |
#require_auth ⇒ Object
Sets up a method to check if the user is authenticated
-
if the user is authenticated setup current_user
-
if the user is not authenticated, raise AuthJwt::Unauthorized
“‘ruby
class AnyController < ApplicationController
before_filter :require_auth
end
“‘
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
# File 'lib/auth_jwt/controller_additions.rb', line 52 def require_auth fail 'not in a controller scope' if request.nil? fail AuthJwt::Unauthorized, 'No Auth' if request..nil? user_class = AuthJwt.configuration.user_class.constantize begin user = user_class.from_jwe request. if user @current_user = user else fail 'Not Found' end rescue raise AuthJwt::Unauthorized, 'Invalid token' end end |