omniauth_callbacks_controller.rb 2.2 KB
Newer Older
V
vsizov 已提交
1
class OmniauthCallbacksController < Devise::OmniauthCallbacksController
2
  Gitlab.config.omniauth.providers.each do |provider|
D
Dmitriy Zaporozhets 已提交
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
F
Florian Unglaub 已提交
17

V
vsizov 已提交
18
  def ldap
19 20
    # We only find ourselves here
    # if the authentication to LDAP was successful.
D
Dmitriy Zaporozhets 已提交
21
    @user = Gitlab::LDAP::User.find_or_create(oauth)
22
    @user.remember_me = true if @user.persisted?
23

24 25 26 27 28 29
    # Do additional LDAP checks for the user filter and EE features
    if Gitlab::LDAP::Access.allowed?(@user)
      sign_in_and_redirect(@user)
    else
      flash[:alert] = "Access denied for your LDAP account."
      redirect_to new_user_session_path
30
    end
V
vsizov 已提交
31 32
  end

33 34 35 36 37 38
  def omniauth_error
    @provider = params[:provider]
    @error = params[:error]
    render 'errors/omniauth_error', layout: "errors", status: 422
  end

F
Florian Unglaub 已提交
39 40 41 42 43
  private

  def handle_omniauth
    if current_user
      # Change a logged-in user's authentication method:
D
Dmitriy Zaporozhets 已提交
44 45
      current_user.extern_uid = oauth['uid']
      current_user.provider = oauth['provider']
F
Florian Unglaub 已提交
46 47 48
      current_user.save
      redirect_to profile_path
    else
D
Dmitriy Zaporozhets 已提交
49 50 51 52
      @user = Gitlab::OAuth::User.find(oauth)

      # Create user if does not exist
      # and allow_single_sign_on is true
53 54
      if Gitlab.config.omniauth['allow_single_sign_on'] && !@user
        @user, errors = Gitlab::OAuth::User.create(oauth)
D
Dmitriy Zaporozhets 已提交
55
      end
F
Florian Unglaub 已提交
56

57
      if @user && !errors
D
Dmitriy Zaporozhets 已提交
58
        sign_in_and_redirect(@user)
F
Florian Unglaub 已提交
59
      else
60 61
        if errors
          error_message = errors.map{ |attribute, message| "#{attribute} #{message}" }.join(", ")
62
          redirect_to omniauth_error_path(oauth['provider'], error: error_message) and return
63 64 65
        else
          flash[:notice] = "There's no such user!"
        end
F
Florian Unglaub 已提交
66 67 68 69
        redirect_to new_user_session_path
      end
    end
  end
D
Dmitriy Zaporozhets 已提交
70 71 72 73

  def oauth
    @oauth ||= request.env['omniauth.auth']
  end
V
vsizov 已提交
74
end