Class: JwtAuthenticate

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

Overview

This class provides methods to encode and decode JWT tokens. It uses the Rails application’s secret key base for signing the tokens. The tokens can be used for user authentication, allowing users to remain logged in for a specified duration. The default expiration time is set to 24 hours, but this can be adjusted as needed.

Constant Summary collapse

SECRET_KEY =
Rails.application.secret_key_base
DEFAULT_EXPIRATION =

This will logout the user from app after 24 hours. Change this value to keep the user logged in for more time.

24.hours

Class Method Summary collapse

Class Method Details

.decode(token) ⇒ ActiveSupport::HashWithIndifferentAccess

Decodes a JWT token and returns the payload as a hash. If the token is invalid or cannot be decoded, it returns an empty hash.

Parameters:

  • token (String)

    The JWT token to decode.

Returns:

  • (ActiveSupport::HashWithIndifferentAccess)

    The decoded payload as a hash with indifferent access.



30
31
32
33
34
35
# File 'lib/jwt_authenticate.rb', line 30

def decode(token)
  body = JWT.decode(token, SECRET_KEY)[0]
  HashWithIndifferentAccess.new body
rescue
  HashWithIndifferentAccess.new
end

.encode(payload, exp = DEFAULT_EXPIRATION.from_now) ⇒ String

Encodes a payload into a JWT token with an expiration time. The payload should include user-specific information, such as user_id. The expiration time defaults to 24 hours from the current time.

Parameters:

  • payload (Hash)

    The payload to encode in the JWT token.

  • exp (Time) (defaults to: DEFAULT_EXPIRATION.from_now)

    The expiration time for the token. Defaults to 24 hours from now.

Returns:

  • (String)

    The encoded JWT token.



21
22
23
24
# File 'lib/jwt_authenticate.rb', line 21

def encode(payload, exp = DEFAULT_EXPIRATION.from_now)
  payload[:exp] = exp.to_i
  JWT.encode(payload, SECRET_KEY)
end