user.rb 28.5 KB
Newer Older
1 2
require 'carrierwave/orm/activerecord'

gitlabhq's avatar
gitlabhq committed
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 :theme_id, gitlab_config.default_theme
25

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

32
  devise :two_factor_authenticatable,
33
         otp_secret_encryption_key: Gitlab::Application.secrets.otp_key_base
34

35
  devise :two_factor_backupable, otp_number_of_backup_codes: 10
36 37
  serialize :otp_backup_codes, JSON

38
  devise :lockable, :recoverable, :rememberable, :trackable,
39
    :validatable, :omniauthable, :confirmable, :registerable
gitlabhq's avatar
gitlabhq committed
40

41
  attr_accessor :force_random_password
gitlabhq's avatar
gitlabhq committed
42

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

46 47 48 49
  #
  # Relations
  #

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

  # Profile
  has_many :keys, dependent: :destroy
55
  has_many :emails, dependent: :destroy
56
  has_many :personal_access_tokens, dependent: :destroy
57
  has_many :identities, dependent: :destroy, autosave: true
58
  has_many :u2f_registrations, dependent: :destroy
59 60

  # Groups
61
  has_many :members, dependent: :destroy
62
  has_many :group_members, -> { where(requested_at: nil) }, dependent: :destroy, source: 'GroupMember'
63
  has_many :groups, through: :group_members
64 65
  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
66

67
  # Projects
68 69
  has_many :groups_projects,          through: :groups, source: :projects
  has_many :personal_projects,        through: :namespace, source: :projects
70
  has_many :project_members, -> { where(requested_at: nil) }, dependent: :destroy
71
  has_many :projects,                 through: :project_members
72
  has_many :created_projects,         foreign_key: :creator_id, class_name: 'Project'
Ciro Santilli's avatar
Ciro Santilli committed
73 74
  has_many :users_star_projects, dependent: :destroy
  has_many :starred_projects, through: :users_star_projects, source: :project
75

76
  has_many :snippets,                 dependent: :destroy, foreign_key: :author_id
77 78 79
  has_many :issues,                   dependent: :destroy, foreign_key: :author_id
  has_many :notes,                    dependent: :destroy, foreign_key: :author_id
  has_many :merge_requests,           dependent: :destroy, foreign_key: :author_id
80
  has_many :events,                   dependent: :destroy, foreign_key: :author_id
81
  has_many :subscriptions,            dependent: :destroy
82
  has_many :recent_events, -> { order "id DESC" }, foreign_key: :author_id,   class_name: "Event"
83 84
  has_many :assigned_issues,          dependent: :destroy, foreign_key: :assignee_id, class_name: "Issue"
  has_many :assigned_merge_requests,  dependent: :destroy, foreign_key: :assignee_id, class_name: "MergeRequest"
Valery Sizov's avatar
Valery Sizov committed
85
  has_many :oauth_applications, class_name: 'Doorkeeper::Application', as: :owner, dependent: :destroy
86
  has_one  :abuse_report,             dependent: :destroy
87
  has_many :spam_logs,                dependent: :destroy
88
  has_many :builds,                   dependent: :nullify, class_name: 'Ci::Build'
89
  has_many :pipelines,                dependent: :nullify, class_name: 'Ci::Pipeline'
90
  has_many :todos,                    dependent: :destroy
91
  has_many :notification_settings,    dependent: :destroy
92
  has_many :award_emoji,              dependent: :destroy
93

94 95 96
  #
  # Validations
  #
97
  # Note: devise :validatable above adds validations for :email and :password
Cyril's avatar
Cyril committed
98
  validates :name, presence: true
99 100
  validates :notification_email, presence: true
  validates :notification_email, email: true, if: ->(user) { user.notification_email != user.email }
101
  validates :public_email, presence: true, uniqueness: true, email: true, allow_blank: true
102
  validates :bio, length: { maximum: 255 }, allow_blank: true
103
  validates :projects_limit, presence: true, numericality: { greater_than_or_equal_to: 0 }
104
  validates :username,
105
    namespace: true,
106
    presence: true,
107
    uniqueness: { case_sensitive: false }
108

109
  validate :namespace_uniq, if: ->(user) { user.username_changed? }
110
  validate :avatar_type, if: ->(user) { user.avatar.present? && user.avatar_changed? }
111
  validate :unique_email, if: ->(user) { user.email_changed? }
112
  validate :owns_notification_email, if: ->(user) { user.notification_email_changed? }
113
  validate :owns_public_email, if: ->(user) { user.public_email_changed? }
114
  validates :avatar, file_size: { maximum: 200.kilobytes.to_i }
115

116
  before_validation :generate_password, on: :create
117
  before_validation :signup_domain_valid?, on: :create
118
  before_validation :sanitize_attrs
119
  before_validation :set_notification_email, if: ->(user) { user.email_changed? }
120
  before_validation :set_public_email, if: ->(user) { user.public_email_changed? }
121

122
  after_update :update_emails_with_primary_email, if: ->(user) { user.email_changed? }
123
  before_save :ensure_authentication_token, :ensure_incoming_email_token
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
124
  before_save :ensure_external_user_rights
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
125
  after_save :ensure_namespace_correct
126
  after_initialize :set_projects_limit
127
  before_create :check_confirmation_email
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
128 129 130
  after_create :post_create_hook
  after_destroy :post_destroy_hook

131
  # User's Layout preference
132
  enum layout: [:fixed, :fluid]
133

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

138 139
  # User's Project preference
  # Note: When adding an option, it MUST go on the end of the array.
140
  enum project_view: [:readme, :activity, :files]
141

Nihad Abbasov's avatar
Nihad Abbasov committed
142
  alias_attribute :private_token, :authentication_token
143

144
  delegate :path, to: :namespace, allow_nil: true, prefix: true
145

146 147 148
  state_machine :state, initial: :active do
    event :block do
      transition active: :blocked
149
      transition ldap_blocked: :blocked
150 151
    end

152 153 154 155
    event :ldap_block do
      transition active: :ldap_blocked
    end

156 157
    event :activate do
      transition blocked: :active
158
      transition ldap_blocked: :active
159
    end
160 161 162 163 164 165

    state :blocked, :ldap_blocked do
      def blocked?
        true
      end
    end
166 167
  end

168
  mount_uploader :avatar, AvatarUploader
169

Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
170
  # Scopes
171
  scope :admins, -> { where(admin: true) }
172
  scope :blocked, -> { with_states(:blocked, :ldap_blocked) }
173
  scope :external, -> { where(external: true) }
174
  scope :active, -> { with_state(:active) }
skv's avatar
skv committed
175
  scope :not_in_project, ->(project) { project.users.present? ? where("id not in (:ids)", ids: project.users.map(&:id) ) : all }
176
  scope :without_projects, -> { where('id NOT IN (SELECT DISTINCT(user_id) FROM members)') }
177
  scope :todo_authors, ->(user_id, state) { where(id: Todo.where(user_id: user_id, state: state).select(:author_id)) }
178 179 180 181 182 183 184 185 186 187

  def self.with_two_factor
    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])
  end

  def self.without_two_factor
    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)
  end
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
188

189 190 191
  #
  # Class methods
  #
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
192
  class << self
193
    # Devise method overridden to allow sign in with email or username
194 195 196
    def find_for_database_authentication(warden_conditions)
      conditions = warden_conditions.dup
      if login = conditions.delete(:login)
Gabriel Mazetto's avatar
Gabriel Mazetto committed
197
        where(conditions).find_by("lower(username) = :value OR lower(email) = :value", value: login.downcase)
198
      else
Gabriel Mazetto's avatar
Gabriel Mazetto committed
199
        find_by(conditions)
200 201
      end
    end
202

Valery Sizov's avatar
Valery Sizov committed
203 204
    def sort(method)
      case method.to_s
205 206 207 208
      when 'recent_sign_in' then reorder(last_sign_in_at: :desc)
      when 'oldest_sign_in' then reorder(last_sign_in_at: :asc)
      else
        order_by(method)
Valery Sizov's avatar
Valery Sizov committed
209 210 211
      end
    end

212 213
    # Find a User by their primary email or any associated secondary email
    def find_by_any_email(email)
214 215 216 217 218 219 220
      sql = 'SELECT *
      FROM users
      WHERE id IN (
        SELECT id FROM users WHERE email = :email
        UNION
        SELECT emails.user_id FROM emails WHERE email = :email
      )
221 222 223
      LIMIT 1;'

      User.find_by_sql([sql, { email: email }]).first
224
    end
225

226
    def filter(filter_name)
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
227
      case filter_name
228 229 230 231 232 233 234 235 236 237
      when 'admins'
        self.admins
      when 'blocked'
        self.blocked
      when 'two_factor_disabled'
        self.without_two_factor
      when 'two_factor_enabled'
        self.with_two_factor
      when 'wop'
        self.without_projects
238 239
      when 'external'
        self.external
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
240 241 242
      else
        self.active
      end
243 244
    end

245 246 247 248 249 250 251
    # 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.
252
    def search(query)
253
      table   = arel_table
254 255 256 257 258 259 260
      pattern = "%#{query}%"

      where(
        table[:name].matches(pattern).
          or(table[:email].matches(pattern)).
          or(table[:username].matches(pattern))
      )
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
261
    end
262

263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
    # 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(
        table[:name].matches(pattern).
          or(table[:email].matches(pattern)).
          or(table[:username].matches(pattern)).
          or(table[:id].in(matched_by_emails_user_ids))
      )
    end

281
    def by_login(login)
282 283 284 285 286 287 288
      return nil unless login

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

291 292 293 294
    def find_by_username!(username)
      find_by!('lower(username) = ?', username.downcase)
    end

295 296 297 298 299
    def find_by_personal_access_token(token_string)
      personal_access_token = PersonalAccessToken.active.find_by_token(token_string) if token_string
      personal_access_token.user if personal_access_token
    end

300
    def by_username_or_id(name_or_id)
Gabriel Mazetto's avatar
Gabriel Mazetto committed
301
      find_by('users.username = ? OR users.id = ?', name_or_id.to_s, name_or_id.to_i)
302
    end
303

304 305 306 307 308
    # 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

309 310
    def build_user(attrs = {})
      User.new(attrs)
311
    end
312 313 314 315

    def reference_prefix
      '@'
    end
316 317 318 319 320 321 322 323

    # Pattern used to extract `@user` user references from text
    def reference_pattern
      %r{
        #{Regexp.escape(reference_prefix)}
        (?<user>#{Gitlab::Regex::NAMESPACE_REGEX_STR})
      }x
    end
vsizov's avatar
vsizov committed
324
  end
randx's avatar
randx committed
325

326 327 328
  #
  # Instance methods
  #
329 330 331 332 333

  def to_param
    username
  end

Timothy Andrew's avatar
Timothy Andrew committed
334
  def to_reference(_from_project = nil, _target_project = nil)
335 336 337
    "#{self.class.reference_prefix}#{username}"
  end

Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
338 339
  def generate_password
    if self.force_random_password
340
      self.password = self.password_confirmation = Devise.friendly_token.first(Devise.password_length.min)
Andrey Kumanyaev's avatar
Andrey Kumanyaev committed
341
    end
randx's avatar
randx committed
342
  end
343

344
  def generate_reset_token
345
    @reset_token, enc = Devise.token_generator.generate(self.class, :reset_password_token)
346 347 348 349

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

350
    @reset_token
351 352
  end

353
  def check_confirmation_email
354
    skip_confirmation! unless current_application_settings.send_user_confirmation_email
355 356
  end

357 358 359 360
  def recently_sent_password_reset?
    reset_password_sent_at.present? && reset_password_sent_at >= 1.minute.ago
  end

361
  def disable_two_factor!
362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    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?
    self.otp_required_for_login?
  end

  def two_factor_u2f_enabled?
    self.u2f_registrations.exists?
385 386
  end

387
  def namespace_uniq
388
    # Return early if username already failed the first uniqueness validation
389 390
    return if self.errors.key?(:username) &&
      self.errors[:username].include?('has already been taken')
391

392
    namespace_name = self.username
393 394
    existing_namespace = Namespace.by_path(namespace_name)
    if existing_namespace && existing_namespace != self.namespace
395
      self.errors.add(:username, 'has already been taken')
396 397
    end
  end
398

399 400 401 402 403 404
  def avatar_type
    unless self.avatar.image?
      self.errors.add :avatar, "only images allowed"
    end
  end

405
  def unique_email
406 407 408
    if !self.emails.exists?(email: self.email) && Email.exists?(email: self.email)
      self.errors.add(:email, 'has already been taken')
    end
409 410
  end

411
  def owns_notification_email
412 413
    return if self.temp_oauth_email?

414 415 416
    self.errors.add(:notification_email, "is not an email you own") unless self.all_emails.include?(self.notification_email)
  end

417
  def owns_public_email
418 419
    return if self.public_email.blank?

420 421 422 423 424 425 426 427
    self.errors.add(:public_email, "is not an email you own") unless self.all_emails.include?(self.public_email)
  end

  def update_emails_with_primary_email
    primary_email_record = self.emails.find_by(email: self.email)
    if primary_email_record
      primary_email_record.destroy
      self.emails.create(email: self.email_was)
428

429 430 431 432
      self.update_secondary_emails!
    end
  end

433 434
  # Returns the groups a user has access to
  def authorized_groups
435
    union = Gitlab::SQL::Union.
436
      new([groups.select(:id), authorized_projects.select(:namespace_id)])
437

438
    Group.where("namespaces.id IN (#{union.to_sql})")
439 440
  end

441
  # Returns projects user is authorized to access.
442 443
  #
  # If you change the logic of this method, please also update `Project#authorized_for_user`
444 445
  def authorized_projects(min_access_level = nil)
    Project.where("projects.id IN (#{projects_union(min_access_level).to_sql})")
446 447
  end

448 449
  def viewable_starred_projects
    starred_projects.where("projects.visibility_level IN (?) OR projects.id IN (#{projects_union.to_sql})",
Sean McGivern's avatar
Sean McGivern committed
450
                           [Project::PUBLIC, Project::INTERNAL])
451 452
  end

453
  def owned_projects
454
    @owned_projects ||=
455 456
      Project.where('namespace_id IN (?) OR namespace_id = ?',
                    owned_groups.select(:id), namespace.id).joins(:namespace)
457 458
  end

459 460 461 462
  # 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
463
    authorized_projects(Gitlab::Access::REPORTER).non_archived.with_issues_enabled
464 465
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
466 467 468 469 470 471 472 473
  def is_admin?
    admin
  end

  def require_ssh_key?
    keys.count == 0
  end

474 475 476 477
  def require_password?
    password_automatically_set? && !ldap_user?
  end

478
  def can_change_username?
479
    gitlab_config.username_changing_enabled
480 481
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
482
  def can_create_project?
483
    projects_limit_left > 0
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
484 485 486
  end

  def can_create_group?
487
    can?(:create_group, nil)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
488 489
  end

490 491 492 493
  def can_select_namespace?
    several_namespaces? || admin
  end

494
  def can?(action, subject)
495
    Ability.allowed?(self, action, subject)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
496 497 498 499 500 501 502
  end

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

  def cared_merge_requests
503
    MergeRequest.cared(self)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
504 505
  end

506
  def projects_limit_left
507
    projects_limit - personal_projects.count
508 509
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
510 511
  def projects_limit_percent
    return 100 if projects_limit.zero?
512
    (personal_projects.count.to_f / projects_limit) * 100
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
513 514
  end

515
  def recent_push(project_ids = nil)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
516 517
    # Get push events not earlier than 2 hours ago
    events = recent_events.code_push.where("created_at > ?", Time.now - 2.hours)
518
    events = events.where(project_id: project_ids) if project_ids
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
519

520 521 522 523 524
    # 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

525
      if project.repository.branch_exists?(event.branch_name)
526 527 528 529 530 531
        merge_requests = MergeRequest.where("created_at >= ?", event.created_at).
            where(source_project_id: project.id,
                  source_branch: event.branch_name)
        merge_requests.empty?
      end
    end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
532 533 534 535 536 537 538
  end

  def projects_sorted_by_activity
    authorized_projects.sorted_by_activity
  end

  def several_namespaces?
539
    owned_groups.any? || masters_groups.any?
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
540 541 542 543 544
  end

  def namespace_id
    namespace.try :id
  end
545

546 547 548
  def name_with_username
    "#{name} (#{username})"
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
549

550
  def already_forked?(project)
551 552 553
    !!fork_of(project)
  end

554
  def fork_of(project)
555 556 557 558 559 560 561 562
    links = ForkedProjectLink.where(forked_from_project_id: project, forked_to_project_id: personal_projects)

    if links.any?
      links.first.forked_to_project
    else
      nil
    end
  end
563 564

  def ldap_user?
565 566 567 568 569
    identities.exists?(["provider LIKE ? AND extern_uid IS NOT NULL", "ldap%"])
  end

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

572
  def project_deploy_keys
573
    DeployKey.unscoped.in_projects(self.authorized_projects.pluck(:id)).distinct(:id)
574 575
  end

576
  def accessible_deploy_keys
577 578 579 580 581
    @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
582
  end
583 584

  def created_by
skv's avatar
skv committed
585
    User.find_by(id: created_by_id) if created_by_id
586
  end
587 588

  def sanitize_attrs
589
    %w(name username skype linkedin twitter).each do |attr|
590 591 592 593
      value = self.send(attr)
      self.send("#{attr}=", Sanitize.clean(value)) if value.present?
    end
  end
594

595 596
  def set_notification_email
    if self.notification_email.blank? || !self.all_emails.include?(self.notification_email)
597
      self.notification_email = self.email
598 599 600
    end
  end

601 602
  def set_public_email
    if self.public_email.blank? || !self.all_emails.include?(self.public_email)
603
      self.public_email = ''
604 605 606
    end
  end

607 608 609 610 611 612
  def update_secondary_emails!
    self.set_notification_email
    self.set_public_email
    self.save if self.notification_email_changed? || self.public_email_changed?
  end

613
  def set_projects_limit
614 615 616 617 618
    # `User.select(:id)` raises
    # `ActiveModel::MissingAttributeError: missing attribute: projects_limit`
    # without this safeguard!
    return unless self.has_attribute?(:projects_limit)

619 620 621 622 623 624
    connection_default_value_defined = new_record? && !projects_limit_changed?
    return unless self.projects_limit.nil? || connection_default_value_defined

    self.projects_limit = current_application_settings.default_projects_limit
  end

625
  def requires_ldap_check?
626 627 628
    if !Gitlab.config.ldap.enabled
      false
    elsif ldap_user?
629 630 631 632 633 634
      !last_credential_check_at || (last_credential_check_at + 1.hour) < Time.now
    else
      false
    end
  end

Jacob Vosmaer's avatar
Jacob Vosmaer committed
635 636 637 638 639 640 641
  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

642 643 644 645 646
  def solo_owned_groups
    @solo_owned_groups ||= owned_groups.select do |group|
      group.owners == [self]
    end
  end
647 648

  def with_defaults
649 650
    User.defaults.each do |k, v|
      self.send("#{k}=", v)
651
    end
652 653

    self
654
  end
655

656 657 658 659
  def can_leave_project?(project)
    project.namespace != namespace &&
      project.project_member(self)
  end
660 661 662 663 664 665 666 667 668 669 670 671 672 673

  # Reset project events cache related to this user
  #
  # Since we do cache @event we need to reset cache in special cases:
  # * when the user changes their avatar
  # Events cache stored like  events/23-20130109142513.
  # The cache key includes updated_at timestamp.
  # Thus it will automatically generate a new fragment
  # when the event is updated because the key changes.
  def reset_events_cache
    Event.where(author_id: self.id).
      order('id DESC').limit(1000).
      update_all(updated_at: Time.now)
  end
Jerome Dalbert's avatar
Jerome Dalbert committed
674 675

  def full_website_url
676
    return "http://#{website_url}" if website_url !~ /\Ahttps?:\/\//
Jerome Dalbert's avatar
Jerome Dalbert committed
677 678 679 680 681

    website_url
  end

  def short_website_url
682
    website_url.sub(/\Ahttps?:\/\//, '')
Jerome Dalbert's avatar
Jerome Dalbert committed
683
  end
GitLab's avatar
GitLab committed
684

685
  def all_ssh_keys
686
    keys.map(&:publishable_key)
687
  end
688 689

  def temp_oauth_email?
690
    email.start_with?('temp-email-for-oauth')
691 692
  end

693
  def avatar_url(size = nil, scale = 2)
694
    if self[:avatar].present?
695
      [gitlab_config.url, avatar.url].join
696
    else
697
      GravatarService.new.execute(email, size, scale)
698 699
    end
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
700

701
  def all_emails
702 703 704 705
    all_emails = []
    all_emails << self.email unless self.temp_oauth_email?
    all_emails.concat(self.emails.map(&:email))
    all_emails
706 707
  end

Kirill Zaitsev's avatar
Kirill Zaitsev committed
708 709 710 711 712 713 714 715
  def hook_attrs
    {
      name: name,
      username: username,
      avatar_url: avatar_url
    }
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
716 717 718 719 720 721 722 723 724 725 726
  def ensure_namespace_correct
    # Ensure user has namespace
    self.create_namespace!(path: self.username, name: self.username) unless self.namespace

    if self.username_changed?
      self.namespace.update_attributes(path: self.username, name: self.username)
    end
  end

  def post_create_hook
    log_info("User \"#{self.name}\" (#{self.email}) was created")
727
    notification_service.new_user(self, @reset_token) if self.created_by_id
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
728 729 730 731 732 733 734 735
    system_hook_service.execute_hooks_for(self, :create)
  end

  def post_destroy_hook
    log_info("User \"#{self.name}\" (#{self.email})  was removed")
    system_hook_service.execute_hooks_for(self, :destroy)
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
736
  def notification_service
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
737 738 739
    NotificationService.new
  end

740
  def log_info(message)
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
741 742 743 744 745 746
    Gitlab::AppLogger.info message
  end

  def system_hook_service
    SystemHooksService.new
  end
Ciro Santilli's avatar
Ciro Santilli committed
747 748

  def starred?(project)
749
    starred_projects.exists?(project.id)
Ciro Santilli's avatar
Ciro Santilli committed
750 751 752
  end

  def toggle_star(project)
753 754 755 756 757 758 759 760 761
    UsersStarProject.transaction do
      user_star_project = users_star_projects.
          where(project: project, user: self).lock(true).first

      if user_star_project
        user_star_project.destroy
      else
        UsersStarProject.create!(project: project, user: self)
      end
Ciro Santilli's avatar
Ciro Santilli committed
762 763
    end
  end
764 765

  def manageable_namespaces
766
    @manageable_namespaces ||= [namespace] + owned_groups + masters_groups
767
  end
Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
768

769 770 771 772 773 774
  def namespaces
    namespace_ids = groups.pluck(:id)
    namespace_ids.push(namespace.id)
    Namespace.where(id: namespace_ids)
  end

Dmitriy Zaporozhets's avatar
Dmitriy Zaporozhets committed
775 776 777
  def oauth_authorized_tokens
    Doorkeeper::AccessToken.where(resource_owner_id: self.id, revoked_at: nil)
  end
778

779 780 781 782 783 784 785 786 787
  # 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
788
  # ms on a database with a similar size to GitLab.com's database. On the other
789 790 791 792
  # hand, using a subquery means we can get the exact same data in about 40 ms.
  def contributed_projects
    events = Event.select(:project_id).
      contributions.where(author_id: self).
793
      where("created_at > ?", Time.now - 1.year).
794
      uniq.
795 796 797
      reorder(nil)

    Project.where(id: events)
798
  end
799

800 801 802
  def can_be_removed?
    !solo_owned_groups.present?
  end
803 804

  def ci_authorized_runners
805
    @ci_authorized_runners ||= begin
806 807
      runner_ids = Ci::RunnerProject.
        where("ci_runner_projects.gl_project_id IN (#{ci_projects_union.to_sql})").
808
        select(:runner_id)
809 810
      Ci::Runner.specific.where(id: runner_ids)
    end
811
  end
812

813 814 815 816
  def notification_settings_for(source)
    notification_settings.find_or_initialize_by(source: source)
  end

817 818 819
  # Lazy load global notification setting
  # Initializes User setting with Participating level if setting not persisted
  def global_notification_setting
820 821 822 823 824 825
    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
826 827
  end

828 829
  def assigned_open_merge_request_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_merge_request_count'], force: force) do
830 831 832 833
      assigned_merge_requests.opened.count
    end
  end

834 835
  def assigned_open_issues_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_issues_count'], force: force) do
836 837
      assigned_issues.opened.count
    end
838 839
  end

840 841 842 843 844
  def update_cache_counts
    assigned_open_merge_request_count(force: true)
    assigned_open_issues_count(force: true)
  end

845 846
  def todos_done_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_done_count'], force: force) do
847
      TodosFinder.new(self, state: :done).execute.count
848 849 850 851 852
    end
  end

  def todos_pending_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_pending_count'], force: force) do
853
      TodosFinder.new(self, state: :pending).execute.count
854 855 856 857 858 859 860 861
    end
  end

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

862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
  # 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

878 879
  private

880
  def projects_union(min_access_level = nil)
881 882 883 884 885 886
    relations = [personal_projects.select(:id),
                 groups_projects.select(:id),
                 projects.select(:id),
                 groups.joins(:shared_projects).select(:project_id)]

    if min_access_level
887
      scope = { access_level: Gitlab::Access.all_values.select { |access| access >= min_access_level } }
888 889
      relations = [relations.shift] + relations.map { |relation| relation.where(members: scope) }
    end
890 891

    Gitlab::SQL::Union.new(relations)
892
  end
893 894 895 896 897 898 899 900 901

  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
902 903 904 905 906

  # 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
Zeger-Jan van de Weg's avatar
Zeger-Jan van de Weg committed
907 908 909 910 911 912 913

  def ensure_external_user_rights
    return unless self.external?

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

915 916 917 918 919 920
  def signup_domain_valid?
    valid = true
    error = nil

    if current_application_settings.domain_blacklist_enabled?
      blocked_domains = current_application_settings.domain_blacklist
921
      if domain_matches?(blocked_domains, self.email)
922 923 924 925 926
        error = 'is not from an allowed domain.'
        valid = false
      end
    end

927
    allowed_domains = current_application_settings.domain_whitelist
928
    unless allowed_domains.blank?
929
      if domain_matches?(allowed_domains, self.email)
930 931
        valid = true
      else
932
        error = "domain is not authorized for sign-up"
933 934 935 936 937 938 939 940
        valid = false
      end
    end

    self.errors.add(:email, error) unless valid

    valid
  end
941

942
  def domain_matches?(email_domains, email)
943 944 945 946 947 948 949
    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
950 951 952 953 954 955 956 957 958

  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.
      SecureRandom.hex
    else
      super
    end
  end
gitlabhq's avatar
gitlabhq committed
959
end