BigW Consortium Gitlab

omniauth_callbacks_controller.rb 1.6 KB
Newer Older
vsizov committed
1
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
2
  Gitlab.config.omniauth.providers.each do |provider|
3 4 5 6
    define_method provider['name'] do
      handle_omniauth
    end
  end
7 8 9 10

  # Extend the standard message generation to accept our custom exception
  def failure_message
    exception = env["omniauth.error"]
11 12 13 14
    error   = exception.error_reason if exception.respond_to?(:error_reason)
    error ||= exception.error        if exception.respond_to?(:error)
    error ||= exception.message      if exception.respond_to?(:message)
    error ||= env["omniauth.error.type"].to_s
15 16
    error.to_s.humanize if error
  end
Florian Unglaub committed
17

vsizov committed
18
  def ldap
19 20
    # We only find ourselves here
    # if the authentication to LDAP was successful.
21
    @user = Gitlab::LDAP::User.find_or_create(oauth)
22 23
    @user.remember_me = true if @user.persisted?
    sign_in_and_redirect(@user)
vsizov committed
24 25
  end

Florian Unglaub committed
26 27 28 29 30
  private

  def handle_omniauth
    if current_user
      # Change a logged-in user's authentication method:
31 32
      current_user.extern_uid = oauth['uid']
      current_user.provider = oauth['provider']
Florian Unglaub committed
33 34 35
      current_user.save
      redirect_to profile_path
    else
36 37 38 39 40 41 42
      @user = Gitlab::OAuth::User.find(oauth)

      # Create user if does not exist
      # and allow_single_sign_on is true
      if Gitlab.config.omniauth['allow_single_sign_on']
        @user ||= Gitlab::OAuth::User.create(oauth)
      end
Florian Unglaub committed
43 44

      if @user
45
        sign_in_and_redirect(@user)
Florian Unglaub committed
46 47 48 49 50 51
      else
        flash[:notice] = "There's no such user!"
        redirect_to new_user_session_path
      end
    end
  end
52 53 54 55

  def oauth
    @oauth ||= request.env['omniauth.auth']
  end
vsizov committed
56
end