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
|
|
|
|
|
|
|
|
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
|