Commit b45e92646e3f91c60e25197d68f72f50b1754c99

Authored by Dmitriy Zaporozhets
1 parent cdc4d64d

Added Gitlab::OAuth::User class

Authenticate or create users from OAuth providers
Showing 1 changed file with 85 additions and 0 deletions   Show diff stats
lib/gitlab/oauth/user.rb 0 → 100644
... ... @@ -0,0 +1,85 @@
  1 +# OAuth extension for User model
  2 +#
  3 +# * Find GitLab user based on omniauth uid and provider
  4 +# * Create new user from omniauth data
  5 +#
  6 +module Gitlab
  7 + module OAuth
  8 + class User
  9 + class << self
  10 + attr_reader :auth
  11 +
  12 + def find(auth)
  13 + @auth = auth
  14 + find_by_uid_and_provider
  15 + end
  16 +
  17 + def create(auth)
  18 + @auth = auth
  19 + password = Devise.friendly_token[0, 8].downcase
  20 + opts = {
  21 + extern_uid: uid,
  22 + provider: provider,
  23 + name: name,
  24 + username: username,
  25 + email: email,
  26 + password: password,
  27 + password_confirmation: password,
  28 + }
  29 +
  30 + user = model.new(opts, as: :admin).with_defaults
  31 + user.save!
  32 + log.info "(OAuth) Creating user #{email} from login with extern_uid => #{uid}"
  33 +
  34 + if Gitlab.config.omniauth['block_auto_created_users'] && !ldap?
  35 + user.block
  36 + end
  37 +
  38 + user
  39 + end
  40 +
  41 + private
  42 +
  43 + def find_by_uid_and_provider
  44 + model.where(provider: provider, extern_uid: uid).last
  45 + end
  46 +
  47 + def uid
  48 + auth.info.uid || auth.uid
  49 + end
  50 +
  51 + def email
  52 + auth.info.email.downcase unless auth.info.email.nil?
  53 + end
  54 +
  55 + def name
  56 + auth.info.name.to_s.force_encoding("utf-8")
  57 + end
  58 +
  59 + def username
  60 + email.match(/^[^@]*/)[0]
  61 + end
  62 +
  63 + def provider
  64 + auth.provider
  65 + end
  66 +
  67 + def log
  68 + Gitlab::AppLogger
  69 + end
  70 +
  71 + def model
  72 + ::User
  73 + end
  74 +
  75 + def raise_error(message)
  76 + raise OmniAuth::Error, "(OAuth) " + message
  77 + end
  78 +
  79 + def ldap?
  80 + provider == 'ldap'
  81 + end
  82 + end
  83 + end
  84 + end
  85 +end
... ...