demarches-normaliennes/app/controllers/agent_connect/agent_controller.rb

73 lines
2 KiB
Ruby
Raw Normal View History

2021-11-19 15:24:54 +01:00
# doc: https://github.com/france-connect/Documentation-AgentConnect
2021-11-19 10:00:04 +01:00
class AgentConnect::AgentController < ApplicationController
2021-11-19 15:24:54 +01:00
before_action :redirect_to_login_if_fc_aborted, only: [:callback]
2022-04-11 13:11:04 +02:00
before_action :check_state, only: [:callback]
STATE_COOKIE_NAME = :agentConnect_state
2022-04-11 13:11:54 +02:00
NONCE_COOKIE_NAME = :agentConnect_nonce
2021-11-19 15:24:54 +01:00
2021-11-19 10:00:04 +01:00
def index
end
2021-11-19 10:21:47 +01:00
def login
2022-04-11 13:11:54 +02:00
uri, state, nonce = AgentConnectService.authorization_uri
2022-04-11 13:11:04 +02:00
cookies.encrypted[STATE_COOKIE_NAME] = state
2022-04-11 13:11:54 +02:00
cookies.encrypted[NONCE_COOKIE_NAME] = nonce
2022-04-11 13:11:04 +02:00
redirect_to uri, allow_other_host: true
2021-11-19 10:21:47 +01:00
end
2021-11-19 15:24:54 +01:00
def callback
2022-04-11 13:11:54 +02:00
user_info = AgentConnectService.user_info(params[:code], cookies.encrypted[NONCE_COOKIE_NAME])
cookies.encrypted[NONCE_COOKIE_NAME] = nil
2021-11-19 15:24:54 +01:00
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
2021-11-19 15:24:54 +01:00
def redirect_to_login_if_fc_aborted
if params[:code].blank?
redirect_to new_user_session_path
end
end
def redirect_france_connect_error_connection
flash.alert = t('errors.messages.france_connect.connexion')
redirect_to(new_user_session_path)
end
2022-04-11 13:11:04 +02:00
def check_state
if cookies.encrypted[STATE_COOKIE_NAME] != params[:state]
flash.alert = t('errors.messages.france_connect.connexion')
redirect_to(new_user_session_path)
else
cookies.encrypted[STATE_COOKIE_NAME] = nil
end
end
2021-11-19 10:00:04 +01:00
end