omniauth_callbacks_controller.rb 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. # frozen_string_literal: true
  2. class Auth::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  3. skip_before_action :check_self_destruct!
  4. skip_before_action :verify_authenticity_token
  5. def self.provides_callback_for(provider)
  6. define_method provider do
  7. @provider = provider
  8. @user = User.find_for_oauth(request.env['omniauth.auth'], current_user)
  9. if @user.persisted?
  10. record_login_activity
  11. sign_in_and_redirect @user, event: :authentication
  12. set_flash_message(:notice, :success, kind: label_for_provider) if is_navigational_format?
  13. else
  14. session["devise.#{provider}_data"] = request.env['omniauth.auth']
  15. redirect_to new_user_registration_url
  16. end
  17. end
  18. end
  19. Devise.omniauth_configs.each_key do |provider|
  20. provides_callback_for provider
  21. end
  22. def after_sign_in_path_for(resource)
  23. if resource.email_present?
  24. stored_location_for(resource) || root_path
  25. else
  26. auth_setup_path(missing_email: '1')
  27. end
  28. end
  29. private
  30. def record_login_activity
  31. LoginActivity.create(
  32. user: @user,
  33. success: true,
  34. authentication_method: :omniauth,
  35. provider: @provider,
  36. ip: request.remote_ip,
  37. user_agent: request.user_agent
  38. )
  39. end
  40. def label_for_provider
  41. provider_display_name || configured_provider_name
  42. end
  43. def provider_display_name
  44. Devise.omniauth_configs[@provider]&.strategy&.display_name.presence
  45. end
  46. def configured_provider_name
  47. I18n.t("auth.providers.#{@provider}", default: @provider.to_s.chomp('_oauth2').capitalize)
  48. end
  49. end