BigW Consortium Gitlab

auth.rb 2.33 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
module Gitlab
  class Auth
    def find_for_ldap_auth(auth, signed_in_resource = nil)
      uid = auth.info.uid
      provider = auth.provider
      email = auth.info.email.downcase unless auth.info.email.nil?
      raise OmniAuth::Error, "LDAP accounts must provide an uid and email address" if uid.nil? or email.nil?

      if @user = User.find_by_extern_uid_and_provider(uid, provider)
        @user
      elsif @user = User.find_by_email(email)
        log.info "Updating legacy LDAP user #{email} with extern_uid => #{uid}"
        @user.update_attributes(:extern_uid => uid, :provider => provider)
        @user
      else
        create_from_omniauth(auth, true)
      end
    end

20
    def create_from_omniauth(auth, ldap = false)
21 22
      provider = auth.provider
      uid = auth.info.uid || auth.uid
23 24 25
      uid = uid.to_s.force_encoding("utf-8")
      name = auth.info.name.to_s.force_encoding("utf-8")
      email = auth.info.email.to_s.downcase unless auth.info.email.nil?
26 27 28 29 30 31 32 33

      ldap_prefix = ldap ? '(LDAP) ' : ''
      raise OmniAuth::Error, "#{ldap_prefix}#{provider} does not provide an email"\
        " address" if auth.info.email.blank?

      log.info "#{ldap_prefix}Creating user from #{provider} login"\
        " {uid => #{uid}, name => #{name}, email => #{email}}"
      password = Devise.friendly_token[0, 8].downcase
34
      @user = User.new({
35 36 37
        extern_uid: uid,
        provider: provider,
        name: name,
38
        username: email.match(/^[^@]*/)[0],
39 40 41
        email: email,
        password: password,
        password_confirmation: password,
42
        projects_limit: Gitlab.config.gitlab.default_projects_limit,
43
      }, as: :admin)
44 45
      @user.save!

46
      if Gitlab.config.omniauth['block_auto_created_users'] && !ldap
47
        @user.block
48
      end
49

50 51 52 53 54
      @user
    end

    def find_or_new_for_omniauth(auth)
      provider, uid = auth.provider, auth.uid
55
      email = auth.info.email.downcase unless auth.info.email.nil?
56 57 58

      if @user = User.find_by_provider_and_extern_uid(provider, uid)
        @user
59 60 61
      elsif @user = User.find_by_email(email)
        @user.update_attributes(:extern_uid => uid, :provider => provider)
        @user
62
      else
63
        if Gitlab.config.omniauth['allow_single_sign_on']
64 65 66 67 68 69 70 71 72 73 74
          @user = create_from_omniauth(auth)
          @user
        end
      end
    end

    def log
      Gitlab::AppLogger
    end
  end
end