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

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

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

13 14
  DEFAULT_NOTIFICATION_LEVEL = :participating

15
  add_authentication_token_field :authentication_token
16
  add_authentication_token_field :incoming_email_token
17

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

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

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

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

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

42
  attr_accessor :force_random_password
G
gitlabhq 已提交
43

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

47 48 49 50
  #
  # Relations
  #

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

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

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

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

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

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

101 102 103
  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"

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

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

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

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

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

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

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

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

N
Nihad Abbasov 已提交
157
  alias_attribute :private_token, :authentication_token
158

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

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

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

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

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

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

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

A
Andrey Kumanyaev 已提交
195
  # Scopes
196
  scope :admins, -> { where(admin: true) }
197
  scope :blocked, -> { with_states(:blocked, :ldap_blocked) }
198
  scope :external, -> { where(external: true) }
199
  scope :active, -> { with_state(:active) }
S
skv 已提交
200
  scope :not_in_project, ->(project) { project.users.present? ? where("id not in (:ids)", ids: project.users.map(&:id) ) : all }
B
Ben Bodenmiller 已提交
201
  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 已提交
202
  scope :todo_authors, ->(user_id, state) { where(id: Todo.where(user_id: user_id, state: state).select(:author_id)) }
203 204
  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')) }
205 206

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

  def self.without_two_factor
212 213
    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)
214
  end
A
Andrey Kumanyaev 已提交
215

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

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

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

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

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

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

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

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

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

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

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

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

T
Timothy Andrew 已提交
326
    def find_by_personal_access_token(token_string)
327 328
      return unless token_string

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

Y
Yorick Peterse 已提交
332 333 334 335 336
    # 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

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

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

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

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

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

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

  def to_param
    username
  end

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

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

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

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

M
Marin Jankovski 已提交
397
    @reset_token
398 399
  end

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

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

  def two_factor_u2f_enabled?
427
    u2f_registrations.exists?
R
Robert Speicher 已提交
428 429
  end

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

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

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

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

453
  def owns_notification_email
454
    return if temp_oauth_email?
455

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

459
  def owns_public_email
460
    return if public_email.blank?
461

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

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

471
      update_secondary_emails!
472 473 474
    end
  end

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

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

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

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

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

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

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

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

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

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

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

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

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

D
Dmitriy Zaporozhets 已提交
557 558 559 560 561
  def is_admin?
    admin
  end

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

565 566 567 568
  def require_password?
    password_automatically_set? && !ldap_user?
  end

569
  def can_change_username?
570
    gitlab_config.username_changing_enabled
571 572
  end

D
Dmitriy Zaporozhets 已提交
573
  def can_create_project?
574
    projects_limit_left > 0
D
Dmitriy Zaporozhets 已提交
575 576 577
  end

  def can_create_group?
578
    can?(:create_group)
D
Dmitriy Zaporozhets 已提交
579 580
  end

581 582 583 584
  def can_select_namespace?
    several_namespaces? || admin
  end

585
  def can?(action, subject = :global)
H
http://jneen.net/ 已提交
586
    Ability.allowed?(self, action, subject)
D
Dmitriy Zaporozhets 已提交
587 588 589 590 591 592 593
  end

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

  def cared_merge_requests
594
    MergeRequest.cared(self)
D
Dmitriy Zaporozhets 已提交
595 596
  end

597
  def projects_limit_left
598
    projects_limit - personal_projects.count
599 600
  end

D
Dmitriy Zaporozhets 已提交
601 602
  def projects_limit_percent
    return 100 if projects_limit.zero?
603
    (personal_projects.count.to_f / projects_limit) * 100
D
Dmitriy Zaporozhets 已提交
604 605
  end

606
  def recent_push(project_ids = nil)
D
Dmitriy Zaporozhets 已提交
607 608
    # Get push events not earlier than 2 hours ago
    events = recent_events.code_push.where("created_at > ?", Time.now - 2.hours)
609
    events = events.where(project_id: project_ids) if project_ids
D
Dmitriy Zaporozhets 已提交
610

611 612 613 614 615
    # 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 已提交
616
      if project.repository.branch_exists?(event.branch_name)
617 618 619
        merge_requests = MergeRequest.where("created_at >= ?", event.created_at).
          where(source_project_id: project.id,
                source_branch: event.branch_name)
620 621 622
        merge_requests.empty?
      end
    end
D
Dmitriy Zaporozhets 已提交
623 624 625 626 627 628 629
  end

  def projects_sorted_by_activity
    authorized_projects.sorted_by_activity
  end

  def several_namespaces?
630
    owned_groups.any? || masters_groups.any?
D
Dmitriy Zaporozhets 已提交
631 632 633 634 635
  end

  def namespace_id
    namespace.try :id
  end
636

637 638 639
  def name_with_username
    "#{name} (#{username})"
  end
D
Dmitriy Zaporozhets 已提交
640

641
  def already_forked?(project)
642 643 644
    !!fork_of(project)
  end

645
  def fork_of(project)
646 647 648 649
    links = ForkedProjectLink.where(
      forked_from_project_id: project,
      forked_to_project_id: personal_projects.unscope(:order)
    )
650 651 652 653 654 655
    if links.any?
      links.first.forked_to_project
    else
      nil
    end
  end
656 657

  def ldap_user?
658 659 660 661 662
    identities.exists?(["provider LIKE ? AND extern_uid IS NOT NULL", "ldap%"])
  end

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

665
  def project_deploy_keys
666
    DeployKey.unscoped.in_projects(authorized_projects.pluck(:id)).distinct(:id)
667 668
  end

669
  def accessible_deploy_keys
670 671 672 673 674
    @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
675
  end
676 677

  def created_by
S
skv 已提交
678
    User.find_by(id: created_by_id) if created_by_id
679
  end
680 681

  def sanitize_attrs
682 683 684
    %w[name username skype linkedin twitter].each do |attr|
      value = public_send(attr)
      public_send("#{attr}=", Sanitize.clean(value)) if value.present?
685 686
    end
  end
687

688
  def set_notification_email
689 690
    if notification_email.blank? || !all_emails.include?(notification_email)
      self.notification_email = email
691 692 693
    end
  end

694
  def set_public_email
695
    if public_email.blank? || !all_emails.include?(public_email)
696
      self.public_email = ''
697 698 699
    end
  end

700
  def update_secondary_emails!
701 702 703
    set_notification_email
    set_public_email
    save if notification_email_changed? || public_email_changed?
704 705
  end

706
  def set_projects_limit
707 708 709
    # `User.select(:id)` raises
    # `ActiveModel::MissingAttributeError: missing attribute: projects_limit`
    # without this safeguard!
710
    return unless has_attribute?(:projects_limit)
711

712
    connection_default_value_defined = new_record? && !projects_limit_changed?
713
    return unless projects_limit.nil? || connection_default_value_defined
714 715 716 717

    self.projects_limit = current_application_settings.default_projects_limit
  end

718
  def requires_ldap_check?
719 720 721
    if !Gitlab.config.ldap.enabled
      false
    elsif ldap_user?
722 723 724 725 726 727
      !last_credential_check_at || (last_credential_check_at + 1.hour) < Time.now
    else
      false
    end
  end

J
Jacob Vosmaer 已提交
728 729 730 731 732 733 734
  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

735 736 737 738 739
  def solo_owned_groups
    @solo_owned_groups ||= owned_groups.select do |group|
      group.owners == [self]
    end
  end
740 741

  def with_defaults
742
    User.defaults.each do |k, v|
743
      public_send("#{k}=", v)
744
    end
745 746

    self
747
  end
748

749 750 751 752
  def can_leave_project?(project)
    project.namespace != namespace &&
      project.project_member(self)
  end
753

J
Jerome Dalbert 已提交
754
  def full_website_url
755
    return "http://#{website_url}" if website_url !~ /\Ahttps?:\/\//
J
Jerome Dalbert 已提交
756 757 758 759 760

    website_url
  end

  def short_website_url
761
    website_url.sub(/\Ahttps?:\/\//, '')
J
Jerome Dalbert 已提交
762
  end
G
GitLab 已提交
763

764
  def all_ssh_keys
765
    keys.map(&:publishable_key)
766
  end
767 768

  def temp_oauth_email?
769
    email.start_with?('temp-email-for-oauth')
770 771
  end

772
  def avatar_url(size = nil, scale = 2)
773
    if self[:avatar].present?
774
      [gitlab_config.url, avatar.url].join
775
    else
776
      GravatarService.new.execute(email, size, scale)
777 778
    end
  end
D
Dmitriy Zaporozhets 已提交
779

780
  def all_emails
781
    all_emails = []
782 783
    all_emails << email unless temp_oauth_email?
    all_emails.concat(emails.map(&:email))
784
    all_emails
785 786
  end

K
Kirill Zaitsev 已提交
787 788 789 790 791 792 793 794
  def hook_attrs
    {
      name: name,
      username: username,
      avatar_url: avatar_url
    }
  end

D
Dmitriy Zaporozhets 已提交
795 796
  def ensure_namespace_correct
    # Ensure user has namespace
797
    create_namespace!(path: username, name: username) unless namespace
D
Dmitriy Zaporozhets 已提交
798

799 800
    if username_changed?
      namespace.update_attributes(path: username, name: username)
D
Dmitriy Zaporozhets 已提交
801 802 803 804
    end
  end

  def post_destroy_hook
805
    log_info("User \"#{name}\" (#{email})  was removed")
D
Dmitriy Zaporozhets 已提交
806 807 808
    system_hook_service.execute_hooks_for(self, :destroy)
  end

D
Dmitriy Zaporozhets 已提交
809
  def notification_service
D
Dmitriy Zaporozhets 已提交
810 811 812
    NotificationService.new
  end

813
  def log_info(message)
D
Dmitriy Zaporozhets 已提交
814 815 816 817 818 819
    Gitlab::AppLogger.info message
  end

  def system_hook_service
    SystemHooksService.new
  end
C
Ciro Santilli 已提交
820 821

  def starred?(project)
V
Valery Sizov 已提交
822
    starred_projects.exists?(project.id)
C
Ciro Santilli 已提交
823 824 825
  end

  def toggle_star(project)
826
    UsersStarProject.transaction do
827 828
      user_star_project = users_star_projects.
          where(project: project, user: self).lock(true).first
829 830 831 832 833 834

      if user_star_project
        user_star_project.destroy
      else
        UsersStarProject.create!(project: project, user: self)
      end
C
Ciro Santilli 已提交
835 836
    end
  end
837 838

  def manageable_namespaces
G
Guilherme Garnier 已提交
839
    @manageable_namespaces ||= [namespace] + owned_groups + masters_groups
840
  end
D
Dmitriy Zaporozhets 已提交
841

842 843 844 845 846 847
  def namespaces
    namespace_ids = groups.pluck(:id)
    namespace_ids.push(namespace.id)
    Namespace.where(id: namespace_ids)
  end

D
Dmitriy Zaporozhets 已提交
848
  def oauth_authorized_tokens
849
    Doorkeeper::AccessToken.where(resource_owner_id: id, revoked_at: nil)
D
Dmitriy Zaporozhets 已提交
850
  end
851

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

    Project.where(id: events)
871
  end
872

873 874 875
  def can_be_removed?
    !solo_owned_groups.present?
  end
876 877

  def ci_authorized_runners
K
Kamil Trzcinski 已提交
878
    @ci_authorized_runners ||= begin
879
      runner_ids = Ci::RunnerProject.
K
Kamil Trzciński 已提交
880
        where("ci_runner_projects.project_id IN (#{ci_projects_union.to_sql})").
881
        select(:runner_id)
K
Kamil Trzcinski 已提交
882 883
      Ci::Runner.specific.where(id: runner_ids)
    end
884
  end
885

886 887 888 889
  def notification_settings_for(source)
    notification_settings.find_or_initialize_by(source: source)
  end

890 891 892
  # Lazy load global notification setting
  # Initializes User setting with Participating level if setting not persisted
  def global_notification_setting
893 894 895 896 897 898
    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
899 900
  end

J
Josh Frye 已提交
901 902
  def assigned_open_merge_request_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_merge_request_count'], force: force) do
903 904 905 906
      assigned_merge_requests.opened.count
    end
  end

J
Josh Frye 已提交
907 908
  def assigned_open_issues_count(force: false)
    Rails.cache.fetch(['users', id, 'assigned_open_issues_count'], force: force) do
909 910
      assigned_issues.opened.count
    end
911 912
  end

J
Josh Frye 已提交
913 914 915 916 917
  def update_cache_counts
    assigned_open_merge_request_count(force: true)
    assigned_open_issues_count(force: true)
  end

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

  def todos_pending_count(force: false)
    Rails.cache.fetch(['users', id, 'todos_pending_count'], force: force) do
926
      TodosFinder.new(self, state: :pending).execute.count
P
Paco Guzman 已提交
927 928 929 930 931 932 933 934
    end
  end

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

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
  # 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

951 952 953 954 955 956 957 958 959
  def access_level
    if admin?
      :admin
    else
      :regular
    end
  end

  def access_level=(new_level)
D
Douwe Maan 已提交
960 961
    new_level = new_level.to_s
    return unless %w(admin regular).include?(new_level)
962

D
Douwe Maan 已提交
963 964
    self.admin = (new_level == 'admin')
  end
965

966 967 968 969 970 971 972 973
  protected

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

974
  def update_two_factor_requirement
975
    periods = expanded_groups_requiring_two_factor_authentication.pluck(:two_factor_grace_period)
976 977 978 979 980 981 982

    self.require_two_factor_authentication = periods.any?
    self.two_factor_grace_period = periods.min || User.column_defaults['two_factor_grace_period']

    save
  end

983 984
  private

985 986 987 988 989 990 991 992
  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 已提交
993 994 995 996 997

  # 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 已提交
998 999

  def ensure_external_user_rights
1000
    return unless external?
Z
Zeger-Jan van de Weg 已提交
1001 1002 1003 1004

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

1006 1007 1008 1009 1010 1011
  def signup_domain_valid?
    valid = true
    error = nil

    if current_application_settings.domain_blacklist_enabled?
      blocked_domains = current_application_settings.domain_blacklist
1012
      if domain_matches?(blocked_domains, email)
1013 1014 1015 1016 1017
        error = 'is not from an allowed domain.'
        valid = false
      end
    end

1018
    allowed_domains = current_application_settings.domain_whitelist
1019
    unless allowed_domains.blank?
1020
      if domain_matches?(allowed_domains, email)
1021 1022
        valid = true
      else
D
dev-chris 已提交
1023
        error = "domain is not authorized for sign-up"
1024 1025 1026 1027
        valid = false
      end
    end

1028
    errors.add(:email, error) unless valid
1029 1030 1031

    valid
  end
1032

1033
  def domain_matches?(email_domains, email)
1034 1035 1036 1037 1038 1039 1040
    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
1041 1042 1043 1044

  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.
1045
      SecureRandom.hex.to_i(16).to_s(36)
1046 1047 1048 1049
    else
      super
    end
  end
1050

1051 1052 1053 1054 1055 1056
  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
1057
    # exclusive lease to ensure than this block is never run concurrently.
1058
    lease_key = "user:unique_internal:#{username}"
1059 1060 1061 1062 1063 1064 1065 1066
    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

1067
    # Recheck if the user is already present. One might have been
1068 1069
    # added between the time we last checked (first line of this method)
    # and the time we acquired the lock.
1070 1071
    existing_user = uncached { scope.first }
    return existing_user if existing_user.present?
1072 1073 1074

    uniquify = Uniquify.new

1075
    username = uniquify.string(username) { |s| User.find_by_username(s) }
1076

1077
    email = uniquify.string(-> (n) { Kernel.sprintf(email_pattern, n) }) do |s|
1078 1079 1080
      User.find_by_email(s)
    end

1081 1082 1083 1084
    scope.create(
      username: username,
      email: email,
      &creation_block
1085 1086 1087 1088
    )
  ensure
    Gitlab::ExclusiveLease.cancel(lease_key, uuid)
  end
G
gitlabhq 已提交
1089
end