Class: ApiAuthenticationGem::Auth

Inherits:
Object
  • Object
show all
Defined in:
lib/api_authentication_gem/auth.rb

Class Method Summary collapse

Class Method Details

.decode(token) ⇒ Object

Decode the JWT token and retrieve the payload



22
23
24
25
26
27
# File 'lib/api_authentication_gem/auth.rb', line 22

def self.decode(token)
  decoded = JWT.decode(token, ApiAuthenticationGem.configuration.secret_key, true, algorithm: 'HS256')
  decoded.first # The payload is in the first element
rescue JWT::DecodeError => e
  nil # If the token is invalid, return nil
end

.login(email:, password:) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/api_authentication_gem/auth.rb', line 11

def self.(email:, password:)
  user_class = ApiAuthenticationGem.configuration.user_class.constantize
  user = user_class.find_by(email: email)
  return nil unless user&.authenticate(password)

  token = generate_token(user.id)
  { token: token, user: user }
end

.signup(email:, password:) ⇒ Object



4
5
6
7
8
9
# File 'lib/api_authentication_gem/auth.rb', line 4

def self.(email:, password:)
  user_class = ApiAuthenticationGem.configuration.user_class.constantize
  user = user_class.create!(email: email, password: password)
  token = generate_token(user.id)
  { token: token, user: user }
end