auth_hash.rb 1.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11
# Class to parse and transform the info provided by omniauth
#
module Gitlab
  module OAuth
    class AuthHash
      attr_reader :auth_hash
      def initialize(auth_hash)
        @auth_hash = auth_hash
      end

      def uid
12
        @uid ||= Gitlab::Utils.force_utf8(auth_hash.uid.to_s)
13 14 15
      end

      def provider
16
        @provider ||= Gitlab::Utils.force_utf8(auth_hash.provider.to_s)
17 18
      end

19 20
      def name
        @name ||= get_info(:name) || "#{get_info(:first_name)} #{get_info(:last_name)}"
21 22 23
      end

      def username
24
        @username ||= username_and_email[:username].to_s
25 26 27
      end

      def email
28
        @email ||= username_and_email[:email].to_s
29 30 31
      end

      def password
32 33 34 35 36
        @password ||= Gitlab::Utils.force_utf8(Devise.friendly_token[0, 8].downcase)
      end

      private

37 38 39 40 41 42 43 44 45 46
      def info
        auth_hash.info
      end

      def get_info(key)
        value = info[key]
        Gitlab::Utils.force_utf8(value) if value
        value
      end

47 48
      def username_and_email
        @username_and_email ||= begin
Douwe Maan's avatar
Douwe Maan committed
49
          username  = get_info(:username) || get_info(:nickname)
50 51 52 53 54 55 56 57 58 59
          email     = get_info(:email)

          username ||= generate_username(email)             if email
          email    ||= generate_temporarily_email(username) if username

          {
            username: username,
            email:    email
          }
        end
60 61 62 63
      end

      # Get the first part of the email address (before @)
      # In addtion in removes illegal characters
64
      def generate_username(email)
65 66 67
        email.match(/^[^@]*/)[0].parameterize
      end

68
      def generate_temporarily_email(username)
69 70 71 72 73
        "temp-email-for-oauth-#{username}@gitlab.localhost"
      end
    end
  end
end