user.rb 28.4 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
  scope :order_recent_sign_in, -> { reorder(last_sign_in_at: :desc) }
  scope :order_oldest_sign_in, -> { reorder(last_sign_in_at: :asc) }
183 184 185 186 187 188 189 190 191 192

  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 已提交
193

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

V
Valery Sizov 已提交
208 209
    def sort(method)
      case method.to_s
210 211
      when 'recent_sign_in' then order_recent_sign_in
      when 'oldest_sign_in' then order_oldest_sign_in
212 213
      else
        order_by(method)
V
Valery Sizov 已提交
214 215 216
      end
    end

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

      User.find_by_sql([sql, { email: email }]).first
229
    end
230

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

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

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

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

286
    def by_login(login)
287 288 289 290 291 292 293
      return nil unless login

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

296 297 298 299
    def find_by_username(username)
      iwhere(username: username).take
    end

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

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

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

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

    # 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 已提交
325
  end
R
randx 已提交
326

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

  def to_param
    username
  end

T
Timothy Andrew 已提交
335
  def to_reference(_from_project = nil, _target_project = nil)
336 337 338
    "#{self.class.reference_prefix}#{username}"
  end

A
Andrey Kumanyaev 已提交
339
  def generate_password
340
    if force_random_password
341
      self.password = self.password_confirmation = Devise.friendly_token.first(Devise.password_length.min)
A
Andrey Kumanyaev 已提交
342
    end
R
randx 已提交
343
  end
344

345
  def generate_reset_token
M
Marin Jankovski 已提交
346
    @reset_token, enc = Devise.token_generator.generate(self.class, :reset_password_token)
347 348 349 350

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

M
Marin Jankovski 已提交
351
    @reset_token
352 353
  end

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

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

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

  def two_factor_u2f_enabled?
385
    u2f_registrations.exists?
R
Robert Speicher 已提交
386 387
  end

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

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

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

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

411
  def owns_notification_email
412
    return if temp_oauth_email?
413

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

417
  def owns_public_email
418
    return if public_email.blank?
419

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

  def update_emails_with_primary_email
424
    primary_email_record = emails.find_by(email: email)
425 426
    if primary_email_record
      primary_email_record.destroy
427
      emails.create(email: email_was)
428

429
      update_secondary_emails!
430 431 432
    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
  def refresh_authorized_projects
442 443 444 445 446 447 448 449 450 451
    Users::RefreshAuthorizedProjectsService.new(self).execute
  end

  def remove_project_authorizations(project_ids)
    project_authorizations.where(id: project_ids).delete_all
  end

  def set_authorized_projects_column
    unless authorized_projects_populated
      update_column(:authorized_projects_populated, true)
452 453 454
    end
  end

455
  def authorized_projects(min_access_level = nil)
456 457 458 459 460 461 462 463 464 465 466
    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 })
467 468
  end

469 470 471 472 473 474 475 476 477 478
  # 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

479
  def viewable_starred_projects
480 481 482
    starred_projects.where("projects.visibility_level IN (?) OR projects.id IN (?)",
                           [Project::PUBLIC, Project::INTERNAL],
                           authorized_projects.select(:project_id))
483 484
  end

485
  def owned_projects
486
    @owned_projects ||=
487 488
      Project.where('namespace_id IN (?) OR namespace_id = ?',
                    owned_groups.select(:id), namespace.id).joins(:namespace)
489 490
  end

491 492 493 494
  # 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 已提交
495
    authorized_projects(Gitlab::Access::REPORTER).non_archived.with_issues_enabled
496 497
  end

D
Dmitriy Zaporozhets 已提交
498 499 500 501 502
  def is_admin?
    admin
  end

  def require_ssh_key?
503
    keys.count == 0 && Gitlab::ProtocolAccess.allowed?('ssh')
D
Dmitriy Zaporozhets 已提交
504 505
  end

506 507 508 509
  def require_password?
    password_automatically_set? && !ldap_user?
  end

510
  def can_change_username?
511
    gitlab_config.username_changing_enabled
512 513
  end

D
Dmitriy Zaporozhets 已提交
514
  def can_create_project?
515
    projects_limit_left > 0
D
Dmitriy Zaporozhets 已提交
516 517 518
  end

  def can_create_group?
519
    can?(:create_group, nil)
D
Dmitriy Zaporozhets 已提交
520 521
  end

522 523 524 525
  def can_select_namespace?
    several_namespaces? || admin
  end

526
  def can?(action, subject)
H
http://jneen.net/ 已提交
527
    Ability.allowed?(self, action, subject)
D
Dmitriy Zaporozhets 已提交
528 529 530 531 532 533 534
  end

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

  def cared_merge_requests
535
    MergeRequest.cared(self)
D
Dmitriy Zaporozhets 已提交
536 537
  end

538
  def projects_limit_left
539
    projects_limit - personal_projects.count
540 541
  end

D
Dmitriy Zaporozhets 已提交
542 543
  def projects_limit_percent
    return 100 if projects_limit.zero?
544
    (personal_projects.count.to_f / projects_limit) * 100
D
Dmitriy Zaporozhets 已提交
545 546
  end

547
  def recent_push(project_ids = nil)
D
Dmitriy Zaporozhets 已提交
548 549
    # Get push events not earlier than 2 hours ago
    events = recent_events.code_push.where("created_at > ?", Time.now - 2.hours)
550
    events = events.where(project_id: project_ids) if project_ids
D
Dmitriy Zaporozhets 已提交
551

552 553 554 555 556
    # 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 已提交
557
      if project.repository.branch_exists?(event.branch_name)
558 559 560 561 562 563
        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 已提交
564 565 566 567 568 569 570
  end

  def projects_sorted_by_activity
    authorized_projects.sorted_by_activity
  end

  def several_namespaces?
571
    owned_groups.any? || masters_groups.any?
D
Dmitriy Zaporozhets 已提交
572 573 574 575 576
  end

  def namespace_id
    namespace.try :id
  end
577

578 579 580
  def name_with_username
    "#{name} (#{username})"
  end
D
Dmitriy Zaporozhets 已提交
581

582
  def already_forked?(project)
583 584 585
    !!fork_of(project)
  end

586
  def fork_of(project)
587 588 589 590 591 592 593 594
    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
595 596

  def ldap_user?
597 598 599 600 601
    identities.exists?(["provider LIKE ? AND extern_uid IS NOT NULL", "ldap%"])
  end

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

604
  def project_deploy_keys
605
    DeployKey.unscoped.in_projects(authorized_projects.pluck(:id)).distinct(:id)
606 607
  end

608
  def accessible_deploy_keys
609 610 611 612 613
    @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
614
  end
615 616

  def created_by
S
skv 已提交
617
    User.find_by(id: created_by_id) if created_by_id
618
  end
619 620

  def sanitize_attrs
621 622 623
    %w[name username skype linkedin twitter].each do |attr|
      value = public_send(attr)
      public_send("#{attr}=", Sanitize.clean(value)) if value.present?
624 625
    end
  end
626

627
  def set_notification_email
628 629
    if notification_email.blank? || !all_emails.include?(notification_email)
      self.notification_email = email
630 631 632
    end
  end

633
  def set_public_email
634
    if public_email.blank? || !all_emails.include?(public_email)
635
      self.public_email = ''
636 637 638
    end
  end

639
  def update_secondary_emails!
640 641 642
    set_notification_email
    set_public_email
    save if notification_email_changed? || public_email_changed?
643 644
  end

645
  def set_projects_limit
646 647 648
    # `User.select(:id)` raises
    # `ActiveModel::MissingAttributeError: missing attribute: projects_limit`
    # without this safeguard!
649
    return unless has_attribute?(:projects_limit)
650

651
    connection_default_value_defined = new_record? && !projects_limit_changed?
652
    return unless projects_limit.nil? || connection_default_value_defined
653 654 655 656

    self.projects_limit = current_application_settings.default_projects_limit
  end

657
  def requires_ldap_check?
658 659 660
    if !Gitlab.config.ldap.enabled
      false
    elsif ldap_user?
661 662 663 664 665 666
      !last_credential_check_at || (last_credential_check_at + 1.hour) < Time.now
    else
      false
    end
  end

J
Jacob Vosmaer 已提交
667 668 669 670 671 672 673
  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

674 675 676 677 678
  def solo_owned_groups
    @solo_owned_groups ||= owned_groups.select do |group|
      group.owners == [self]
    end
  end
679 680

  def with_defaults
681
    User.defaults.each do |k, v|
682
      public_send("#{k}=", v)
683
    end
684 685

    self
686
  end
687

688 689 690 691
  def can_leave_project?(project)
    project.namespace != namespace &&
      project.project_member(self)
  end
692

J
Jerome Dalbert 已提交
693
  def full_website_url
694
    return "http://#{website_url}" if website_url !~ /\Ahttps?:\/\//
J
Jerome Dalbert 已提交
695 696 697 698 699

    website_url
  end

  def short_website_url
700
    website_url.sub(/\Ahttps?:\/\//, '')
J
Jerome Dalbert 已提交
701
  end
G
GitLab 已提交
702

703
  def all_ssh_keys
704
    keys.map(&:publishable_key)
705
  end
706 707

  def temp_oauth_email?
708
    email.start_with?('temp-email-for-oauth')
709 710
  end

711
  def avatar_url(size = nil, scale = 2)
712
    if self[:avatar].present?
713
      [gitlab_config.url, avatar.url].join
714
    else
715
      GravatarService.new.execute(email, size, scale)
716 717
    end
  end
D
Dmitriy Zaporozhets 已提交
718

719
  def all_emails
720
    all_emails = []
721 722
    all_emails << email unless temp_oauth_email?
    all_emails.concat(emails.map(&:email))
723
    all_emails
724 725
  end

K
Kirill Zaitsev 已提交
726 727 728 729 730 731 732 733
  def hook_attrs
    {
      name: name,
      username: username,
      avatar_url: avatar_url
    }
  end

D
Dmitriy Zaporozhets 已提交
734 735
  def ensure_namespace_correct
    # Ensure user has namespace
736
    create_namespace!(path: username, name: username) unless namespace
D
Dmitriy Zaporozhets 已提交
737

738 739
    if username_changed?
      namespace.update_attributes(path: username, name: username)
D
Dmitriy Zaporozhets 已提交
740 741 742 743
    end
  end

  def post_create_hook
744 745
    log_info("User \"#{name}\" (#{email}) was created")
    notification_service.new_user(self, @reset_token) if created_by_id
D
Dmitriy Zaporozhets 已提交
746 747 748 749
    system_hook_service.execute_hooks_for(self, :create)
  end

  def post_destroy_hook
750
    log_info("User \"#{name}\" (#{email})  was removed")
D
Dmitriy Zaporozhets 已提交
751 752 753
    system_hook_service.execute_hooks_for(self, :destroy)
  end

D
Dmitriy Zaporozhets 已提交
754
  def notification_service
D
Dmitriy Zaporozhets 已提交
755 756 757
    NotificationService.new
  end

758
  def log_info(message)
D
Dmitriy Zaporozhets 已提交
759 760 761 762 763 764
    Gitlab::AppLogger.info message
  end

  def system_hook_service
    SystemHooksService.new
  end
C
Ciro Santilli 已提交
765 766

  def starred?(project)
V
Valery Sizov 已提交
767
    starred_projects.exists?(project.id)
C
Ciro Santilli 已提交
768 769 770
  end

  def toggle_star(project)
771 772 773 774 775 776 777 778 779
    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 已提交
780 781
    end
  end
782 783

  def manageable_namespaces
G
Guilherme Garnier 已提交
784
    @manageable_namespaces ||= [namespace] + owned_groups + masters_groups
785
  end
D
Dmitriy Zaporozhets 已提交
786

787 788 789 790 791 792
  def namespaces
    namespace_ids = groups.pluck(:id)
    namespace_ids.push(namespace.id)
    Namespace.where(id: namespace_ids)
  end

D
Dmitriy Zaporozhets 已提交
793
  def oauth_authorized_tokens
794
    Doorkeeper::AccessToken.where(resource_owner_id: id, revoked_at: nil)
D
Dmitriy Zaporozhets 已提交
795
  end
796

797 798 799 800 801 802 803 804 805
  # 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
806
  # ms on a database with a similar size to GitLab.com's database. On the other
807 808 809 810
  # 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).
811
      where("created_at > ?", Time.now - 1.year).
812
      uniq.
813 814 815
      reorder(nil)

    Project.where(id: events)
816
  end
817

818 819 820
  def can_be_removed?
    !solo_owned_groups.present?
  end
821 822

  def ci_authorized_runners
K
Kamil Trzcinski 已提交
823
    @ci_authorized_runners ||= begin
K
Kamil Trzcinski 已提交
824 825
      runner_ids = Ci::RunnerProject.
        where("ci_runner_projects.gl_project_id IN (#{ci_projects_union.to_sql})").
826
        select(:runner_id)
K
Kamil Trzcinski 已提交
827 828
      Ci::Runner.specific.where(id: runner_ids)
    end
829
  end
830

831 832 833 834
  def notification_settings_for(source)
    notification_settings.find_or_initialize_by(source: source)
  end

835 836 837
  # Lazy load global notification setting
  # Initializes User setting with Participating level if setting not persisted
  def global_notification_setting
838 839 840 841 842 843
    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
844 845
  end

J
Josh Frye 已提交
846 847
  def assigned_open_merge_request_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_merge_request_count'], force: force) do
848 849 850 851
      assigned_merge_requests.opened.count
    end
  end

J
Josh Frye 已提交
852 853
  def assigned_open_issues_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_issues_count'], force: force) do
854 855
      assigned_issues.opened.count
    end
856 857
  end

J
Josh Frye 已提交
858 859 860 861 862
  def update_cache_counts
    assigned_open_merge_request_count(force: true)
    assigned_open_issues_count(force: true)
  end

P
Paco Guzman 已提交
863 864
  def todos_done_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_done_count'], force: force) do
865
      TodosFinder.new(self, state: :done).execute.count
P
Paco Guzman 已提交
866 867 868 869 870
    end
  end

  def todos_pending_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_pending_count'], force: force) do
871
      TodosFinder.new(self, state: :pending).execute.count
P
Paco Guzman 已提交
872 873 874 875 876 877 878 879
    end
  end

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

880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895
  # 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

896 897
  private

898 899 900 901 902 903 904 905
  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 已提交
906 907 908 909 910

  # 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 已提交
911 912

  def ensure_external_user_rights
913
    return unless external?
Z
Zeger-Jan van de Weg 已提交
914 915 916 917

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

919 920 921 922 923 924
  def signup_domain_valid?
    valid = true
    error = nil

    if current_application_settings.domain_blacklist_enabled?
      blocked_domains = current_application_settings.domain_blacklist
925
      if domain_matches?(blocked_domains, email)
926 927 928 929 930
        error = 'is not from an allowed domain.'
        valid = false
      end
    end

931
    allowed_domains = current_application_settings.domain_whitelist
932
    unless allowed_domains.blank?
933
      if domain_matches?(allowed_domains, email)
934 935
        valid = true
      else
D
dev-chris 已提交
936
        error = "domain is not authorized for sign-up"
937 938 939 940
        valid = false
      end
    end

941
    errors.add(:email, error) unless valid
942 943 944

    valid
  end
945

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

  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.
958
      SecureRandom.hex.to_i(16).to_s(36)
959 960 961 962
    else
      super
    end
  end
G
gitlabhq 已提交
963
end