user.rb 29.2 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 :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
R
Robert Speicher 已提交
34

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

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

41
  attr_accessor :force_random_password
G
gitlabhq 已提交
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
  has_many :chat_names, dependent: :destroy
60 61

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

68
  # Projects
69 70
  has_many :groups_projects,          through: :groups, source: :projects
  has_many :personal_projects,        through: :namespace, source: :projects
71
  has_many :project_members, -> { where(requested_at: nil) }, dependent: :destroy
72
  has_many :projects,                 through: :project_members
73
  has_many :created_projects,         foreign_key: :creator_id, class_name: 'Project'
C
Ciro Santilli 已提交
74 75
  has_many :users_star_projects, dependent: :destroy
  has_many :starred_projects, through: :users_star_projects, source: :project
76 77
  has_many :project_authorizations, dependent: :destroy
  has_many :authorized_projects, through: :project_authorizations, source: :project
78

79
  has_many :snippets,                 dependent: :destroy, foreign_key: :author_id
80 81 82
  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
83
  has_many :events,                   dependent: :destroy, foreign_key: :author_id
84
  has_many :subscriptions,            dependent: :destroy
85
  has_many :recent_events, -> { order "id DESC" }, foreign_key: :author_id,   class_name: "Event"
86 87
  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"
V
Valery Sizov 已提交
88
  has_many :oauth_applications, class_name: 'Doorkeeper::Application', as: :owner, dependent: :destroy
R
Rémy Coutable 已提交
89
  has_one  :abuse_report,             dependent: :destroy
90
  has_many :spam_logs,                dependent: :destroy
91
  has_many :builds,                   dependent: :nullify, class_name: 'Ci::Build'
92
  has_many :pipelines,                dependent: :nullify, class_name: 'Ci::Pipeline'
93
  has_many :todos,                    dependent: :destroy
94
  has_many :notification_settings,    dependent: :destroy
95
  has_many :award_emoji,              dependent: :destroy
96

97 98 99
  #
  # Validations
  #
100
  # Note: devise :validatable above adds validations for :email and :password
C
Cyril 已提交
101
  validates :name, presence: true
102 103
  validates :notification_email, presence: true
  validates :notification_email, email: true, if: ->(user) { user.notification_email != user.email }
104
  validates :public_email, presence: true, uniqueness: true, email: true, allow_blank: true
105
  validates :bio, length: { maximum: 255 }, allow_blank: true
106
  validates :projects_limit, presence: true, numericality: { greater_than_or_equal_to: 0 }
107
  validates :username,
R
Robert Speicher 已提交
108
    namespace: true,
109
    presence: true,
R
Robert Speicher 已提交
110
    uniqueness: { case_sensitive: false }
111

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

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

125
  after_update :update_emails_with_primary_email, if: ->(user) { user.email_changed? }
126
  before_save :ensure_authentication_token, :ensure_incoming_email_token
Z
Zeger-Jan van de Weg 已提交
127
  before_save :ensure_external_user_rights
D
Dmitriy Zaporozhets 已提交
128
  after_save :ensure_namespace_correct
129
  after_initialize :set_projects_limit
130
  before_create :check_confirmation_email
D
Dmitriy Zaporozhets 已提交
131 132 133
  after_create :post_create_hook
  after_destroy :post_destroy_hook

134
  # User's Layout preference
135
  enum layout: [:fixed, :fluid]
136

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

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

N
Nihad Abbasov 已提交
145
  alias_attribute :private_token, :authentication_token
146

147
  delegate :path, to: :namespace, allow_nil: true, prefix: true
148

149 150 151
  state_machine :state, initial: :active do
    event :block do
      transition active: :blocked
152
      transition ldap_blocked: :blocked
153 154
    end

155 156 157 158
    event :ldap_block do
      transition active: :ldap_blocked
    end

159 160
    event :activate do
      transition blocked: :active
161
      transition ldap_blocked: :active
162
    end
163 164 165 166 167 168

    state :blocked, :ldap_blocked do
      def blocked?
        true
      end
    end
169 170
  end

171
  mount_uploader :avatar, AvatarUploader
S
Steven Thonus 已提交
172

A
Andrey Kumanyaev 已提交
173
  # Scopes
174
  scope :admins, -> { where(admin: true) }
175
  scope :blocked, -> { with_states(:blocked, :ldap_blocked) }
176
  scope :external, -> { where(external: true) }
177
  scope :active, -> { with_state(:active) }
S
skv 已提交
178
  scope :not_in_project, ->(project) { project.users.present? ? where("id not in (:ids)", ids: project.users.map(&:id) ) : all }
B
Ben Bodenmiller 已提交
179
  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 已提交
180
  scope :todo_authors, ->(user_id, state) { where(id: Todo.where(user_id: user_id, state: state).select(:author_id)) }
181 182 183 184 185 186 187 188 189 190

  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
A
Andrey Kumanyaev 已提交
191

192 193 194
  #
  # Class methods
  #
A
Andrey Kumanyaev 已提交
195
  class << self
196
    # Devise method overridden to allow sign in with email or username
197 198 199
    def find_for_database_authentication(warden_conditions)
      conditions = warden_conditions.dup
      if login = conditions.delete(:login)
G
Gabriel Mazetto 已提交
200
        where(conditions).find_by("lower(username) = :value OR lower(email) = :value", value: login.downcase)
201
      else
G
Gabriel Mazetto 已提交
202
        find_by(conditions)
203 204
      end
    end
205

V
Valery Sizov 已提交
206 207
    def sort(method)
      case method.to_s
208 209 210 211
      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)
V
Valery Sizov 已提交
212 213 214
      end
    end

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

      User.find_by_sql([sql, { email: email }]).first
227
    end
228

229
    def filter(filter_name)
A
Andrey Kumanyaev 已提交
230
      case filter_name
231
      when 'admins'
232
        admins
233
      when 'blocked'
234
        blocked
235
      when 'two_factor_disabled'
236
        without_two_factor
237
      when 'two_factor_enabled'
238
        with_two_factor
239
      when 'wop'
240
        without_projects
241
      when 'external'
242
        external
A
Andrey Kumanyaev 已提交
243
      else
244
        active
A
Andrey Kumanyaev 已提交
245
      end
246 247
    end

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

      where(
        table[:name].matches(pattern).
          or(table[:email].matches(pattern)).
          or(table[:username].matches(pattern))
      )
A
Andrey Kumanyaev 已提交
264
    end
265

266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283
    # 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

284
    def by_login(login)
285 286 287 288 289 290 291
      return nil unless login

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

294 295 296 297
    def find_by_username(username)
      iwhere(username: username).take
    end

R
Robert Speicher 已提交
298
    def find_by_username!(username)
299
      iwhere(username: username).take!
R
Robert Speicher 已提交
300 301
    end

T
Timothy Andrew 已提交
302 303 304 305 306
    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

307
    def by_username_or_id(name_or_id)
G
Gabriel Mazetto 已提交
308
      find_by('users.username = ? OR users.id = ?', name_or_id.to_s, name_or_id.to_i)
309
    end
310

Y
Yorick Peterse 已提交
311 312 313 314 315
    # 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

316 317
    def build_user(attrs = {})
      User.new(attrs)
318
    end
319 320 321 322

    def reference_prefix
      '@'
    end
323 324 325 326 327 328 329 330

    # 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
V
vsizov 已提交
331
  end
R
randx 已提交
332

333 334 335
  #
  # Instance methods
  #
336 337 338 339 340

  def to_param
    username
  end

T
Timothy Andrew 已提交
341
  def to_reference(_from_project = nil, _target_project = nil)
342 343 344
    "#{self.class.reference_prefix}#{username}"
  end

A
Andrey Kumanyaev 已提交
345
  def generate_password
346
    if force_random_password
347
      self.password = self.password_confirmation = Devise.friendly_token.first(Devise.password_length.min)
A
Andrey Kumanyaev 已提交
348
    end
R
randx 已提交
349
  end
350

351
  def generate_reset_token
M
Marin Jankovski 已提交
352
    @reset_token, enc = Devise.token_generator.generate(self.class, :reset_password_token)
353 354 355 356

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

M
Marin Jankovski 已提交
357
    @reset_token
358 359
  end

360
  def check_confirmation_email
361
    skip_confirmation! unless current_application_settings.send_user_confirmation_email
362 363
  end

364 365 366 367
  def recently_sent_password_reset?
    reset_password_sent_at.present? && reset_password_sent_at >= 1.minute.ago
  end

R
Robert Speicher 已提交
368
  def disable_two_factor!
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
    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?
387
    otp_required_for_login?
388 389 390
  end

  def two_factor_u2f_enabled?
391
    u2f_registrations.exists?
R
Robert Speicher 已提交
392 393
  end

394
  def namespace_uniq
395
    # Return early if username already failed the first uniqueness validation
396 397
    return if errors.key?(:username) &&
      errors[:username].include?('has already been taken')
398

399 400 401
    existing_namespace = Namespace.by_path(username)
    if existing_namespace && existing_namespace != namespace
      errors.add(:username, 'has already been taken')
402 403
    end
  end
404

405
  def avatar_type
406 407
    unless avatar.image?
      errors.add :avatar, "only images allowed"
408 409 410
    end
  end

411
  def unique_email
412 413
    if !emails.exists?(email: email) && Email.exists?(email: email)
      errors.add(:email, 'has already been taken')
414
    end
415 416
  end

417
  def owns_notification_email
418
    return if temp_oauth_email?
419

420
    errors.add(:notification_email, "is not an email you own") unless all_emails.include?(notification_email)
421 422
  end

423
  def owns_public_email
424
    return if public_email.blank?
425

426
    errors.add(:public_email, "is not an email you own") unless all_emails.include?(public_email)
427 428 429
  end

  def update_emails_with_primary_email
430
    primary_email_record = emails.find_by(email: email)
431 432
    if primary_email_record
      primary_email_record.destroy
433
      emails.create(email: email_was)
434

435
      update_secondary_emails!
436 437 438
    end
  end

439 440
  # Returns the groups a user has access to
  def authorized_groups
441
    union = Gitlab::SQL::Union.
442
      new([groups.select(:id), authorized_projects.select(:namespace_id)])
443

444
    Group.where("namespaces.id IN (#{union.to_sql})")
445 446
  end

447
  def refresh_authorized_projects
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462
    transaction do
      project_authorizations.delete_all

      # project_authorizations_union can return multiple records for the same
      # project/user with different access_level so we take row with the maximum
      # access_level
      project_authorizations.connection.execute <<-SQL
      INSERT INTO project_authorizations (user_id, project_id, access_level)
      SELECT user_id, project_id, MAX(access_level) AS access_level
      FROM (#{project_authorizations_union.to_sql}) sub
      GROUP BY user_id, project_id
      SQL

      unless authorized_projects_populated
        update_column(:authorized_projects_populated, true)
463 464 465 466
      end
    end
  end

467
  def authorized_projects(min_access_level = nil)
468 469 470 471 472 473 474 475 476 477 478
    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 })
479 480
  end

481 482 483 484 485 486 487 488 489 490
  # 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

491
  def viewable_starred_projects
492 493 494
    starred_projects.where("projects.visibility_level IN (?) OR projects.id IN (?)",
                           [Project::PUBLIC, Project::INTERNAL],
                           authorized_projects.select(:project_id))
495 496
  end

497
  def owned_projects
498
    @owned_projects ||=
499 500
      Project.where('namespace_id IN (?) OR namespace_id = ?',
                    owned_groups.select(:id), namespace.id).joins(:namespace)
501 502
  end

503 504 505 506
  # 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 已提交
507
    authorized_projects(Gitlab::Access::REPORTER).non_archived.with_issues_enabled
508 509
  end

D
Dmitriy Zaporozhets 已提交
510 511 512 513 514 515 516 517
  def is_admin?
    admin
  end

  def require_ssh_key?
    keys.count == 0
  end

518 519 520 521
  def require_password?
    password_automatically_set? && !ldap_user?
  end

522
  def can_change_username?
523
    gitlab_config.username_changing_enabled
524 525
  end

D
Dmitriy Zaporozhets 已提交
526
  def can_create_project?
527
    projects_limit_left > 0
D
Dmitriy Zaporozhets 已提交
528 529 530
  end

  def can_create_group?
531
    can?(:create_group, nil)
D
Dmitriy Zaporozhets 已提交
532 533
  end

534 535 536 537
  def can_select_namespace?
    several_namespaces? || admin
  end

538
  def can?(action, subject)
H
http://jneen.net/ 已提交
539
    Ability.allowed?(self, action, subject)
D
Dmitriy Zaporozhets 已提交
540 541 542 543 544 545 546
  end

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

  def cared_merge_requests
547
    MergeRequest.cared(self)
D
Dmitriy Zaporozhets 已提交
548 549
  end

550
  def projects_limit_left
551
    projects_limit - personal_projects.count
552 553
  end

D
Dmitriy Zaporozhets 已提交
554 555
  def projects_limit_percent
    return 100 if projects_limit.zero?
556
    (personal_projects.count.to_f / projects_limit) * 100
D
Dmitriy Zaporozhets 已提交
557 558
  end

559
  def recent_push(project_ids = nil)
D
Dmitriy Zaporozhets 已提交
560 561
    # Get push events not earlier than 2 hours ago
    events = recent_events.code_push.where("created_at > ?", Time.now - 2.hours)
562
    events = events.where(project_id: project_ids) if project_ids
D
Dmitriy Zaporozhets 已提交
563

564 565 566 567 568
    # 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 已提交
569
      if project.repository.branch_exists?(event.branch_name)
570 571 572 573 574 575
        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
D
Dmitriy Zaporozhets 已提交
576 577 578 579 580 581 582
  end

  def projects_sorted_by_activity
    authorized_projects.sorted_by_activity
  end

  def several_namespaces?
583
    owned_groups.any? || masters_groups.any?
D
Dmitriy Zaporozhets 已提交
584 585 586 587 588
  end

  def namespace_id
    namespace.try :id
  end
589

590 591 592
  def name_with_username
    "#{name} (#{username})"
  end
D
Dmitriy Zaporozhets 已提交
593

594
  def already_forked?(project)
595 596 597
    !!fork_of(project)
  end

598
  def fork_of(project)
599 600 601 602 603 604 605 606
    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
607 608

  def ldap_user?
609 610 611 612 613
    identities.exists?(["provider LIKE ? AND extern_uid IS NOT NULL", "ldap%"])
  end

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

616
  def project_deploy_keys
617
    DeployKey.unscoped.in_projects(authorized_projects.pluck(:id)).distinct(:id)
618 619
  end

620
  def accessible_deploy_keys
621 622 623 624 625
    @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
626
  end
627 628

  def created_by
S
skv 已提交
629
    User.find_by(id: created_by_id) if created_by_id
630
  end
631 632

  def sanitize_attrs
633 634 635
    %w[name username skype linkedin twitter].each do |attr|
      value = public_send(attr)
      public_send("#{attr}=", Sanitize.clean(value)) if value.present?
636 637
    end
  end
638

639
  def set_notification_email
640 641
    if notification_email.blank? || !all_emails.include?(notification_email)
      self.notification_email = email
642 643 644
    end
  end

645
  def set_public_email
646
    if public_email.blank? || !all_emails.include?(public_email)
647
      self.public_email = ''
648 649 650
    end
  end

651
  def update_secondary_emails!
652 653 654
    set_notification_email
    set_public_email
    save if notification_email_changed? || public_email_changed?
655 656
  end

657
  def set_projects_limit
658 659 660
    # `User.select(:id)` raises
    # `ActiveModel::MissingAttributeError: missing attribute: projects_limit`
    # without this safeguard!
661
    return unless has_attribute?(:projects_limit)
662

663
    connection_default_value_defined = new_record? && !projects_limit_changed?
664
    return unless projects_limit.nil? || connection_default_value_defined
665 666 667 668

    self.projects_limit = current_application_settings.default_projects_limit
  end

669
  def requires_ldap_check?
670 671 672
    if !Gitlab.config.ldap.enabled
      false
    elsif ldap_user?
673 674 675 676 677 678
      !last_credential_check_at || (last_credential_check_at + 1.hour) < Time.now
    else
      false
    end
  end

J
Jacob Vosmaer 已提交
679 680 681 682 683 684 685
  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

686 687 688 689 690
  def solo_owned_groups
    @solo_owned_groups ||= owned_groups.select do |group|
      group.owners == [self]
    end
  end
691 692

  def with_defaults
693
    User.defaults.each do |k, v|
694
      public_send("#{k}=", v)
695
    end
696 697

    self
698
  end
699

700 701 702 703
  def can_leave_project?(project)
    project.namespace != namespace &&
      project.project_member(self)
  end
704

J
Jerome Dalbert 已提交
705
  def full_website_url
706
    return "http://#{website_url}" if website_url !~ /\Ahttps?:\/\//
J
Jerome Dalbert 已提交
707 708 709 710 711

    website_url
  end

  def short_website_url
712
    website_url.sub(/\Ahttps?:\/\//, '')
J
Jerome Dalbert 已提交
713
  end
G
GitLab 已提交
714

715
  def all_ssh_keys
716
    keys.map(&:publishable_key)
717
  end
718 719

  def temp_oauth_email?
720
    email.start_with?('temp-email-for-oauth')
721 722
  end

723
  def avatar_url(size = nil, scale = 2)
724
    if self[:avatar].present?
725
      [gitlab_config.url, avatar.url].join
726
    else
727
      GravatarService.new.execute(email, size, scale)
728 729
    end
  end
D
Dmitriy Zaporozhets 已提交
730

731
  def all_emails
732
    all_emails = []
733 734
    all_emails << email unless temp_oauth_email?
    all_emails.concat(emails.map(&:email))
735
    all_emails
736 737
  end

K
Kirill Zaitsev 已提交
738 739 740 741 742 743 744 745
  def hook_attrs
    {
      name: name,
      username: username,
      avatar_url: avatar_url
    }
  end

D
Dmitriy Zaporozhets 已提交
746 747
  def ensure_namespace_correct
    # Ensure user has namespace
748
    create_namespace!(path: username, name: username) unless namespace
D
Dmitriy Zaporozhets 已提交
749

750 751
    if username_changed?
      namespace.update_attributes(path: username, name: username)
D
Dmitriy Zaporozhets 已提交
752 753 754 755
    end
  end

  def post_create_hook
756 757
    log_info("User \"#{name}\" (#{email}) was created")
    notification_service.new_user(self, @reset_token) if created_by_id
D
Dmitriy Zaporozhets 已提交
758 759 760 761
    system_hook_service.execute_hooks_for(self, :create)
  end

  def post_destroy_hook
762
    log_info("User \"#{name}\" (#{email})  was removed")
D
Dmitriy Zaporozhets 已提交
763 764 765
    system_hook_service.execute_hooks_for(self, :destroy)
  end

D
Dmitriy Zaporozhets 已提交
766
  def notification_service
D
Dmitriy Zaporozhets 已提交
767 768 769
    NotificationService.new
  end

770
  def log_info(message)
D
Dmitriy Zaporozhets 已提交
771 772 773 774 775 776
    Gitlab::AppLogger.info message
  end

  def system_hook_service
    SystemHooksService.new
  end
C
Ciro Santilli 已提交
777 778

  def starred?(project)
V
Valery Sizov 已提交
779
    starred_projects.exists?(project.id)
C
Ciro Santilli 已提交
780 781 782
  end

  def toggle_star(project)
783 784 785 786 787 788 789 790 791
    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
C
Ciro Santilli 已提交
792 793
    end
  end
794 795

  def manageable_namespaces
G
Guilherme Garnier 已提交
796
    @manageable_namespaces ||= [namespace] + owned_groups + masters_groups
797
  end
D
Dmitriy Zaporozhets 已提交
798

799 800 801 802 803 804
  def namespaces
    namespace_ids = groups.pluck(:id)
    namespace_ids.push(namespace.id)
    Namespace.where(id: namespace_ids)
  end

D
Dmitriy Zaporozhets 已提交
805
  def oauth_authorized_tokens
806
    Doorkeeper::AccessToken.where(resource_owner_id: id, revoked_at: nil)
D
Dmitriy Zaporozhets 已提交
807
  end
808

809 810 811 812 813 814 815 816 817
  # 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
818
  # ms on a database with a similar size to GitLab.com's database. On the other
819 820 821 822
  # 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).
823
      where("created_at > ?", Time.now - 1.year).
824
      uniq.
825 826 827
      reorder(nil)

    Project.where(id: events)
828
  end
829

830 831 832
  def can_be_removed?
    !solo_owned_groups.present?
  end
833 834

  def ci_authorized_runners
K
Kamil Trzcinski 已提交
835
    @ci_authorized_runners ||= begin
K
Kamil Trzcinski 已提交
836 837
      runner_ids = Ci::RunnerProject.
        where("ci_runner_projects.gl_project_id IN (#{ci_projects_union.to_sql})").
838
        select(:runner_id)
K
Kamil Trzcinski 已提交
839 840
      Ci::Runner.specific.where(id: runner_ids)
    end
841
  end
842

843 844 845 846
  def notification_settings_for(source)
    notification_settings.find_or_initialize_by(source: source)
  end

847 848 849
  # Lazy load global notification setting
  # Initializes User setting with Participating level if setting not persisted
  def global_notification_setting
850 851 852 853 854 855
    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
856 857
  end

J
Josh Frye 已提交
858 859
  def assigned_open_merge_request_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_merge_request_count'], force: force) do
860 861 862 863
      assigned_merge_requests.opened.count
    end
  end

J
Josh Frye 已提交
864 865
  def assigned_open_issues_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_issues_count'], force: force) do
866 867
      assigned_issues.opened.count
    end
868 869
  end

J
Josh Frye 已提交
870 871 872 873 874
  def update_cache_counts
    assigned_open_merge_request_count(force: true)
    assigned_open_issues_count(force: true)
  end

P
Paco Guzman 已提交
875 876
  def todos_done_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_done_count'], force: force) do
877
      TodosFinder.new(self, state: :done).execute.count
P
Paco Guzman 已提交
878 879 880 881 882
    end
  end

  def todos_pending_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_pending_count'], force: force) do
883
      TodosFinder.new(self, state: :pending).execute.count
P
Paco Guzman 已提交
884 885 886 887 888 889 890 891
    end
  end

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

892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907
  # 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

908 909
  private

910 911 912
  # Returns a union query of projects that the user is authorized to access
  def project_authorizations_union
    relations = [
913
      personal_projects.select("#{id} AS user_id, projects.id AS project_id, #{Gitlab::Access::MASTER} AS access_level"),
914 915 916 917
      groups_projects.select_for_project_authorization,
      projects.select_for_project_authorization,
      groups.joins(:shared_projects).select_for_project_authorization
    ]
918 919

    Gitlab::SQL::Union.new(relations)
920
  end
921 922 923 924 925 926 927 928 929

  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 已提交
930 931 932 933 934

  # 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 已提交
935 936

  def ensure_external_user_rights
937
    return unless external?
Z
Zeger-Jan van de Weg 已提交
938 939 940 941

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

943 944 945 946 947 948
  def signup_domain_valid?
    valid = true
    error = nil

    if current_application_settings.domain_blacklist_enabled?
      blocked_domains = current_application_settings.domain_blacklist
949
      if domain_matches?(blocked_domains, email)
950 951 952 953 954
        error = 'is not from an allowed domain.'
        valid = false
      end
    end

955
    allowed_domains = current_application_settings.domain_whitelist
956
    unless allowed_domains.blank?
957
      if domain_matches?(allowed_domains, email)
958 959
        valid = true
      else
D
dev-chris 已提交
960
        error = "domain is not authorized for sign-up"
961 962 963 964
        valid = false
      end
    end

965
    errors.add(:email, error) unless valid
966 967 968

    valid
  end
969

970
  def domain_matches?(email_domains, email)
971 972 973 974 975 976 977
    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
978 979 980 981

  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.
982
      SecureRandom.hex.to_i(16).to_s(36)
983 984 985 986
    else
      super
    end
  end
G
gitlabhq 已提交
987
end