diff --git a/app/controllers/users/omniauth_callbacks_controller.rb b/app/controllers/users/omniauth_callbacks_controller.rb index 9983ee0..96dbd26 100644 --- a/app/controllers/users/omniauth_callbacks_controller.rb +++ b/app/controllers/users/omniauth_callbacks_controller.rb @@ -1,5 +1,55 @@ class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController + ## + # Dynamically build a handler for each omniauth provider + # ------------------------------------------------------------- + IdentifierScheme.all.each do |scheme| + define_method(scheme.name.downcase) do + handle_omniauth(scheme) + end + end + + ## + # Processes callbacks from an omniauth provider and directs the user to + # the appropriate page: + # Not logged in and uid had no match ---> Sign Up page + # Not logged in and uid had a match ---> Sign In and go to Home Page + # Signed in and uid had no match --> Save the uid and go to the Profile Page + # Signed in and uid had a match --> Go to the Home Page + # + # @scheme [IdentifierScheme] The IdentifierScheme for the provider + # ------------------------------------------------------------- + def handle_omniauth(scheme) + user = User.from_omniauth(request.env["omniauth.auth"]) + + # If the user isn't logged in + if current_user.nil? + session["devise.#{scheme.name.downcase}_data"] = request.env["omniauth.auth"] + + # If the uid didn't have a match in the system send them to register + if user.email.nil? + redirect_to new_user_registration_url + + # Otherwise sign them in + else + sign_in_and_redirect @user, event: :authentication + set_flash_message(:notice, :success, kind: scheme.name) if is_navigational_format? + end + + # The user is just registering the uid with us + else + # If the user could not be found by that uid then attach it to their record + if user.email.nil? || user.email.empty? + UserIdentifier.create!(identifier_scheme: scheme, + identifier: request.env["omniauth.auth"].uid, + user: current_user) + end + + redirect_to edit_user_registration_path + end + end + +=begin # We could consider combining these callbacks into a shared generic version # ------------------------------------------------------------- def orcid @@ -32,7 +82,8 @@ redirect_to edit_user_registration_path end end - +=end + # ------------------------------------------------------------- def shibboleth if user_signed_in? && current_user.shibboleth_id.present? && current_user.shibboleth_id.length > 0 then