2024-04-29 00:17:15 +02:00
|
|
|
# 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?
|
2024-03-19 18:10:59 +01:00
|
|
|
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],
|
2023-12-12 15:02:22 +01:00
|
|
|
state:,
|
|
|
|
nonce:,
|
2024-09-11 10:18:46 +02:00
|
|
|
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
|
|
|
|
2024-09-11 10:18:46 +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
|
|
|
|
2024-09-16 12:10:55 +02:00
|
|
|
def self.logout_url(id_token, host_with_port:)
|
|
|
|
app_logout = Rails.application.routes.url_helpers.logout_url(host: host_with_port)
|
|
|
|
h = { id_token_hint: id_token, post_logout_redirect_uri: app_logout }
|
|
|
|
"#{AGENT_CONNECT[:end_session_endpoint]}?#{h.to_query}"
|
|
|
|
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
|