iachat/app/services/widget/token_service.rb
Pranav cc21016e6d
feat: Add support for customizing expiry of widget token (#12446)
This PR is part of https://github.com/chatwoot/chatwoot/pull/12259. It
adds a default expiry of 180 days for tokens issued on the widget. The
expiry can be customized based on customer requests and internal
security requirements.

Co-authored-by: Balasaheb Dubale <bdubale@entrata.com>
2025-09-16 12:41:05 +05:30

42 lines
800 B
Ruby

class Widget::TokenService
DEFAULT_EXPIRY_DAYS = 180
pattr_initialize [:payload, :token]
def generate_token
JWT.encode payload_with_expiry, secret_key, 'HS256'
end
def decode_token
JWT.decode(
token, secret_key, true, algorithm: 'HS256'
).first.symbolize_keys
rescue StandardError
{}
end
private
def payload_with_expiry
payload.merge(exp: exp, iat: iat)
end
def iat
Time.zone.now.to_i
end
def exp
iat + expire_in.days.to_i
end
def expire_in
# Value is stored in days, defaulting to 6 months (180 days)
token_expiry_value = InstallationConfig.find_by(name: 'WIDGET_TOKEN_EXPIRY')&.value
(token_expiry_value.presence || DEFAULT_EXPIRY_DAYS).to_i
end
def secret_key
Rails.application.secret_key_base
end
end