user.rb 2.27 KB
Newer Older
1 2 3 4 5 6 7 8
# OAuth extension for User model
#
# * Find GitLab user based on omniauth uid and provider
# * Create new user from omniauth data
#
module Gitlab
  module OAuth
    class User
9
      attr_accessor :auth_hash, :gl_user
10

11 12 13
      def initialize(auth_hash)
        self.auth_hash = auth_hash
      end
14

15
      def persisted?
16
        gl_user.try(:persisted?)
17
      end
18

19
      def new?
20
        !persisted?
21
      end
22

23
      def valid?
24
        gl_user.try(:valid?)
25
      end
26

27
      def save
28 29
        unauthorized_to_create unless gl_user

30 31 32 33 34 35
        if needs_blocking?
          gl_user.save!
          gl_user.block
        else
          gl_user.save!
        end
36

37
        log.info "(OAuth) saving user #{auth_hash.email} from login with extern_uid => #{auth_hash.uid}"
38 39 40 41 42 43 44
        gl_user
      rescue ActiveRecord::RecordInvalid => e
        log.info "(OAuth) Error saving user: #{gl_user.errors.full_messages}"
        return self, e.record.errors
      end

      def gl_user
45 46
        @user ||= find_by_uid_and_provider

47
        if signup_enabled?
48 49
          @user ||= build_new_user
        end
50

51
        @user
52
      end
53

54
      protected
55 56 57 58 59 60 61 62 63 64 65 66 67

      def needs_blocking?
        new? && block_after_signup?
      end

      def signup_enabled?
        Gitlab.config.omniauth.allow_single_sign_on
      end

      def block_after_signup?
        Gitlab.config.omniauth.block_auto_created_users
      end

68 69 70 71
      def auth_hash=(auth_hash)
        @auth_hash = AuthHash.new(auth_hash)
      end

72 73 74
      def find_by_uid_and_provider
        model.where(provider: auth_hash.provider, extern_uid: auth_hash.uid).last
      end
75

76 77 78 79
      def build_new_user
        model.new(user_attributes).tap do |user|
          user.skip_confirmation!
        end
80 81
      end

82 83
      def user_attributes
        {
84 85 86 87 88 89 90
          extern_uid: auth_hash.uid,
          provider: auth_hash.provider,
          name: auth_hash.name,
          username: auth_hash.username,
          email: auth_hash.email,
          password: auth_hash.password,
          password_confirmation: auth_hash.password,
91 92
        }
      end
93

94 95 96 97
      def log
        Gitlab::AppLogger
      end

98 99 100
      def model
        ::User
      end
101 102 103 104

      def raise_unauthorized_to_create
        raise StandardError.new("Unauthorized to create user, signup disabled for #{auth_hash.provider}")
      end
105 106 107
    end
  end
end