BigW Consortium Gitlab

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

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 :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
35

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

39
  devise :lockable, :recoverable, :rememberable, :trackable,
40
    :validatable, :omniauthable, :confirmable, :registerable
gitlabhq committed
41

42
  attr_accessor :force_random_password
gitlabhq committed
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'
Ciro Santilli committed
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"
Valery Sizov committed
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
100
  has_many :triggers,                 dependent: :destroy, class_name: 'Ci::Trigger', foreign_key: :owner_id
101

102 103 104
  has_many :assigned_issues,          dependent: :nullify, foreign_key: :assignee_id, class_name: "Issue"
  has_many :assigned_merge_requests,  dependent: :nullify, foreign_key: :assignee_id, class_name: "MergeRequest"

105 106 107 108 109
  # 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

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

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

136
  before_validation :sanitize_attrs
137
  before_validation :set_notification_email, if: ->(user) { user.email_changed? }
138
  before_validation :set_public_email, if: ->(user) { user.public_email_changed? }
139

140
  after_update :update_emails_with_primary_email, if: ->(user) { user.email_changed? }
141
  before_save :ensure_authentication_token, :ensure_incoming_email_token
Zeger-Jan van de Weg committed
142
  before_save :ensure_external_user_rights
143
  after_save :ensure_namespace_correct
144
  after_initialize :set_projects_limit
145 146
  after_destroy :post_destroy_hook

147
  # User's Layout preference
148
  enum layout: [:fixed, :fluid]
149

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

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

158
  alias_attribute :private_token, :authentication_token
159

160
  delegate :path, to: :namespace, allow_nil: true, prefix: true
161

162 163 164
  state_machine :state, initial: :active do
    event :block do
      transition active: :blocked
165
      transition ldap_blocked: :blocked
166 167
    end

168 169 170 171
    event :ldap_block do
      transition active: :ldap_blocked
    end

172 173
    event :activate do
      transition blocked: :active
174
      transition ldap_blocked: :active
175
    end
176 177 178 179 180

    state :blocked, :ldap_blocked do
      def blocked?
        true
      end
181 182 183 184 185 186 187 188 189

      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
190
    end
191 192
  end

193
  mount_uploader :avatar, AvatarUploader
194
  has_many :uploads, as: :model, dependent: :destroy
195

Andrey Kumanyaev committed
196
  # Scopes
197
  scope :admins, -> { where(admin: true) }
198
  scope :blocked, -> { with_states(:blocked, :ldap_blocked) }
199
  scope :external, -> { where(external: true) }
James Lopez committed
200
  scope :active, -> { with_state(:active).non_internal }
skv committed
201
  scope :not_in_project, ->(project) { project.users.present? ? where("id not in (:ids)", ids: project.users.map(&:id) ) : all }
202
  scope :without_projects, -> { where('id NOT IN (SELECT DISTINCT(user_id) FROM members WHERE user_id IS NOT NULL AND requested_at IS NULL)') }
203
  scope :todo_authors, ->(user_id, state) { where(id: Todo.where(user_id: user_id, state: state).select(:author_id)) }
204 205
  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')) }
206 207

  def self.with_two_factor
208 209
    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])
210 211 212
  end

  def self.without_two_factor
213 214
    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)
215
  end
Andrey Kumanyaev committed
216

217 218 219
  #
  # Class methods
  #
Andrey Kumanyaev committed
220
  class << self
221
    # Devise method overridden to allow sign in with email or username
222 223 224
    def find_for_database_authentication(warden_conditions)
      conditions = warden_conditions.dup
      if login = conditions.delete(:login)
225
        where(conditions).find_by("lower(username) = :value OR lower(email) = :value", value: login.downcase)
226
      else
227
        find_by(conditions)
228 229
      end
    end
230

Valery Sizov committed
231 232
    def sort(method)
      case method.to_s
233 234
      when 'recent_sign_in' then order_recent_sign_in
      when 'oldest_sign_in' then order_oldest_sign_in
235 236
      else
        order_by(method)
Valery Sizov committed
237 238 239
      end
    end

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

      User.find_by_sql([sql, { email: email }]).first
252
    end
253

254
    def filter(filter_name)
Andrey Kumanyaev committed
255
      case filter_name
256
      when 'admins'
257
        admins
258
      when 'blocked'
259
        blocked
260
      when 'two_factor_disabled'
261
        without_two_factor
262
      when 'two_factor_enabled'
263
        with_two_factor
264
      when 'wop'
265
        without_projects
266
      when 'external'
267
        external
Andrey Kumanyaev committed
268
      else
269
        active
Andrey Kumanyaev committed
270
      end
271 272
    end

273 274 275 276 277 278 279
    # 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.
280
    def search(query)
281
      table   = arel_table
282 283 284
      pattern = "%#{query}%"

      where(
285 286 287
        table[:name].matches(pattern).
          or(table[:email].matches(pattern)).
          or(table[:username].matches(pattern))
288
      )
Andrey Kumanyaev committed
289
    end
290

291 292 293 294 295 296 297 298 299 300 301
    # 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(
302 303 304 305
        table[:name].matches(pattern).
          or(table[:email].matches(pattern)).
          or(table[:username].matches(pattern)).
          or(table[:id].in(matched_by_emails_user_ids))
306 307 308
      )
    end

309
    def by_login(login)
310 311 312 313 314 315 316
      return nil unless login

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

319 320 321 322
    def find_by_username(username)
      iwhere(username: username).take
    end

323
    def find_by_username!(username)
324
      iwhere(username: username).take!
325 326
    end

327
    def find_by_personal_access_token(token_string)
328 329
      return unless token_string

330
      PersonalAccessTokensFinder.new(state: 'active').find_by(token: token_string)&.user
331 332
    end

333 334 335 336 337
    # 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

338 339 340
    def reference_prefix
      '@'
    end
341 342 343 344 345

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

    # Return (create if necessary) the ghost user. The ghost user
    # owns records previously belonging to deleted users.
    def ghost
353 354 355 356
      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
357
    end
vsizov committed
358
  end
randx committed
359

360 361 362 363
  def self.internal_attributes
    [:ghost]
  end

364
  def internal?
365 366 367 368 369 370 371 372
    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
373
    where(Hash[internal_attributes.zip([[false, nil]] * internal_attributes.size)])
374 375
  end

376 377 378
  #
  # Instance methods
  #
379 380 381 382 383

  def to_param
    username
  end

384
  def to_reference(_from_project = nil, target_project: nil, full: nil)
385 386 387
    "#{self.class.reference_prefix}#{username}"
  end

388 389
  def skip_confirmation=(bool)
    skip_confirmation! if bool
randx committed
390
  end
391

392
  def generate_reset_token
393
    @reset_token, enc = Devise.token_generator.generate(self.class, :reset_password_token)
394 395 396 397

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

398
    @reset_token
399 400
  end

401 402 403 404
  def recently_sent_password_reset?
    reset_password_sent_at.present? && reset_password_sent_at >= 1.minute.ago
  end

405
  def disable_two_factor!
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423
    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?
424
    otp_required_for_login?
425 426 427
  end

  def two_factor_u2f_enabled?
428
    u2f_registrations.exists?
429 430
  end

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

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

442
  def avatar_type
443 444
    unless avatar.image?
      errors.add :avatar, "only images allowed"
445 446 447
    end
  end

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

454
  def owns_notification_email
455
    return if temp_oauth_email?
456

457
    errors.add(:notification_email, "is not an email you own") unless all_emails.include?(notification_email)
458 459
  end

460
  def owns_public_email
461
    return if public_email.blank?
462

463
    errors.add(:public_email, "is not an email you own") unless all_emails.include?(public_email)
464 465 466
  end

  def update_emails_with_primary_email
467
    primary_email_record = emails.find_by(email: email)
468 469
    if primary_email_record
      primary_email_record.destroy
470
      emails.create(email: email_was)
471

472
      update_secondary_emails!
473 474 475
    end
  end

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

481
    Group.where("namespaces.id IN (#{union.to_sql})")
482 483
  end

484 485 486 487
  def nested_groups
    Group.member_descendants(id)
  end

488 489 490 491 492 493 494 495
  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

496
  def nested_groups_projects
497 498
    Project.joins(:namespace).where('namespaces.parent_id IS NOT NULL').
      member_descendants(id)
499 500
  end

501
  def refresh_authorized_projects
502 503 504 505
    Users::RefreshAuthorizedProjectsService.new(self).execute
  end

  def remove_project_authorizations(project_ids)
506
    project_authorizations.where(project_id: project_ids).delete_all
507 508 509 510 511
  end

  def set_authorized_projects_column
    unless authorized_projects_populated
      update_column(:authorized_projects_populated, true)
512 513 514
    end
  end

515
  def authorized_projects(min_access_level = nil)
516 517 518 519 520 521 522 523 524 525 526
    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 })
527 528
  end

529 530 531 532 533 534 535 536 537 538
  # 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

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

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

551 552 553 554
  # 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
555
    authorized_projects(Gitlab::Access::REPORTER).non_archived.with_issues_enabled
556 557
  end

Dmitriy Zaporozhets committed
558
  def require_ssh_key?
559
    keys.count == 0 && Gitlab::ProtocolAccess.allowed?('ssh')
Dmitriy Zaporozhets committed
560 561
  end

562 563 564 565
  def require_password?
    password_automatically_set? && !ldap_user?
  end

566
  def can_change_username?
567
    gitlab_config.username_changing_enabled
568 569
  end

Dmitriy Zaporozhets committed
570
  def can_create_project?
571
    projects_limit_left > 0
Dmitriy Zaporozhets committed
572 573 574
  end

  def can_create_group?
575
    can?(:create_group)
Dmitriy Zaporozhets committed
576 577
  end

578 579 580 581
  def can_select_namespace?
    several_namespaces? || admin
  end

582
  def can?(action, subject = :global)
583
    Ability.allowed?(self, action, subject)
Dmitriy Zaporozhets committed
584 585 586 587 588 589
  end

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

590
  def projects_limit_left
591
    projects_limit - personal_projects.count
592 593
  end

Dmitriy Zaporozhets committed
594 595
  def projects_limit_percent
    return 100 if projects_limit.zero?
596
    (personal_projects.count.to_f / projects_limit) * 100
Dmitriy Zaporozhets committed
597 598
  end

599
  def recent_push(project_ids = nil)
Dmitriy Zaporozhets committed
600 601
    # Get push events not earlier than 2 hours ago
    events = recent_events.code_push.where("created_at > ?", Time.now - 2.hours)
602
    events = events.where(project_id: project_ids) if project_ids
Dmitriy Zaporozhets committed
603

604 605 606 607 608
    # 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

609
      if project.repository.branch_exists?(event.branch_name)
610 611 612
        merge_requests = MergeRequest.where("created_at >= ?", event.created_at).
          where(source_project_id: project.id,
                source_branch: event.branch_name)
613 614 615
        merge_requests.empty?
      end
    end
Dmitriy Zaporozhets committed
616 617 618 619 620 621 622
  end

  def projects_sorted_by_activity
    authorized_projects.sorted_by_activity
  end

  def several_namespaces?
623
    owned_groups.any? || masters_groups.any?
Dmitriy Zaporozhets committed
624 625 626 627 628
  end

  def namespace_id
    namespace.try :id
  end
629

630 631 632
  def name_with_username
    "#{name} (#{username})"
  end
633

634
  def already_forked?(project)
635 636 637
    !!fork_of(project)
  end

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

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

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

658
  def project_deploy_keys
659
    DeployKey.unscoped.in_projects(authorized_projects.pluck(:id)).distinct(:id)
660 661
  end

662
  def accessible_deploy_keys
663 664 665 666 667
    @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
668
  end
669 670

  def created_by
skv committed
671
    User.find_by(id: created_by_id) if created_by_id
672
  end
673 674

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

681
  def set_notification_email
682 683
    if notification_email.blank? || !all_emails.include?(notification_email)
      self.notification_email = email
684 685 686
    end
  end

687
  def set_public_email
688
    if public_email.blank? || !all_emails.include?(public_email)
689
      self.public_email = ''
690 691 692
    end
  end

693
  def update_secondary_emails!
694 695 696
    set_notification_email
    set_public_email
    save if notification_email_changed? || public_email_changed?
697 698
  end

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

705
    connection_default_value_defined = new_record? && !projects_limit_changed?
706
    return unless projects_limit.nil? || connection_default_value_defined
707 708 709 710

    self.projects_limit = current_application_settings.default_projects_limit
  end

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

Jacob Vosmaer committed
721 722 723 724 725 726 727
  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

728 729 730 731 732
  def solo_owned_groups
    @solo_owned_groups ||= owned_groups.select do |group|
      group.owners == [self]
    end
  end
733 734

  def with_defaults
735
    User.defaults.each do |k, v|
736
      public_send("#{k}=", v)
737
    end
738 739

    self
740
  end
741

742 743 744 745
  def can_leave_project?(project)
    project.namespace != namespace &&
      project.project_member(self)
  end
746

Jerome Dalbert committed
747
  def full_website_url
748
    return "http://#{website_url}" if website_url !~ /\Ahttps?:\/\//
Jerome Dalbert committed
749 750 751 752 753

    website_url
  end

  def short_website_url
754
    website_url.sub(/\Ahttps?:\/\//, '')
Jerome Dalbert committed
755
  end
GitLab committed
756

757
  def all_ssh_keys
758
    keys.map(&:publishable_key)
759
  end
760 761

  def temp_oauth_email?
762
    email.start_with?('temp-email-for-oauth')
763 764
  end

765
  def avatar_url(size = nil, scale = 2)
766
    if self[:avatar].present?
767
      [gitlab_config.url, avatar.url].join
768
    else
769
      GravatarService.new.execute(email, size, scale)
770 771
    end
  end
772

773
  def all_emails
774
    all_emails = []
775 776
    all_emails << email unless temp_oauth_email?
    all_emails.concat(emails.map(&:email))
777
    all_emails
778 779
  end

Kirill Zaitsev committed
780 781 782 783 784 785 786 787
  def hook_attrs
    {
      name: name,
      username: username,
      avatar_url: avatar_url
    }
  end

788 789
  def ensure_namespace_correct
    # Ensure user has namespace
790
    create_namespace!(path: username, name: username) unless namespace
791

792 793
    if username_changed?
      namespace.update_attributes(path: username, name: username)
794 795 796 797
    end
  end

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

802
  def notification_service
803 804 805
    NotificationService.new
  end

806
  def log_info(message)
807 808 809 810 811 812
    Gitlab::AppLogger.info message
  end

  def system_hook_service
    SystemHooksService.new
  end
Ciro Santilli committed
813 814

  def starred?(project)
815
    starred_projects.exists?(project.id)
Ciro Santilli committed
816 817 818
  end

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

      if user_star_project
        user_star_project.destroy
      else
        UsersStarProject.create!(project: project, user: self)
      end
Ciro Santilli committed
828 829
    end
  end
830 831

  def manageable_namespaces
832
    @manageable_namespaces ||= [namespace] + owned_groups + masters_groups
833
  end
834

835 836 837 838 839 840
  def namespaces
    namespace_ids = groups.pluck(:id)
    namespace_ids.push(namespace.id)
    Namespace.where(id: namespace_ids)
  end

841
  def oauth_authorized_tokens
842
    Doorkeeper::AccessToken.where(resource_owner_id: id, revoked_at: nil)
843
  end
844

845 846 847 848 849 850 851 852 853
  # 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
854
  # ms on a database with a similar size to GitLab.com's database. On the other
855 856
  # hand, using a subquery means we can get the exact same data in about 40 ms.
  def contributed_projects
857 858 859 860 861
    events = Event.select(:project_id).
      contributions.where(author_id: self).
      where("created_at > ?", Time.now - 1.year).
      uniq.
      reorder(nil)
862 863

    Project.where(id: events)
864
  end
865

866 867 868
  def can_be_removed?
    !solo_owned_groups.present?
  end
869 870

  def ci_authorized_runners
871
    @ci_authorized_runners ||= begin
872
      runner_ids = Ci::RunnerProject.
873
        where("ci_runner_projects.project_id IN (#{ci_projects_union.to_sql})").
874
        select(:runner_id)
875 876
      Ci::Runner.specific.where(id: runner_ids)
    end
877
  end
878

879 880 881 882
  def notification_settings_for(source)
    notification_settings.find_or_initialize_by(source: source)
  end

883 884 885
  # Lazy load global notification setting
  # Initializes User setting with Participating level if setting not persisted
  def global_notification_setting
886 887 888 889 890 891
    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
892 893
  end

894 895
  def assigned_open_merge_request_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_merge_request_count'], force: force) do
896 897 898 899
      assigned_merge_requests.opened.count
    end
  end

900 901
  def assigned_open_issues_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_issues_count'], force: force) do
902 903
      assigned_issues.opened.count
    end
904 905
  end

906 907 908 909 910
  def update_cache_counts
    assigned_open_merge_request_count(force: true)
    assigned_open_issues_count(force: true)
  end

911 912
  def todos_done_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_done_count'], force: force) do
913
      TodosFinder.new(self, state: :done).execute.count
914 915 916 917 918
    end
  end

  def todos_pending_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_pending_count'], force: force) do
919
      TodosFinder.new(self, state: :pending).execute.count
920 921 922 923 924 925 926 927
    end
  end

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

928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
  # 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

944 945 946 947 948 949 950 951 952
  def access_level
    if admin?
      :admin
    else
      :regular
    end
  end

  def access_level=(new_level)
Douwe Maan committed
953 954
    new_level = new_level.to_s
    return unless %w(admin regular).include?(new_level)
955

Douwe Maan committed
956 957
    self.admin = (new_level == 'admin')
  end
958

959
  def update_two_factor_requirement
960
    periods = expanded_groups_requiring_two_factor_authentication.pluck(:two_factor_grace_period)
961

962
    self.require_two_factor_authentication_from_group = periods.any?
963 964 965 966 967
    self.two_factor_grace_period = periods.min || User.column_defaults['two_factor_grace_period']

    save
  end

968 969 970 971 972 973 974 975
  protected

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

976 977
  private

978 979 980 981 982 983 984 985
  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
986 987 988 989 990

  # 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 committed
991 992

  def ensure_external_user_rights
993
    return unless external?
Zeger-Jan van de Weg committed
994 995 996 997

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

999 1000 1001 1002 1003 1004
  def signup_domain_valid?
    valid = true
    error = nil

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

1011
    allowed_domains = current_application_settings.domain_whitelist
1012
    unless allowed_domains.blank?
1013
      if domain_matches?(allowed_domains, email)
1014 1015
        valid = true
      else
1016
        error = "domain is not authorized for sign-up"
1017 1018 1019 1020
        valid = false
      end
    end

1021
    errors.add(:email, error) unless valid
1022 1023 1024

    valid
  end
1025

1026
  def domain_matches?(email_domains, email)
1027 1028 1029 1030 1031 1032 1033
    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
1034 1035 1036 1037

  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.
1038
      SecureRandom.hex.to_i(16).to_s(36)
1039 1040 1041 1042
    else
      super
    end
  end
1043

1044 1045 1046 1047 1048 1049
  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
1050
    # exclusive lease to ensure than this block is never run concurrently.
1051
    lease_key = "user:unique_internal:#{username}"
1052 1053 1054 1055 1056 1057 1058 1059
    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

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

    uniquify = Uniquify.new

1068
    username = uniquify.string(username) { |s| User.find_by_username(s) }
1069

1070
    email = uniquify.string(-> (n) { Kernel.sprintf(email_pattern, n) }) do |s|
1071 1072 1073
      User.find_by_email(s)
    end

1074 1075 1076 1077
    scope.create(
      username: username,
      email: email,
      &creation_block
1078 1079 1080 1081
    )
  ensure
    Gitlab::ExclusiveLease.cancel(lease_key, uuid)
  end
gitlabhq committed
1082
end