diff --git a/app/controllers/agent_connect/agent_controller.rb b/app/controllers/agent_connect/agent_controller.rb index 718a866de..b24369c1b 100644 --- a/app/controllers/agent_connect/agent_controller.rb +++ b/app/controllers/agent_connect/agent_controller.rb @@ -1,3 +1,4 @@ +# doc: https://github.com/france-connect/Documentation-AgentConnect class AgentConnect::AgentController < ApplicationController def index end @@ -5,4 +6,35 @@ class AgentConnect::AgentController < ApplicationController def login redirect_to AgentConnectService.authorization_uri end + + def callback + user_info = AgentConnectService.user_info(params[:code]) + + instructeur = Instructeur.find_by(agent_connect_id: user_info['sub']) + + if instructeur.nil? + instructeur = Instructeur.find_by(users: { email: santized_email(user_info) }) + instructeur&.update(agent_connect_id: user_info['sub']) + end + + if instructeur.nil? + user = User.create_or_promote_to_instructeur(santized_email(user_info), Devise.friendly_token[0, 20]) + instructeur = user.instructeur + instructeur.update(agent_connect_id: user_info['sub']) + end + + sign_in(:user, instructeur.user) + + redirect_to instructeur_procedures_path + + rescue Rack::OAuth2::Client::Error => e + Rails.logger.error e.message + redirect_france_connect_error_connection + end + + private + + def santized_email(user_info) + user_info['email'].strip.downcase + end end diff --git a/app/models/agent_connect_client.rb b/app/models/agent_connect_client.rb index 45cab0bb0..f18eb4a63 100644 --- a/app/models/agent_connect_client.rb +++ b/app/models/agent_connect_client.rb @@ -1,5 +1,9 @@ class AgentConnectClient < OpenIDConnect::Client - def initialize + def initialize(code = nil) super(AGENT_CONNECT) + + if code.present? + self.authorization_code = code + end end end diff --git a/app/services/agent_connect_service.rb b/app/services/agent_connect_service.rb index 95d422f37..beefe3b99 100644 --- a/app/services/agent_connect_service.rb +++ b/app/services/agent_connect_service.rb @@ -13,4 +13,12 @@ class AgentConnectService acr_values: 'eidas1' ) end + + def self.user_info(code) + client = AgentConnectClient.new(code) + + client.access_token!(client_auth_method: :secret) + .userinfo! + .raw_attributes + end end diff --git a/config/routes.rb b/config/routes.rb index fa89733a0..3b4812185 100644 --- a/config/routes.rb +++ b/config/routes.rb @@ -132,6 +132,7 @@ Rails.application.routes.draw do namespace :agent_connect do get '' => 'agent#index' get 'login' => 'agent#login' + get 'callback' => 'agent#callback' end namespace :champs do