2017-08-30 00:49:07 +08:00
|
|
|
module Api
|
|
|
|
class CoreJwt
|
|
|
|
require 'jwt'
|
|
|
|
KEY_SECRET = Rails.application.secrets.secret_key_base
|
|
|
|
|
|
|
|
def self.encode(payload, expires_at = nil)
|
|
|
|
if expires_at
|
|
|
|
payload[:exp] = expires_at
|
|
|
|
else
|
2019-11-26 22:09:40 +08:00
|
|
|
payload[:exp] = Rails.configuration.x.core_api_token_ttl.from_now.to_i
|
2017-08-30 00:49:07 +08:00
|
|
|
end
|
2019-11-26 22:09:40 +08:00
|
|
|
payload[:iss] = Rails.configuration.x.core_api_token_iss
|
2023-07-18 15:22:39 +08:00
|
|
|
payload[:salt] = SecureRandom.base64(30)
|
2019-11-26 22:09:40 +08:00
|
|
|
JWT.encode(payload, KEY_SECRET, Rails.configuration.x.core_api_sign_alg)
|
2017-08-30 00:49:07 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def self.decode(token)
|
|
|
|
HashWithIndifferentAccess.new(
|
2019-11-26 22:09:40 +08:00
|
|
|
JWT.decode(token, KEY_SECRET, Rails.configuration.x.core_api_sign_alg)[0]
|
2017-08-30 00:49:07 +08:00
|
|
|
)
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.read_iss(token)
|
|
|
|
HashWithIndifferentAccess.new(
|
|
|
|
JWT.decode(token, nil, false)[0]
|
|
|
|
)[:iss].to_s
|
|
|
|
end
|
|
|
|
|
2018-08-17 17:59:47 +08:00
|
|
|
# Method used by Doorkeeper for custom tokens
|
|
|
|
def self.generate(options = {})
|
|
|
|
encode(
|
2018-10-28 21:34:51 +08:00
|
|
|
{ sub: options[:resource_owner_id] },
|
2018-08-17 17:59:47 +08:00
|
|
|
options[:expires_in].seconds.from_now.to_i
|
|
|
|
)
|
|
|
|
end
|
2017-08-30 00:49:07 +08:00
|
|
|
end
|
|
|
|
end
|