Module: Rubee::AuthTokenable::InstanceMethods

Defined in:
lib/rubee/controllers/extensions/auth_tokenable.rb

Instance Method Summary collapse

Instance Method Details

#authentificate!(user_model: ::User, login: :email, password: :password) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/rubee/controllers/extensions/auth_tokenable.rb', line 41

def authentificate!(user_model: ::User, login: :email, password: :password)
  return false unless authentificated_user(user_model:, login:, password:)

  # Generate token
  payload = { login: {  => params[] }, klass: user_model.name, exp: Time.now.to_i + EXPIRE }
  @token = ::JWT.encode(payload, KEY, 'HS256')
  # Set jwt token to the browser within cookie, so next browser request will include it.
  # make sure it passed to response_with headers options
  @token_header = { 'set-cookie' => "jwt=#{@token}; path=/; httponly; secure" }

  true
end

#authentificated?Boolean

Returns:

  • (Boolean)


18
19
20
21
22
23
24
# File 'lib/rubee/controllers/extensions/auth_tokenable.rb', line 18

def authentificated?
  methods = self.class._auth_methods
  return true if methods && !methods.include?(@route[:action].to_sym)

  # This is suppose to be set in the middleware, otherwise it will return false
  valid_token?
end

#authentificated_user(user_model: ::User, login: :email, password: :password) ⇒ Object



30
31
32
33
34
35
36
37
38
39
# File 'lib/rubee/controllers/extensions/auth_tokenable.rb', line 30

def authentificated_user(user_model: ::User, login: :email, password: :password)
  if params[] && params[password]
    query_params = {  => params[], password => params[password] }
    @authentificated_user ||= user_model.where(query_params).first
  elsif @request.cookies['jwt'] && valid_token?
    token = @request.cookies['jwt']
    hash = ::JWT.decode(token, Rubee::AuthTokenable::KEY, true, { algorithm: 'HS256' })
    @authentificated_user ||= user_model.where( => hash[0]["login"][.to_s]).first
  end
end

#handle_authObject



65
66
67
68
69
70
71
# File 'lib/rubee/controllers/extensions/auth_tokenable.rb', line 65

def handle_auth
  if authentificated?
    yield
  else
    response_with(type: :unauthentificated)
  end
end

#unauthentificate!Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/rubee/controllers/extensions/auth_tokenable.rb', line 54

def unauthentificate!
  @request.env['rack.session']['authentificated'] = nil if @request.env['rack.session']&.[]('authentificated')
  @authehtificated_user = nil if @authehtificated_user
  @zeroed_token_header = {
    'set-cookie' => 'jwt=; path=/; httponly; secure; expires=thu, 01 jan 1970 00:00:00 gmt',
    'content-type' => 'application/json',
  }

  true
end

#valid_token?Boolean

Returns:

  • (Boolean)


26
27
28
# File 'lib/rubee/controllers/extensions/auth_tokenable.rb', line 26

def valid_token?
  @request.env['rack.session']&.[]('authentificated')
end