demarches-normaliennes/app/services/agent_connect_service.rb

53 lines
1.3 KiB
Ruby
Raw Normal View History

# frozen_string_literal: true
2021-11-19 10:00:04 +01:00
class AgentConnectService
2022-04-11 13:11:54 +02:00
include OpenIDConnect
2021-11-19 10:00:04 +01:00
def self.enabled?
ENV['AGENT_CONNECT_BASE_URL'].present?
2021-11-19 10:00:04 +01:00
end
2021-11-19 10:21:47 +01:00
def self.authorization_uri
2024-03-19 14:42:40 +01:00
client = OpenIDConnect::Client.new(conf)
2021-11-19 10:21:47 +01:00
2022-04-11 13:11:04 +02:00
state = SecureRandom.hex(16)
2022-04-11 13:11:54 +02:00
nonce = SecureRandom.hex(16)
2022-04-11 13:11:04 +02:00
uri = client.authorization_uri(
2024-09-16 11:03:24 +02:00
scope: [:openid, :email, :given_name, :usual_name, :organizational_unit, :belonging_population, :siret, :idp_id],
state:,
nonce:,
acr_values: 'eidas1',
claims: { id_token: { amr: { essential: true } } }.to_json,
prompt: :login
2021-11-19 10:21:47 +01:00
)
2022-04-11 13:11:04 +02:00
2022-04-11 13:11:54 +02:00
[uri, state, nonce]
2021-11-19 10:21:47 +01:00
end
2021-11-19 15:24:54 +01:00
2022-04-11 13:11:54 +02:00
def self.user_info(code, nonce)
2024-03-19 14:42:40 +01:00
client = OpenIDConnect::Client.new(conf)
2024-03-18 17:36:25 +01:00
client.authorization_code = code
2021-11-19 15:24:54 +01:00
2022-04-11 13:11:54 +02:00
access_token = client.access_token!(client_auth_method: :secret)
2024-03-19 14:42:40 +01:00
id_token = ResponseObject::IdToken.decode(access_token.id_token, conf[:jwks])
id_token.verify!(conf.merge(nonce: nonce))
2022-04-11 13:11:54 +02:00
amr = id_token.amr.present? ? JSON.parse(id_token.amr) : []
[access_token.userinfo!.raw_attributes, access_token.id_token, amr]
2021-11-19 15:24:54 +01:00
end
2024-03-19 14:42:40 +01:00
private
# TODO: remove this block when migration to new domain is done
def self.conf
if Current.host.end_with?('.gouv.fr')
AGENT_CONNECT_GOUV
else
AGENT_CONNECT
end
end
2021-11-19 10:00:04 +01:00
end