Class: JwtAuthenticate
- Inherits:
-
Object
- Object
- JwtAuthenticate
- 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
-
.decode(token) ⇒ ActiveSupport::HashWithIndifferentAccess
Decodes a JWT token and returns the payload as a hash.
-
.encode(payload, exp = DEFAULT_EXPIRATION.from_now) ⇒ String
Encodes a payload into a JWT token with an expiration time.
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.
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.
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 |