PageRenderTime 40ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/app/controllers/omniauth_callbacks_controller.rb

https://gitlab.com/axil/gitlab
Ruby | 292 lines | 219 code | 66 blank | 7 comment | 29 complexity | a51e06bd3ecffdc6121c1bf5eaf12812 MD5 | raw file
  1. # frozen_string_literal: true
  2. class OmniauthCallbacksController < Devise::OmniauthCallbacksController
  3. include AuthenticatesWithTwoFactorForAdminMode
  4. include Devise::Controllers::Rememberable
  5. include AuthHelper
  6. include InitializesCurrentUserMode
  7. include KnownSignIn
  8. after_action :verify_known_sign_in
  9. protect_from_forgery except: [:kerberos, :saml, :cas3, :failure], with: :exception, prepend: true
  10. feature_category :authentication_and_authorization
  11. def handle_omniauth
  12. omniauth_flow(Gitlab::Auth::OAuth)
  13. end
  14. AuthHelper.providers_for_base_controller.each do |provider|
  15. alias_method provider, :handle_omniauth
  16. end
  17. # Extend the standard implementation to also increment
  18. # the number of failed sign in attempts
  19. def failure
  20. if params[:username].present? && AuthHelper.form_based_provider?(failed_strategy.name)
  21. user = User.by_login(params[:username])
  22. user&.increment_failed_attempts!
  23. log_failed_login(params[:username], failed_strategy.name)
  24. end
  25. super
  26. end
  27. # Extend the standard message generation to accept our custom exception
  28. def failure_message
  29. exception = request.env["omniauth.error"]
  30. error = exception.error_reason if exception.respond_to?(:error_reason)
  31. error ||= exception.error if exception.respond_to?(:error)
  32. error ||= exception.message if exception.respond_to?(:message)
  33. error ||= request.env["omniauth.error.type"].to_s
  34. error.to_s.humanize if error
  35. end
  36. def saml
  37. omniauth_flow(Gitlab::Auth::Saml)
  38. rescue Gitlab::Auth::Saml::IdentityLinker::UnverifiedRequest
  39. redirect_unverified_saml_initiation
  40. end
  41. def cas3
  42. ticket = params['ticket']
  43. if ticket
  44. handle_service_ticket oauth['provider'], ticket
  45. end
  46. handle_omniauth
  47. end
  48. def authentiq
  49. if params['sid']
  50. handle_service_ticket oauth['provider'], params['sid']
  51. end
  52. handle_omniauth
  53. end
  54. def auth0
  55. if oauth['uid'].blank?
  56. fail_auth0_login
  57. else
  58. handle_omniauth
  59. end
  60. end
  61. def salesforce
  62. if oauth.dig('extra', 'email_verified')
  63. handle_omniauth
  64. else
  65. fail_salesforce_login
  66. end
  67. end
  68. def atlassian_oauth2
  69. omniauth_flow(Gitlab::Auth::Atlassian)
  70. end
  71. private
  72. def log_failed_login(user, provider)
  73. # overridden in EE
  74. end
  75. def after_omniauth_failure_path_for(scope)
  76. if Feature.enabled?(:user_mode_in_session)
  77. return new_admin_session_path if current_user_mode.admin_mode_requested?
  78. end
  79. super
  80. end
  81. def omniauth_flow(auth_module, identity_linker: nil)
  82. if fragment = request.env.dig('omniauth.params', 'redirect_fragment').presence
  83. store_redirect_fragment(fragment)
  84. end
  85. if current_user
  86. return render_403 unless link_provider_allowed?(oauth['provider'])
  87. log_audit_event(current_user, with: oauth['provider'])
  88. if Feature.enabled?(:user_mode_in_session)
  89. return admin_mode_flow(auth_module::User) if current_user_mode.admin_mode_requested?
  90. end
  91. identity_linker ||= auth_module::IdentityLinker.new(current_user, oauth, session)
  92. link_identity(identity_linker)
  93. if identity_linker.changed?
  94. redirect_identity_linked
  95. elsif identity_linker.failed?
  96. redirect_identity_link_failed(identity_linker.error_message)
  97. else
  98. redirect_identity_exists
  99. end
  100. else
  101. sign_in_user_flow(auth_module::User)
  102. end
  103. end
  104. def link_identity(identity_linker)
  105. identity_linker.link
  106. end
  107. def redirect_identity_exists
  108. redirect_to after_sign_in_path_for(current_user)
  109. end
  110. def redirect_identity_link_failed(error_message)
  111. redirect_to profile_account_path, notice: _("Authentication failed: %{error_message}") % { error_message: error_message }
  112. end
  113. def redirect_identity_linked
  114. redirect_to profile_account_path, notice: _('Authentication method updated')
  115. end
  116. def handle_service_ticket(provider, ticket)
  117. Gitlab::Auth::OAuth::Session.create provider, ticket
  118. session[:service_tickets] ||= {}
  119. session[:service_tickets][provider] = ticket
  120. end
  121. def build_auth_user(auth_user_class)
  122. auth_user_class.new(oauth)
  123. end
  124. def sign_in_user_flow(auth_user_class)
  125. auth_user = build_auth_user(auth_user_class)
  126. user = auth_user.find_and_update!
  127. if auth_user.valid_sign_in?
  128. log_audit_event(user, with: oauth['provider'])
  129. set_remember_me(user)
  130. if user.two_factor_enabled? && !auth_user.bypass_two_factor?
  131. prompt_for_two_factor(user)
  132. else
  133. if user.deactivated?
  134. user.activate
  135. flash[:notice] = _('Welcome back! Your account had been deactivated due to inactivity but is now reactivated.')
  136. end
  137. sign_in_and_redirect(user, event: :authentication)
  138. end
  139. else
  140. fail_login(user)
  141. end
  142. rescue Gitlab::Auth::OAuth::User::SigninDisabledForProviderError
  143. handle_disabled_provider
  144. rescue Gitlab::Auth::OAuth::User::SignupDisabledError
  145. handle_signup_error
  146. end
  147. def handle_signup_error
  148. label = Gitlab::Auth::OAuth::Provider.label_for(oauth['provider'])
  149. message = [_("Signing in using your %{label} account without a pre-existing GitLab account is not allowed.") % { label: label }]
  150. if Gitlab::CurrentSettings.allow_signup?
  151. message << _("Create a GitLab account first, and then connect it to your %{label} account.") % { label: label }
  152. end
  153. flash[:alert] = message.join(' ')
  154. redirect_to new_user_session_path
  155. end
  156. def oauth
  157. @oauth ||= request.env['omniauth.auth']
  158. end
  159. def fail_login(user)
  160. log_failed_login(user.username, oauth['provider'])
  161. @provider = Gitlab::Auth::OAuth::Provider.label_for(params[:action])
  162. @error = user.errors.full_messages.to_sentence
  163. render 'errors/omniauth_error', layout: "oauth_error", status: :unprocessable_entity
  164. end
  165. def fail_auth0_login
  166. fail_login_with_message(_('Wrong extern UID provided. Make sure Auth0 is configured correctly.'))
  167. end
  168. def fail_salesforce_login
  169. fail_login_with_message(_('Email not verified. Please verify your email in Salesforce.'))
  170. end
  171. def fail_login_with_message(message)
  172. flash[:alert] = message
  173. redirect_to new_user_session_path
  174. end
  175. def redirect_unverified_saml_initiation
  176. redirect_to profile_account_path, notice: _('Request to link SAML account must be authorized')
  177. end
  178. def handle_disabled_provider
  179. label = Gitlab::Auth::OAuth::Provider.label_for(oauth['provider'])
  180. flash[:alert] = _("Signing in using %{label} has been disabled") % { label: label }
  181. redirect_to new_user_session_path
  182. end
  183. def log_audit_event(user, options = {})
  184. AuditEventService.new(user, user, options)
  185. .for_authentication.security_event
  186. end
  187. def set_remember_me(user)
  188. return unless remember_me?
  189. if user.two_factor_enabled?
  190. params[:remember_me] = '1'
  191. else
  192. remember_me(user)
  193. end
  194. end
  195. def remember_me?
  196. request_params = request.env['omniauth.params']
  197. (request_params['remember_me'] == '1') if request_params.present?
  198. end
  199. def store_redirect_fragment(redirect_fragment)
  200. key = stored_location_key_for(:user)
  201. location = session[key]
  202. if uri = parse_uri(location)
  203. uri.fragment = redirect_fragment
  204. store_location_for(:user, uri.to_s)
  205. end
  206. end
  207. def admin_mode_flow(auth_user_class)
  208. auth_user = build_auth_user(auth_user_class)
  209. return fail_admin_mode_invalid_credentials unless omniauth_identity_matches_current_user?
  210. if current_user.two_factor_enabled? && !auth_user.bypass_two_factor?
  211. admin_mode_prompt_for_two_factor(current_user)
  212. else
  213. # Can only reach here if the omniauth identity matches current user
  214. # and current_user is an admin that requested admin mode
  215. current_user_mode.enable_admin_mode!(skip_password_validation: true)
  216. redirect_to stored_location_for(:redirect) || admin_root_path, notice: _('Admin mode enabled')
  217. end
  218. end
  219. def omniauth_identity_matches_current_user?
  220. current_user.matches_identity?(oauth['provider'], oauth['uid'])
  221. end
  222. def fail_admin_mode_invalid_credentials
  223. redirect_to new_admin_session_path, alert: _('Invalid login or password')
  224. end
  225. end
  226. OmniauthCallbacksController.prepend_if_ee('EE::OmniauthCallbacksController')