2024-04-29 00:17:15 +02:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2020-08-05 18:40:47 +02:00
|
|
|
class APIEntrepriseToken
|
2022-02-07 11:42:44 +01:00
|
|
|
TokenError = Class.new(StandardError)
|
2020-05-05 15:26:08 +02:00
|
|
|
|
|
|
|
def initialize(token)
|
|
|
|
@token = token
|
|
|
|
end
|
|
|
|
|
2022-02-07 11:42:44 +01:00
|
|
|
def token
|
|
|
|
raise TokenError, I18n.t("api_entreprise.errors.missing_token") if @token.blank?
|
|
|
|
|
|
|
|
@token
|
2020-05-05 15:26:08 +02:00
|
|
|
end
|
|
|
|
|
|
|
|
def expired?
|
2022-02-07 11:42:44 +01:00
|
|
|
decoded_token.key?("exp") && decoded_token["exp"] <= Time.zone.now.to_i
|
2020-05-05 15:26:08 +02:00
|
|
|
end
|
|
|
|
|
2024-09-24 14:08:06 +02:00
|
|
|
def expiration
|
2024-09-27 16:49:23 +02:00
|
|
|
decoded_token.key?("exp") && Time.zone.at(decoded_token["exp"])
|
2024-09-24 14:08:06 +02:00
|
|
|
end
|
|
|
|
|
2020-05-05 15:26:08 +02:00
|
|
|
def role?(role)
|
|
|
|
roles.include?(role)
|
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
2022-02-07 11:42:44 +01:00
|
|
|
def roles
|
2023-01-03 15:31:08 +01:00
|
|
|
Array(decoded_token["roles"] || decoded_token["scopes"])
|
2022-02-07 11:42:44 +01:00
|
|
|
end
|
|
|
|
|
2020-05-05 15:26:08 +02:00
|
|
|
def decoded_token
|
2022-02-07 11:42:44 +01:00
|
|
|
@decoded_token ||= {}
|
|
|
|
@decoded_token[token] ||= JWT.decode(token, nil, false)[0]
|
|
|
|
rescue JWT::DecodeError => e
|
|
|
|
raise TokenError, e.message
|
2020-05-05 15:26:08 +02:00
|
|
|
end
|
|
|
|
end
|