Module: AuthJwt::ControllerAdditions::InstanceMethods

Defined in:
lib/auth_jwt/controller_additions.rb

Overview

InstanceMethods to be included

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#current_userObject (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 
    (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 (credentials)
  user_class = AuthJwt.configuration.user_class.constantize
   = AuthJwt.configuration..to_sym
  password_field = AuthJwt.configuration.password_field.to_sym

  user = user_class.find_by( => credentials[])
  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_authObject

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.authorization.nil?
  user_class = AuthJwt.configuration.user_class.constantize
  begin
    user = user_class.from_jwe request.authorization
    if user
      @current_user = user
    else
      fail 'Not Found'
    end
  rescue
    raise AuthJwt::Unauthorized, 'Invalid token'
  end
end