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



49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/rubee/controllers/extensions/auth_tokenable.rb', line 49

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)


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

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



38
39
40
41
42
43
44
45
46
47
# File 'lib/rubee/controllers/extensions/auth_tokenable.rb', line 38

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



73
74
75
76
77
78
79
# File 'lib/rubee/controllers/extensions/auth_tokenable.rb', line 73

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

#unauthentificate!Object



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

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)


34
35
36
# File 'lib/rubee/controllers/extensions/auth_tokenable.rb', line 34

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