demarches-normaliennes/app/services/agent_connect_service.rb

47 lines
1.1 KiB
Ruby
Raw Normal View History

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(
scope: [:openid, :email, :given_name, :usual_name, :organizational_unit, :belonging_population, :siret],
state:,
nonce:,
2021-11-19 10:21:47 +01:00
acr_values: 'eidas1'
)
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-03-18 10:35:41 +01:00
[access_token.userinfo!.raw_attributes, access_token.id_token]
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