|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "devise" |
| 4 | + |
| 5 | +module ActiveAdmin |
| 6 | + module Oidc |
| 7 | + module Devise |
| 8 | + # Handles the OAuth callback from the IdP. Wiring: |
| 9 | + # |
| 10 | + # # config/routes.rb (or inside ActiveAdmin::Devise.config) |
| 11 | + # devise_for :admin_users, ActiveAdmin::Devise.config.merge( |
| 12 | + # controllers: { |
| 13 | + # omniauth_callbacks: "active_admin/oidc/devise/omniauth_callbacks" |
| 14 | + # } |
| 15 | + # ) |
| 16 | + # |
| 17 | + # The action name matches the provider name registered with Devise |
| 18 | + # (`:oidc`, from ActiveAdmin::Oidc::Engine::PROVIDER_NAME). |
| 19 | + class OmniauthCallbacksController < ::Devise::OmniauthCallbacksController |
| 20 | + def oidc |
| 21 | + auth = request.env["omniauth.auth"] || {} |
| 22 | + info = auth["info"] || {} |
| 23 | + extra = auth.dig("extra", "raw_info") || {} |
| 24 | + |
| 25 | + claims = extra.to_h.transform_keys(&:to_s) |
| 26 | + claims["sub"] = auth["uid"] if claims["sub"].blank? && auth["uid"].present? |
| 27 | + claims["email"] = info["email"] if claims["email"].blank? && info["email"].present? |
| 28 | + |
| 29 | + admin_user = UserProvisioner.new( |
| 30 | + ActiveAdmin::Oidc.config, |
| 31 | + claims: claims, |
| 32 | + provider: ActiveAdmin::Oidc::Engine::PROVIDER_NAME.to_s |
| 33 | + ).call |
| 34 | + |
| 35 | + sign_in_and_redirect admin_user, event: :authentication |
| 36 | + set_flash_message(:notice, :success, kind: "OIDC") if is_navigational_format? |
| 37 | + rescue ActiveAdmin::Oidc::ProvisioningError => e |
| 38 | + Rails.logger.warn("[activeadmin-oidc] denial: #{e.message}") |
| 39 | + flash[:alert] = ActiveAdmin::Oidc.config.access_denied_message |
| 40 | + redirect_to after_omniauth_failure_path_for(resource_name) |
| 41 | + end |
| 42 | + |
| 43 | + def failure |
| 44 | + Rails.logger.warn("[activeadmin-oidc] omniauth failure: #{failure_message}") |
| 45 | + flash[:alert] = ActiveAdmin::Oidc.config.access_denied_message |
| 46 | + redirect_to after_omniauth_failure_path_for(resource_name) |
| 47 | + end |
| 48 | + end |
| 49 | + end |
| 50 | + end |
| 51 | +end |
0 commit comments