user.rb 31.9 KB
Newer Older
S
Steven Thonus 已提交
1 2
require 'carrierwave/orm/activerecord'

G
gitlabhq 已提交
3
class User < ActiveRecord::Base
4
  extend Gitlab::ConfigHelper
5 6

  include Gitlab::ConfigHelper
7
  include Gitlab::CurrentSettings
8 9
  include Referable
  include Sortable
10
  include CaseSensitivity
11 12
  include TokenAuthenticatable

13 14
  DEFAULT_NOTIFICATION_LEVEL = :participating

15
  add_authentication_token_field :authentication_token
16
  add_authentication_token_field :incoming_email_token
17

18
  default_value_for :admin, false
19
  default_value_for(:external) { current_application_settings.user_default_external }
20
  default_value_for :can_create_group, gitlab_config.default_can_create_group
21 22
  default_value_for :can_create_team, false
  default_value_for :hide_no_ssh_key, false
23
  default_value_for :hide_no_password, false
24
  default_value_for :project_view, :files
25
  default_value_for :notified_of_own_activity, false
26

27
  attr_encrypted :otp_secret,
28
    key:       Gitlab::Application.secrets.otp_key_base,
29
    mode:      :per_attribute_iv_and_salt,
30
    insecure_mode: true,
31 32
    algorithm: 'aes-256-cbc'

33
  devise :two_factor_authenticatable,
34
         otp_secret_encryption_key: Gitlab::Application.secrets.otp_key_base
R
Robert Speicher 已提交
35

36
  devise :two_factor_backupable, otp_number_of_backup_codes: 10
R
Robert Speicher 已提交
37 38
  serialize :otp_backup_codes, JSON

39
  devise :lockable, :recoverable, :rememberable, :trackable,
40
    :validatable, :omniauthable, :confirmable, :registerable
G
gitlabhq 已提交
41

42
  attr_accessor :force_random_password
G
gitlabhq 已提交
43

44 45 46
  # Virtual attribute for authenticating by either username or email
  attr_accessor :login

47 48 49 50
  #
  # Relations
  #

51
  # Namespace for personal projects
52
  has_one :namespace, -> { where type: nil }, dependent: :destroy, foreign_key: :owner_id
53 54

  # Profile
55 56 57 58 59 60
  has_many :keys, -> do
    type = Key.arel_table[:type]
    where(type.not_eq('DeployKey').or(type.eq(nil)))
  end, dependent: :destroy
  has_many :deploy_keys, -> { where(type: 'DeployKey') }, dependent: :destroy

61
  has_many :emails, dependent: :destroy
62
  has_many :personal_access_tokens, dependent: :destroy
63
  has_many :identities, dependent: :destroy, autosave: true
64
  has_many :u2f_registrations, dependent: :destroy
65
  has_many :chat_names, dependent: :destroy
66 67

  # Groups
68
  has_many :members, dependent: :destroy
69
  has_many :group_members, -> { where(requested_at: nil) }, dependent: :destroy, source: 'GroupMember'
70
  has_many :groups, through: :group_members
71 72
  has_many :owned_groups, -> { where members: { access_level: Gitlab::Access::OWNER } }, through: :group_members, source: :group
  has_many :masters_groups, -> { where members: { access_level: Gitlab::Access::MASTER } }, through: :group_members, source: :group
73

74
  # Projects
75 76
  has_many :groups_projects,          through: :groups, source: :projects
  has_many :personal_projects,        through: :namespace, source: :projects
77
  has_many :project_members, -> { where(requested_at: nil) }, dependent: :destroy
78
  has_many :projects,                 through: :project_members
79
  has_many :created_projects,         foreign_key: :creator_id, class_name: 'Project'
C
Ciro Santilli 已提交
80 81
  has_many :users_star_projects, dependent: :destroy
  has_many :starred_projects, through: :users_star_projects, source: :project
82
  has_many :project_authorizations
83
  has_many :authorized_projects, through: :project_authorizations, source: :project
84

85
  has_many :snippets,                 dependent: :destroy, foreign_key: :author_id
86 87
  has_many :notes,                    dependent: :destroy, foreign_key: :author_id
  has_many :merge_requests,           dependent: :destroy, foreign_key: :author_id
88
  has_many :events,                   dependent: :destroy, foreign_key: :author_id
89
  has_many :subscriptions,            dependent: :destroy
90
  has_many :recent_events, -> { order "id DESC" }, foreign_key: :author_id,   class_name: "Event"
V
Valery Sizov 已提交
91
  has_many :oauth_applications, class_name: 'Doorkeeper::Application', as: :owner, dependent: :destroy
92
  has_one  :abuse_report,             dependent: :destroy, foreign_key: :user_id
93
  has_many :reported_abuse_reports,   dependent: :destroy, foreign_key: :reporter_id, class_name: "AbuseReport"
94
  has_many :spam_logs,                dependent: :destroy
95
  has_many :builds,                   dependent: :nullify, class_name: 'Ci::Build'
96
  has_many :pipelines,                dependent: :nullify, class_name: 'Ci::Pipeline'
97
  has_many :todos,                    dependent: :destroy
98
  has_many :notification_settings,    dependent: :destroy
99
  has_many :award_emoji,              dependent: :destroy
K
Kamil Trzcinski 已提交
100
  has_many :triggers,                 dependent: :destroy, class_name: 'Ci::Trigger', foreign_key: :owner_id
101

102 103 104 105 106
  # Issues that a user owns are expected to be moved to the "ghost" user before
  # the user is destroyed. If the user owns any issues during deletion, this
  # should be treated as an exceptional condition.
  has_many :issues,                   dependent: :restrict_with_exception, foreign_key: :author_id

107 108 109
  #
  # Validations
  #
110
  # Note: devise :validatable above adds validations for :email and :password
C
Cyril 已提交
111
  validates :name, presence: true
D
Douwe Maan 已提交
112
  validates :email, confirmation: true
113 114
  validates :notification_email, presence: true
  validates :notification_email, email: true, if: ->(user) { user.notification_email != user.email }
115
  validates :public_email, presence: true, uniqueness: true, email: true, allow_blank: true
116
  validates :bio, length: { maximum: 255 }, allow_blank: true
117 118 119
  validates :projects_limit,
    presence: true,
    numericality: { greater_than_or_equal_to: 0, less_than_or_equal_to: Gitlab::Database::MAX_INT_VALUE }
120
  validates :username,
R
Robert Speicher 已提交
121
    namespace: true,
122
    presence: true,
R
Robert Speicher 已提交
123
    uniqueness: { case_sensitive: false }
124

125
  validate :namespace_uniq, if: ->(user) { user.username_changed? }
126
  validate :avatar_type, if: ->(user) { user.avatar.present? && user.avatar_changed? }
127
  validate :unique_email, if: ->(user) { user.email_changed? }
128
  validate :owns_notification_email, if: ->(user) { user.notification_email_changed? }
129
  validate :owns_public_email, if: ->(user) { user.public_email_changed? }
130
  validate :signup_domain_valid?, on: :create, if: ->(user) { !user.created_by_id }
131
  validates :avatar, file_size: { maximum: 200.kilobytes.to_i }
132

133
  before_validation :sanitize_attrs
134
  before_validation :set_notification_email, if: ->(user) { user.email_changed? }
135
  before_validation :set_public_email, if: ->(user) { user.public_email_changed? }
136

137
  after_update :update_emails_with_primary_email, if: ->(user) { user.email_changed? }
138
  before_save :ensure_authentication_token, :ensure_incoming_email_token
Z
Zeger-Jan van de Weg 已提交
139
  before_save :ensure_external_user_rights
D
Dmitriy Zaporozhets 已提交
140
  after_save :ensure_namespace_correct
141
  after_initialize :set_projects_limit
D
Dmitriy Zaporozhets 已提交
142 143
  after_destroy :post_destroy_hook

144
  # User's Layout preference
145
  enum layout: [:fixed, :fluid]
146

147 148
  # User's Dashboard preference
  # Note: When adding an option, it MUST go on the end of the array.
149
  enum dashboard: [:projects, :stars, :project_activity, :starred_project_activity, :groups, :todos]
150

151 152
  # User's Project preference
  # Note: When adding an option, it MUST go on the end of the array.
153
  enum project_view: [:readme, :activity, :files]
154

N
Nihad Abbasov 已提交
155
  alias_attribute :private_token, :authentication_token
156

157
  delegate :path, to: :namespace, allow_nil: true, prefix: true
158

159 160 161
  state_machine :state, initial: :active do
    event :block do
      transition active: :blocked
162
      transition ldap_blocked: :blocked
163 164
    end

165 166 167 168
    event :ldap_block do
      transition active: :ldap_blocked
    end

169 170
    event :activate do
      transition blocked: :active
171
      transition ldap_blocked: :active
172
    end
173 174 175 176 177

    state :blocked, :ldap_blocked do
      def blocked?
        true
      end
178 179 180 181 182 183 184 185 186

      def active_for_authentication?
        false
      end

      def inactive_message
        "Your account has been blocked. Please contact your GitLab " \
          "administrator if you think this is an error."
      end
187
    end
188 189
  end

190
  mount_uploader :avatar, AvatarUploader
191
  has_many :uploads, as: :model, dependent: :destroy
S
Steven Thonus 已提交
192

A
Andrey Kumanyaev 已提交
193
  # Scopes
194
  scope :admins, -> { where(admin: true) }
195
  scope :blocked, -> { with_states(:blocked, :ldap_blocked) }
196
  scope :external, -> { where(external: true) }
J
James Lopez 已提交
197
  scope :active, -> { with_state(:active).non_internal }
S
skv 已提交
198
  scope :not_in_project, ->(project) { project.users.present? ? where("id not in (:ids)", ids: project.users.map(&:id) ) : all }
B
Ben Bodenmiller 已提交
199
  scope :without_projects, -> { where('id NOT IN (SELECT DISTINCT(user_id) FROM members WHERE user_id IS NOT NULL AND requested_at IS NULL)') }
V
Valery Sizov 已提交
200
  scope :todo_authors, ->(user_id, state) { where(id: Todo.where(user_id: user_id, state: state).select(:author_id)) }
201 202
  scope :order_recent_sign_in, -> { reorder(Gitlab::Database.nulls_last_order('last_sign_in_at', 'DESC')) }
  scope :order_oldest_sign_in, -> { reorder(Gitlab::Database.nulls_last_order('last_sign_in_at', 'ASC')) }
203 204

  def self.with_two_factor
205 206
    joins("LEFT OUTER JOIN u2f_registrations AS u2f ON u2f.user_id = users.id").
      where("u2f.id IS NOT NULL OR otp_required_for_login = ?", true).distinct(arel_table[:id])
207 208 209
  end

  def self.without_two_factor
210 211
    joins("LEFT OUTER JOIN u2f_registrations AS u2f ON u2f.user_id = users.id").
      where("u2f.id IS NULL AND otp_required_for_login = ?", false)
212
  end
A
Andrey Kumanyaev 已提交
213

214 215 216
  #
  # Class methods
  #
A
Andrey Kumanyaev 已提交
217
  class << self
218
    # Devise method overridden to allow sign in with email or username
219 220 221
    def find_for_database_authentication(warden_conditions)
      conditions = warden_conditions.dup
      if login = conditions.delete(:login)
G
Gabriel Mazetto 已提交
222
        where(conditions).find_by("lower(username) = :value OR lower(email) = :value", value: login.downcase)
223
      else
G
Gabriel Mazetto 已提交
224
        find_by(conditions)
225 226
      end
    end
227

V
Valery Sizov 已提交
228 229
    def sort(method)
      case method.to_s
230 231
      when 'recent_sign_in' then order_recent_sign_in
      when 'oldest_sign_in' then order_oldest_sign_in
232 233
      else
        order_by(method)
V
Valery Sizov 已提交
234 235 236
      end
    end

237 238
    # Find a User by their primary email or any associated secondary email
    def find_by_any_email(email)
239 240 241 242 243 244 245
      sql = 'SELECT *
      FROM users
      WHERE id IN (
        SELECT id FROM users WHERE email = :email
        UNION
        SELECT emails.user_id FROM emails WHERE email = :email
      )
246 247 248
      LIMIT 1;'

      User.find_by_sql([sql, { email: email }]).first
249
    end
250

251
    def filter(filter_name)
A
Andrey Kumanyaev 已提交
252
      case filter_name
253
      when 'admins'
254
        admins
255
      when 'blocked'
256
        blocked
257
      when 'two_factor_disabled'
258
        without_two_factor
259
      when 'two_factor_enabled'
260
        with_two_factor
261
      when 'wop'
262
        without_projects
263
      when 'external'
264
        external
A
Andrey Kumanyaev 已提交
265
      else
266
        active
A
Andrey Kumanyaev 已提交
267
      end
268 269
    end

270 271 272 273 274 275 276
    # Searches users matching the given query.
    #
    # This method uses ILIKE on PostgreSQL and LIKE on MySQL.
    #
    # query - The search query as a String
    #
    # Returns an ActiveRecord::Relation.
277
    def search(query)
278
      table   = arel_table
279 280 281
      pattern = "%#{query}%"

      where(
282 283 284
        table[:name].matches(pattern).
          or(table[:email].matches(pattern)).
          or(table[:username].matches(pattern))
285
      )
A
Andrey Kumanyaev 已提交
286
    end
287

288 289 290 291 292 293 294 295 296 297 298
    # searches user by given pattern
    # it compares name, email, username fields and user's secondary emails with given pattern
    # This method uses ILIKE on PostgreSQL and LIKE on MySQL.

    def search_with_secondary_emails(query)
      table = arel_table
      email_table = Email.arel_table
      pattern = "%#{query}%"
      matched_by_emails_user_ids = email_table.project(email_table[:user_id]).where(email_table[:email].matches(pattern))

      where(
299 300 301 302
        table[:name].matches(pattern).
          or(table[:email].matches(pattern)).
          or(table[:username].matches(pattern)).
          or(table[:id].in(matched_by_emails_user_ids))
303 304 305
      )
    end

306
    def by_login(login)
307 308 309 310 311 312 313
      return nil unless login

      if login.include?('@'.freeze)
        unscoped.iwhere(email: login).take
      else
        unscoped.iwhere(username: login).take
      end
314 315
    end

316 317 318 319
    def find_by_username(username)
      iwhere(username: username).take
    end

R
Robert Speicher 已提交
320
    def find_by_username!(username)
321
      iwhere(username: username).take!
R
Robert Speicher 已提交
322 323
    end

T
Timothy Andrew 已提交
324
    def find_by_personal_access_token(token_string)
325 326
      return unless token_string

327
      PersonalAccessTokensFinder.new(state: 'active').find_by(token: token_string)&.user
T
Timothy Andrew 已提交
328 329
    end

Y
Yorick Peterse 已提交
330 331 332 333 334
    # Returns a user for the given SSH key.
    def find_by_ssh_key_id(key_id)
      find_by(id: Key.unscoped.select(:user_id).where(id: key_id))
    end

335 336 337
    def reference_prefix
      '@'
    end
338 339 340 341 342

    # Pattern used to extract `@user` user references from text
    def reference_pattern
      %r{
        #{Regexp.escape(reference_prefix)}
343
        (?<user>#{Gitlab::Regex::FULL_NAMESPACE_REGEX_STR})
344 345
      }x
    end
346 347 348 349

    # Return (create if necessary) the ghost user. The ghost user
    # owns records previously belonging to deleted users.
    def ghost
350 351 352 353
      unique_internal(where(ghost: true), 'ghost', 'ghost%s@example.com') do |u|
        u.bio = 'This is a "Ghost User", created to hold all issues authored by users that have since been deleted. This user cannot be removed.'
        u.name = 'Ghost User'
      end
354
    end
V
vsizov 已提交
355
  end
R
randx 已提交
356

357 358 359 360
  def self.internal_attributes
    [:ghost]
  end

361
  def internal?
362 363 364 365 366 367 368 369
    self.class.internal_attributes.any? { |a| self[a] }
  end

  def self.internal
    where(Hash[internal_attributes.zip([true] * internal_attributes.size)])
  end

  def self.non_internal
370
    where(Hash[internal_attributes.zip([[false, nil]] * internal_attributes.size)])
371 372
  end

373 374 375
  #
  # Instance methods
  #
376 377 378 379 380

  def to_param
    username
  end

381
  def to_reference(_from_project = nil, target_project: nil, full: nil)
382 383 384
    "#{self.class.reference_prefix}#{username}"
  end

385 386
  def skip_confirmation=(bool)
    skip_confirmation! if bool
R
randx 已提交
387
  end
388

389
  def generate_reset_token
M
Marin Jankovski 已提交
390
    @reset_token, enc = Devise.token_generator.generate(self.class, :reset_password_token)
391 392 393 394

    self.reset_password_token   = enc
    self.reset_password_sent_at = Time.now.utc

M
Marin Jankovski 已提交
395
    @reset_token
396 397
  end

398 399 400 401
  def recently_sent_password_reset?
    reset_password_sent_at.present? && reset_password_sent_at >= 1.minute.ago
  end

R
Robert Speicher 已提交
402
  def disable_two_factor!
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420
    transaction do
      update_attributes(
        otp_required_for_login:      false,
        encrypted_otp_secret:        nil,
        encrypted_otp_secret_iv:     nil,
        encrypted_otp_secret_salt:   nil,
        otp_grace_period_started_at: nil,
        otp_backup_codes:            nil
      )
      self.u2f_registrations.destroy_all
    end
  end

  def two_factor_enabled?
    two_factor_otp_enabled? || two_factor_u2f_enabled?
  end

  def two_factor_otp_enabled?
421
    otp_required_for_login?
422 423 424
  end

  def two_factor_u2f_enabled?
425
    u2f_registrations.exists?
R
Robert Speicher 已提交
426 427
  end

428
  def namespace_uniq
429
    # Return early if username already failed the first uniqueness validation
430
    return if errors.key?(:username) &&
431
        errors[:username].include?('has already been taken')
432

433 434 435
    existing_namespace = Namespace.by_path(username)
    if existing_namespace && existing_namespace != namespace
      errors.add(:username, 'has already been taken')
436 437
    end
  end
438

439
  def avatar_type
440 441
    unless avatar.image?
      errors.add :avatar, "only images allowed"
442 443 444
    end
  end

445
  def unique_email
446 447
    if !emails.exists?(email: email) && Email.exists?(email: email)
      errors.add(:email, 'has already been taken')
448
    end
449 450
  end

451
  def owns_notification_email
452
    return if temp_oauth_email?
453

454
    errors.add(:notification_email, "is not an email you own") unless all_emails.include?(notification_email)
455 456
  end

457
  def owns_public_email
458
    return if public_email.blank?
459

460
    errors.add(:public_email, "is not an email you own") unless all_emails.include?(public_email)
461 462 463
  end

  def update_emails_with_primary_email
464
    primary_email_record = emails.find_by(email: email)
465 466
    if primary_email_record
      primary_email_record.destroy
467
      emails.create(email: email_was)
468

469
      update_secondary_emails!
470 471 472
    end
  end

473 474
  # Returns the groups a user has access to
  def authorized_groups
475 476
    union = Gitlab::SQL::Union.
      new([groups.select(:id), authorized_projects.select(:namespace_id)])
477

478
    Group.where("namespaces.id IN (#{union.to_sql})")
479 480
  end

481 482 483 484
  def nested_groups
    Group.member_descendants(id)
  end

485 486 487 488 489 490 491 492
  def all_expanded_groups
    Group.member_hierarchy(id)
  end

  def expanded_groups_requiring_two_factor_authentication
    all_expanded_groups.where(require_two_factor_authentication: true)
  end

493
  def nested_groups_projects
494 495
    Project.joins(:namespace).where('namespaces.parent_id IS NOT NULL').
      member_descendants(id)
496 497
  end

498
  def refresh_authorized_projects
499 500 501 502
    Users::RefreshAuthorizedProjectsService.new(self).execute
  end

  def remove_project_authorizations(project_ids)
503
    project_authorizations.where(project_id: project_ids).delete_all
504 505 506 507 508
  end

  def set_authorized_projects_column
    unless authorized_projects_populated
      update_column(:authorized_projects_populated, true)
509 510 511
    end
  end

512
  def authorized_projects(min_access_level = nil)
513 514 515 516 517 518 519 520 521 522 523
    refresh_authorized_projects unless authorized_projects_populated

    # We're overriding an association, so explicitly call super with no arguments or it would be passed as `force_reload` to the association
    projects = super()
    projects = projects.where('project_authorizations.access_level >= ?', min_access_level) if min_access_level

    projects
  end

  def authorized_project?(project, min_access_level = nil)
    authorized_projects(min_access_level).exists?({ id: project.id })
524 525
  end

526 527 528 529 530 531 532 533 534 535
  # Returns the projects this user has reporter (or greater) access to, limited
  # to at most the given projects.
  #
  # This method is useful when you have a list of projects and want to
  # efficiently check to which of these projects the user has at least reporter
  # access.
  def projects_with_reporter_access_limited_to(projects)
    authorized_projects(Gitlab::Access::REPORTER).where(id: projects)
  end

536
  def viewable_starred_projects
537 538 539
    starred_projects.where("projects.visibility_level IN (?) OR projects.id IN (?)",
                           [Project::PUBLIC, Project::INTERNAL],
                           authorized_projects.select(:project_id))
540 541
  end

542
  def owned_projects
543
    @owned_projects ||=
544 545
      Project.where('namespace_id IN (?) OR namespace_id = ?',
                    owned_groups.select(:id), namespace.id).joins(:namespace)
546 547
  end

548 549 550 551
  # Returns projects which user can admin issues on (for example to move an issue to that project).
  #
  # This logic is duplicated from `Ability#project_abilities` into a SQL form.
  def projects_where_can_admin_issues
F
Felipe Artur 已提交
552
    authorized_projects(Gitlab::Access::REPORTER).non_archived.with_issues_enabled
553 554
  end

D
Dmitriy Zaporozhets 已提交
555
  def require_ssh_key?
556
    keys.count == 0 && Gitlab::ProtocolAccess.allowed?('ssh')
D
Dmitriy Zaporozhets 已提交
557 558
  end

559 560 561 562
  def require_password?
    password_automatically_set? && !ldap_user?
  end

563
  def can_change_username?
564
    gitlab_config.username_changing_enabled
565 566
  end

D
Dmitriy Zaporozhets 已提交
567
  def can_create_project?
568
    projects_limit_left > 0
D
Dmitriy Zaporozhets 已提交
569 570 571
  end

  def can_create_group?
572
    can?(:create_group)
D
Dmitriy Zaporozhets 已提交
573 574
  end

575 576 577 578
  def can_select_namespace?
    several_namespaces? || admin
  end

579
  def can?(action, subject = :global)
H
http://jneen.net/ 已提交
580
    Ability.allowed?(self, action, subject)
D
Dmitriy Zaporozhets 已提交
581 582 583 584 585 586
  end

  def first_name
    name.split.first unless name.blank?
  end

587
  def projects_limit_left
588
    projects_limit - personal_projects.count
589 590
  end

D
Dmitriy Zaporozhets 已提交
591 592
  def projects_limit_percent
    return 100 if projects_limit.zero?
593
    (personal_projects.count.to_f / projects_limit) * 100
D
Dmitriy Zaporozhets 已提交
594 595
  end

596
  def recent_push(project_ids = nil)
D
Dmitriy Zaporozhets 已提交
597 598
    # Get push events not earlier than 2 hours ago
    events = recent_events.code_push.where("created_at > ?", Time.now - 2.hours)
599
    events = events.where(project_id: project_ids) if project_ids
D
Dmitriy Zaporozhets 已提交
600

601 602 603 604 605
    # Use the latest event that has not been pushed or merged recently
    events.recent.find do |event|
      project = Project.find_by_id(event.project_id)
      next unless project

P
Paco Guzman 已提交
606
      if project.repository.branch_exists?(event.branch_name)
607 608 609
        merge_requests = MergeRequest.where("created_at >= ?", event.created_at).
          where(source_project_id: project.id,
                source_branch: event.branch_name)
610 611 612
        merge_requests.empty?
      end
    end
D
Dmitriy Zaporozhets 已提交
613 614 615 616 617 618 619
  end

  def projects_sorted_by_activity
    authorized_projects.sorted_by_activity
  end

  def several_namespaces?
620
    owned_groups.any? || masters_groups.any?
D
Dmitriy Zaporozhets 已提交
621 622 623 624 625
  end

  def namespace_id
    namespace.try :id
  end
626

627 628 629
  def name_with_username
    "#{name} (#{username})"
  end
D
Dmitriy Zaporozhets 已提交
630

631
  def already_forked?(project)
632 633 634
    !!fork_of(project)
  end

635
  def fork_of(project)
636 637 638 639
    links = ForkedProjectLink.where(
      forked_from_project_id: project,
      forked_to_project_id: personal_projects.unscope(:order)
    )
640 641 642 643 644 645
    if links.any?
      links.first.forked_to_project
    else
      nil
    end
  end
646 647

  def ldap_user?
648 649 650 651 652
    identities.exists?(["provider LIKE ? AND extern_uid IS NOT NULL", "ldap%"])
  end

  def ldap_identity
    @ldap_identity ||= identities.find_by(["provider LIKE ?", "ldap%"])
653
  end
654

655
  def project_deploy_keys
656
    DeployKey.unscoped.in_projects(authorized_projects.pluck(:id)).distinct(:id)
657 658
  end

659
  def accessible_deploy_keys
660 661 662 663 664
    @accessible_deploy_keys ||= begin
      key_ids = project_deploy_keys.pluck(:id)
      key_ids.push(*DeployKey.are_public.pluck(:id))
      DeployKey.where(id: key_ids)
    end
665
  end
666 667

  def created_by
S
skv 已提交
668
    User.find_by(id: created_by_id) if created_by_id
669
  end
670 671

  def sanitize_attrs
672 673 674
    %w[name username skype linkedin twitter].each do |attr|
      value = public_send(attr)
      public_send("#{attr}=", Sanitize.clean(value)) if value.present?
675 676
    end
  end
677

678
  def set_notification_email
679 680
    if notification_email.blank? || !all_emails.include?(notification_email)
      self.notification_email = email
681 682 683
    end
  end

684
  def set_public_email
685
    if public_email.blank? || !all_emails.include?(public_email)
686
      self.public_email = ''
687 688 689
    end
  end

690
  def update_secondary_emails!
691 692 693
    set_notification_email
    set_public_email
    save if notification_email_changed? || public_email_changed?
694 695
  end

696
  def set_projects_limit
697 698 699
    # `User.select(:id)` raises
    # `ActiveModel::MissingAttributeError: missing attribute: projects_limit`
    # without this safeguard!
700
    return unless has_attribute?(:projects_limit)
701

702
    connection_default_value_defined = new_record? && !projects_limit_changed?
703
    return unless projects_limit.nil? || connection_default_value_defined
704 705 706 707

    self.projects_limit = current_application_settings.default_projects_limit
  end

708
  def requires_ldap_check?
709 710 711
    if !Gitlab.config.ldap.enabled
      false
    elsif ldap_user?
712 713 714 715 716 717
      !last_credential_check_at || (last_credential_check_at + 1.hour) < Time.now
    else
      false
    end
  end

J
Jacob Vosmaer 已提交
718 719 720 721 722 723 724
  def try_obtain_ldap_lease
    # After obtaining this lease LDAP checks will be blocked for 600 seconds
    # (10 minutes) for this user.
    lease = Gitlab::ExclusiveLease.new("user_ldap_check:#{id}", timeout: 600)
    lease.try_obtain
  end

725 726 727 728 729
  def solo_owned_groups
    @solo_owned_groups ||= owned_groups.select do |group|
      group.owners == [self]
    end
  end
730 731

  def with_defaults
732
    User.defaults.each do |k, v|
733
      public_send("#{k}=", v)
734
    end
735 736

    self
737
  end
738

739 740 741 742
  def can_leave_project?(project)
    project.namespace != namespace &&
      project.project_member(self)
  end
743

J
Jerome Dalbert 已提交
744
  def full_website_url
745
    return "http://#{website_url}" if website_url !~ /\Ahttps?:\/\//
J
Jerome Dalbert 已提交
746 747 748 749 750

    website_url
  end

  def short_website_url
751
    website_url.sub(/\Ahttps?:\/\//, '')
J
Jerome Dalbert 已提交
752
  end
G
GitLab 已提交
753

754
  def all_ssh_keys
755
    keys.map(&:publishable_key)
756
  end
757 758

  def temp_oauth_email?
759
    email.start_with?('temp-email-for-oauth')
760 761
  end

762
  def avatar_url(size = nil, scale = 2)
763
    if self[:avatar].present?
764
      [gitlab_config.url, avatar.url].join
765
    else
766
      GravatarService.new.execute(email, size, scale)
767 768
    end
  end
D
Dmitriy Zaporozhets 已提交
769

770
  def all_emails
771
    all_emails = []
772 773
    all_emails << email unless temp_oauth_email?
    all_emails.concat(emails.map(&:email))
774
    all_emails
775 776
  end

K
Kirill Zaitsev 已提交
777 778 779 780 781 782 783 784
  def hook_attrs
    {
      name: name,
      username: username,
      avatar_url: avatar_url
    }
  end

D
Dmitriy Zaporozhets 已提交
785 786
  def ensure_namespace_correct
    # Ensure user has namespace
787
    create_namespace!(path: username, name: username) unless namespace
D
Dmitriy Zaporozhets 已提交
788

789 790
    if username_changed?
      namespace.update_attributes(path: username, name: username)
D
Dmitriy Zaporozhets 已提交
791 792 793 794
    end
  end

  def post_destroy_hook
795
    log_info("User \"#{name}\" (#{email})  was removed")
D
Dmitriy Zaporozhets 已提交
796 797 798
    system_hook_service.execute_hooks_for(self, :destroy)
  end

D
Dmitriy Zaporozhets 已提交
799
  def notification_service
D
Dmitriy Zaporozhets 已提交
800 801 802
    NotificationService.new
  end

803
  def log_info(message)
D
Dmitriy Zaporozhets 已提交
804 805 806 807 808 809
    Gitlab::AppLogger.info message
  end

  def system_hook_service
    SystemHooksService.new
  end
C
Ciro Santilli 已提交
810 811

  def starred?(project)
V
Valery Sizov 已提交
812
    starred_projects.exists?(project.id)
C
Ciro Santilli 已提交
813 814 815
  end

  def toggle_star(project)
816
    UsersStarProject.transaction do
817 818
      user_star_project = users_star_projects.
          where(project: project, user: self).lock(true).first
819 820 821 822 823 824

      if user_star_project
        user_star_project.destroy
      else
        UsersStarProject.create!(project: project, user: self)
      end
C
Ciro Santilli 已提交
825 826
    end
  end
827 828

  def manageable_namespaces
G
Guilherme Garnier 已提交
829
    @manageable_namespaces ||= [namespace] + owned_groups + masters_groups
830
  end
D
Dmitriy Zaporozhets 已提交
831

832 833 834 835 836 837
  def namespaces
    namespace_ids = groups.pluck(:id)
    namespace_ids.push(namespace.id)
    Namespace.where(id: namespace_ids)
  end

D
Dmitriy Zaporozhets 已提交
838
  def oauth_authorized_tokens
839
    Doorkeeper::AccessToken.where(resource_owner_id: id, revoked_at: nil)
D
Dmitriy Zaporozhets 已提交
840
  end
841

842 843 844 845 846 847 848 849 850
  # Returns the projects a user contributed to in the last year.
  #
  # This method relies on a subquery as this performs significantly better
  # compared to a JOIN when coupled with, for example,
  # `Project.visible_to_user`. That is, consider the following code:
  #
  #     some_user.contributed_projects.visible_to_user(other_user)
  #
  # If this method were to use a JOIN the resulting query would take roughly 200
851
  # ms on a database with a similar size to GitLab.com's database. On the other
852 853
  # hand, using a subquery means we can get the exact same data in about 40 ms.
  def contributed_projects
854 855 856 857 858
    events = Event.select(:project_id).
      contributions.where(author_id: self).
      where("created_at > ?", Time.now - 1.year).
      uniq.
      reorder(nil)
859 860

    Project.where(id: events)
861
  end
862

863 864 865
  def can_be_removed?
    !solo_owned_groups.present?
  end
866 867

  def ci_authorized_runners
K
Kamil Trzcinski 已提交
868
    @ci_authorized_runners ||= begin
869
      runner_ids = Ci::RunnerProject.
K
Kamil Trzciński 已提交
870
        where("ci_runner_projects.project_id IN (#{ci_projects_union.to_sql})").
871
        select(:runner_id)
K
Kamil Trzcinski 已提交
872 873
      Ci::Runner.specific.where(id: runner_ids)
    end
874
  end
875

876 877 878 879
  def notification_settings_for(source)
    notification_settings.find_or_initialize_by(source: source)
  end

880 881 882
  # Lazy load global notification setting
  # Initializes User setting with Participating level if setting not persisted
  def global_notification_setting
883 884 885 886 887 888
    return @global_notification_setting if defined?(@global_notification_setting)

    @global_notification_setting = notification_settings.find_or_initialize_by(source: nil)
    @global_notification_setting.update_attributes(level: NotificationSetting.levels[DEFAULT_NOTIFICATION_LEVEL]) unless @global_notification_setting.persisted?

    @global_notification_setting
889 890
  end

891 892
  def assigned_open_merge_requests_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_merge_requests_count'], force: force) do
893
      MergeRequestsFinder.new(self, assignee_id: self.id, state: 'opened').execute.count
894 895 896
    end
  end

J
Josh Frye 已提交
897 898
  def assigned_open_issues_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_issues_count'], force: force) do
899
      IssuesFinder.new(self, assignee_id: self.id, state: 'opened').execute.count
900
    end
901 902
  end

J
Josh Frye 已提交
903
  def update_cache_counts
904
    assigned_open_merge_requests_count(force: true)
J
Josh Frye 已提交
905 906 907
    assigned_open_issues_count(force: true)
  end

P
Paco Guzman 已提交
908 909
  def todos_done_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_done_count'], force: force) do
910
      TodosFinder.new(self, state: :done).execute.count
P
Paco Guzman 已提交
911 912 913 914 915
    end
  end

  def todos_pending_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_pending_count'], force: force) do
916
      TodosFinder.new(self, state: :pending).execute.count
P
Paco Guzman 已提交
917 918 919 920 921 922 923 924
    end
  end

  def update_todos_count_cache
    todos_done_count(force: true)
    todos_pending_count(force: true)
  end

925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
  # This is copied from Devise::Models::Lockable#valid_for_authentication?, as our auth
  # flow means we don't call that automatically (and can't conveniently do so).
  #
  # See:
  #   <https://github.com/plataformatec/devise/blob/v4.0.0/lib/devise/models/lockable.rb#L92>
  #
  def increment_failed_attempts!
    self.failed_attempts ||= 0
    self.failed_attempts += 1
    if attempts_exceeded?
      lock_access! unless access_locked?
    else
      save(validate: false)
    end
  end

941 942 943 944 945 946 947 948 949
  def access_level
    if admin?
      :admin
    else
      :regular
    end
  end

  def access_level=(new_level)
D
Douwe Maan 已提交
950 951
    new_level = new_level.to_s
    return unless %w(admin regular).include?(new_level)
952

D
Douwe Maan 已提交
953 954
    self.admin = (new_level == 'admin')
  end
955

956
  def update_two_factor_requirement
957
    periods = expanded_groups_requiring_two_factor_authentication.pluck(:two_factor_grace_period)
958

959
    self.require_two_factor_authentication_from_group = periods.any?
960 961 962 963 964
    self.two_factor_grace_period = periods.min || User.column_defaults['two_factor_grace_period']

    save
  end

965 966 967 968 969 970 971 972
  protected

  # override, from Devise::Validatable
  def password_required?
    return false if internal?
    super
  end

973 974
  private

975 976 977 978 979 980 981 982
  def ci_projects_union
    scope  = { access_level: [Gitlab::Access::MASTER, Gitlab::Access::OWNER] }
    groups = groups_projects.where(members: scope)
    other  = projects.where(members: scope)

    Gitlab::SQL::Union.new([personal_projects.select(:id), groups.select(:id),
                            other.select(:id)])
  end
V
Valery Sizov 已提交
983 984 985 986 987

  # Added according to https://github.com/plataformatec/devise/blob/7df57d5081f9884849ca15e4fde179ef164a575f/README.md#activejob-integration
  def send_devise_notification(notification, *args)
    devise_mailer.send(notification, self, *args).deliver_later
  end
Z
Zeger-Jan van de Weg 已提交
988 989

  def ensure_external_user_rights
990
    return unless external?
Z
Zeger-Jan van de Weg 已提交
991 992 993 994

    self.can_create_group   = false
    self.projects_limit     = 0
  end
995

996 997 998 999 1000 1001
  def signup_domain_valid?
    valid = true
    error = nil

    if current_application_settings.domain_blacklist_enabled?
      blocked_domains = current_application_settings.domain_blacklist
1002
      if domain_matches?(blocked_domains, email)
1003 1004 1005 1006 1007
        error = 'is not from an allowed domain.'
        valid = false
      end
    end

1008
    allowed_domains = current_application_settings.domain_whitelist
1009
    unless allowed_domains.blank?
1010
      if domain_matches?(allowed_domains, email)
1011 1012
        valid = true
      else
D
dev-chris 已提交
1013
        error = "domain is not authorized for sign-up"
1014 1015 1016 1017
        valid = false
      end
    end

1018
    errors.add(:email, error) unless valid
1019 1020 1021

    valid
  end
1022

1023
  def domain_matches?(email_domains, email)
1024 1025 1026 1027 1028 1029 1030
    signup_domain = Mail::Address.new(email).domain
    email_domains.any? do |domain|
      escaped = Regexp.escape(domain).gsub('\*', '.*?')
      regexp = Regexp.new "^#{escaped}$", Regexp::IGNORECASE
      signup_domain =~ regexp
    end
  end
1031 1032 1033 1034

  def generate_token(token_field)
    if token_field == :incoming_email_token
      # Needs to be all lowercase and alphanumeric because it's gonna be used in an email address.
1035
      SecureRandom.hex.to_i(16).to_s(36)
1036 1037 1038 1039
    else
      super
    end
  end
1040

1041 1042 1043 1044 1045 1046
  def self.unique_internal(scope, username, email_pattern, &b)
    scope.first || create_unique_internal(scope, username, email_pattern, &b)
  end

  def self.create_unique_internal(scope, username, email_pattern, &creation_block)
    # Since we only want a single one of these in an instance, we use an
1047
    # exclusive lease to ensure than this block is never run concurrently.
1048
    lease_key = "user:unique_internal:#{username}"
1049 1050 1051 1052 1053 1054 1055 1056
    lease = Gitlab::ExclusiveLease.new(lease_key, timeout: 1.minute.to_i)

    until uuid = lease.try_obtain
      # Keep trying until we obtain the lease. To prevent hammering Redis too
      # much we'll wait for a bit between retries.
      sleep(1)
    end

1057
    # Recheck if the user is already present. One might have been
1058 1059
    # added between the time we last checked (first line of this method)
    # and the time we acquired the lock.
1060 1061
    existing_user = uncached { scope.first }
    return existing_user if existing_user.present?
1062 1063 1064

    uniquify = Uniquify.new

1065
    username = uniquify.string(username) { |s| User.find_by_username(s) }
1066

1067
    email = uniquify.string(-> (n) { Kernel.sprintf(email_pattern, n) }) do |s|
1068 1069 1070
      User.find_by_email(s)
    end

1071 1072 1073 1074
    scope.create(
      username: username,
      email: email,
      &creation_block
1075 1076 1077 1078
    )
  ensure
    Gitlab::ExclusiveLease.cancel(lease_key, uuid)
  end
G
gitlabhq 已提交
1079
end