Class: User

Constant Summary collapse

DEFAULT_NOTIFICATION_LEVEL =
:participating
INSTANCE_ACCESS_REQUEST_APPROVERS_TO_BE_NOTIFIED_LIMIT =
10
BLOCKED_PENDING_APPROVAL_STATE =
'blocked_pending_approval'
COUNT_CACHE_VALIDITY_PERIOD =
24.hours
OTP_SECRET_LENGTH =
32
OTP_SECRET_TTL =
2.minutes
MAX_USERNAME_LENGTH =
255
MIN_USERNAME_LENGTH =
2
MAX_LIMIT_FOR_ASSIGNEED_ISSUES_COUNT =
100
SECONDARY_EMAIL_ATTRIBUTES =
[
  :commit_email,
  :notification_email,
  :public_email
].freeze
FORBIDDEN_SEARCH_STATES =
%w[blocked banned ldap_blocked].freeze
INCOMING_MAIL_TOKEN_PREFIX =
'glimt-'
FEED_TOKEN_PREFIX =
'glft-'
MINIMUM_DAYS_CREATED =
7
DISALLOWED_PASSWORDS =
%w[123qweQWE!@#000000000].freeze
DELETION_DELAY_IN_DAYS =

rubocop: enable CodeReuse/ServiceClass

7.days

Constants included from RequireEmailVerification

RequireEmailVerification::MAXIMUM_ATTEMPTS, RequireEmailVerification::UNLOCK_IN

Constants included from EncryptedUserPassword

EncryptedUserPassword::BCRYPT_PREFIX, EncryptedUserPassword::BCRYPT_STRATEGY, EncryptedUserPassword::PBKDF2_SHA512_PREFIX, EncryptedUserPassword::PBKDF2_SHA512_STRATEGY

Constants included from HasUserType

HasUserType::BOT_USER_TYPES, HasUserType::INTERNAL_USER_TYPES, HasUserType::NON_INTERNAL_USER_TYPES, HasUserType::USER_TYPES

Constants included from UpdateHighestRole

UpdateHighestRole::HIGHEST_ROLE_JOB_DELAY, UpdateHighestRole::HIGHEST_ROLE_LEASE_TIMEOUT

Constants included from BatchDestroyDependentAssociations

BatchDestroyDependentAssociations::DEPENDENT_ASSOCIATIONS_BATCH_SIZE

Constants included from WithUploads

WithUploads::FILE_UPLOADERS

Constants included from BlocksUnsafeSerialization

BlocksUnsafeSerialization::UnsafeSerializationError

Constants included from Avatarable

Avatarable::ALLOWED_IMAGE_SCALER_WIDTHS, Avatarable::GROUP_AVATAR_SIZES, Avatarable::MAXIMUM_FILE_SIZE, Avatarable::PROJECT_AVATAR_SIZES, Avatarable::USER_AVATAR_SIZES

Constants included from Gitlab::SQL::Pattern

Gitlab::SQL::Pattern::MIN_CHARS_FOR_PARTIAL_MATCHING, Gitlab::SQL::Pattern::REGEX_QUOTED_TERM

Constants inherited from ApplicationRecord

ApplicationRecord::MAX_PLUCK

Constants included from ResetOnUnionError

ResetOnUnionError::MAX_RESET_PERIOD

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Gitlab::ConfigHelper

gitlab_config, gitlab_config_features

Methods included from ForcedEmailConfirmation

#force_confirm

Methods included from AfterCommitQueue

#run_after_commit, #run_after_commit_or_now

Methods included from AdminChangedPasswordNotifier

#send_only_admin_changed_your_password_notification!

Methods included from RecoverableByAnyEmail

#send_reset_password_instructions

Methods included from EncryptedUserPassword

#authenticatable_salt, #password=

Methods included from StripAttribute

#strip_attributes!

Methods included from Gitlab::Auth::Otp::DuoAuth

#duo_auth_enabled?

Methods included from HasUserType

#bot?, #internal?, #redacted_name, #resource_bot_owners, #resource_bot_resource

Methods included from BatchNullifyDependentAssociations

#nullify_dependent_associations_in_batches

Methods included from BatchDestroyDependentAssociations

#dependent_associations_to_destroy, #destroy_dependent_associations_in_batches

Methods included from WithUploads

#retrieve_upload

Methods included from FastDestroyAll::Helpers

#perform_fast_destroy

Methods included from BlocksUnsafeSerialization

#serializable_hash

Methods included from Gitlab::Utils::Override

#extended, extensions, #included, #method_added, #override, #prepended, #queue_verification, verify!

Methods included from FeatureGate

#flipper_id

Methods included from Referable

#referable_inspect, #reference_link_text, #to_reference_base

Methods included from Avatarable

#avatar_path, #avatar_type, #uncached_avatar_path, #upload_paths

Methods included from Gitlab::SQL::Pattern

split_query_to_search_terms

Methods inherited from ApplicationRecord

cached_column_list, #create_or_load_association, declarative_enum, default_select_columns, id_in, id_not_in, iid_in, pluck_primary_key, primary_key_in, #readable_by?, safe_ensure_unique, safe_find_or_create_by, safe_find_or_create_by!, #to_ability_name, underscore, where_exists, where_not_exists, with_fast_read_statement_timeout, without_order

Methods included from SensitiveSerializableHash

#serializable_hash

Instance Attribute Details

#force_random_passwordObject

rubocop: enable CodeReuse/ServiceClass



147
148
149
# File 'app/models/user.rb', line 147

def force_random_password
  @force_random_password
end

#impersonatorObject

Virtual attribute for impersonator



153
154
155
# File 'app/models/user.rb', line 153

def impersonator
  @impersonator
end

#loginObject

Virtual attribute for authenticating by either username or email



150
151
152
# File 'app/models/user.rb', line 150

def 
  @login
end

Class Method Details

.by_any_email(emails, confirmed: false) ⇒ Object

Returns a relation containing all found users by their primary email or any associated confirmed secondary email

Parameters:

  • emails (String, Array<String>)

    email addresses to check

  • confirmed (Boolean) (defaults to: false)

    Only return users where the primary email is confirmed



729
730
731
732
733
734
735
736
737
738
739
740
741
742
# File 'app/models/user.rb', line 729

def by_any_email(emails, confirmed: false)
  from_users = by_user_email(emails)
  from_users = from_users.confirmed if confirmed

  from_emails = by_emails(emails).merge(Email.confirmed)
  from_emails = from_emails.confirmed if confirmed

  items = [from_users, from_emails]

  user_ids = Gitlab::PrivateCommitEmail.user_ids_for_emails(Array(emails).map(&:downcase))
  items << where(id: user_ids) if user_ids.present?

  from_union(items)
end

.filter_items(filter_name) ⇒ Object



750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
# File 'app/models/user.rb', line 750

def filter_items(filter_name)
  case filter_name
  when 'admins'
    admins
  when 'blocked'
    blocked
  when 'blocked_pending_approval'
    blocked_pending_approval
  when 'banned'
    banned
  when 'two_factor_disabled'
    without_two_factor
  when 'two_factor_enabled'
    with_two_factor
  when 'wop'
    without_projects
  when 'external'
    external
  when 'deactivated'
    deactivated
  else
    active_without_ghosts
  end
end

.find_by_any_email(email, confirmed: false) ⇒ Object

Find a User by their primary email or any associated confirmed secondary email



718
719
720
721
722
# File 'app/models/user.rb', line 718

def find_by_any_email(email, confirmed: false)
  return unless email

  by_any_email(email, confirmed: confirmed).take
end

.find_by_full_path(path, follow_redirects: false) ⇒ Object



896
897
898
899
# File 'app/models/user.rb', line 896

def find_by_full_path(path, follow_redirects: false)
  namespace = Namespace.user_namespaces.find_by_full_path(path, follow_redirects: follow_redirects)
  namespace&.owner
end

.find_by_login(login) ⇒ Object



879
880
881
# File 'app/models/user.rb', line 879

def ()
  ().take
end

.find_by_private_commit_email(email) ⇒ Object



744
745
746
747
748
# File 'app/models/user.rb', line 744

def find_by_private_commit_email(email)
  user_id = Gitlab::PrivateCommitEmail.user_id_for_email(email)

  find_by(id: user_id)
end

.find_by_ssh_key_id(key_id) ⇒ Object

Returns a user for the given SSH key.



892
893
894
# File 'app/models/user.rb', line 892

def find_by_ssh_key_id(key_id)
  find_by('EXISTS (?)', Key.select(1).where('keys.user_id = users.id').auth.where(id: key_id))
end

.find_by_username(username) ⇒ Object



883
884
885
# File 'app/models/user.rb', line 883

def find_by_username(username)
  by_username(username).take
end

.find_by_username!(username) ⇒ Object



887
888
889
# File 'app/models/user.rb', line 887

def find_by_username!(username)
  by_username(username).take!
end

.find_for_database_authentication(warden_conditions) ⇒ Object

Devise method overridden to allow sign in with email or username



695
696
697
698
699
700
701
702
# File 'app/models/user.rb', line 695

def find_for_database_authentication(warden_conditions)
  conditions = warden_conditions.dup
  if  = conditions.delete(:login)
    where(conditions).find_by("lower(username) = :value OR lower(email) = :value", value: .downcase.strip)
  else
    find_by(conditions)
  end
end

.generate_incoming_mail_tokenObject



929
930
931
# File 'app/models/user.rb', line 929

def generate_incoming_mail_token
  "#{INCOMING_MAIL_TOKEN_PREFIX}#{SecureRandom.hex.to_i(16).to_s(36)}"
end

.get_ids_by_ids_or_usernames(ids, usernames) ⇒ Object



925
926
927
# File 'app/models/user.rb', line 925

def get_ids_by_ids_or_usernames(ids, usernames)
  by_ids_or_usernames(ids, usernames).pluck(:id)
end

.limit_to_todo_authors(user: nil, with_todos: false, todo_state: nil) ⇒ Object

Limits the users to those that have TODOs, optionally in the given state.

user - The user to get the todos for.

with_todos - If we should limit the result set to users that are the

authors of todos.

todo_state - An optional state to require the todos to be in.



648
649
650
651
652
653
654
# File 'app/models/user.rb', line 648

def self.limit_to_todo_authors(user: nil, with_todos: false, todo_state: nil)
  if user && with_todos
    where(id: Todo.where(user: user, state: todo_state).select(:author_id))
  else
    all
  end
end

.password_lengthObject

Devise method overridden to allow support for dynamic password lengths



685
686
687
# File 'app/models/user.rb', line 685

def password_length
  Gitlab::CurrentSettings.minimum_password_length..Devise.password_length.max
end

.random_passwordObject

Generate a random password that conforms to the current password length settings



690
691
692
# File 'app/models/user.rb', line 690

def random_password
  Devise.friendly_token(password_length.max)
end

.reference_patternObject

Pattern used to extract ‘@user` user references from text



906
907
908
909
910
911
912
913
# File 'app/models/user.rb', line 906

def reference_pattern
  @reference_pattern ||=
    %r{
      (?<!\w)
      #{Regexp.escape(reference_prefix)}
      (?<user>#{Gitlab::PathRegex::FULL_NAMESPACE_FORMAT_REGEX})
    }x
end

.reference_prefixObject



901
902
903
# File 'app/models/user.rb', line 901

def reference_prefix
  '@'
end

.reorder_by_nameObject



839
840
841
# File 'app/models/user.rb', line 839

def reorder_by_name
  reorder(:name)
end

.search(query, **options) ⇒ Object

Searches users matching the given query.

This method uses ILIKE on PostgreSQL.

query - The search query as a String with_private_emails - include private emails in search

Returns an ActiveRecord::Relation.



783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
# File 'app/models/user.rb', line 783

def search(query, **options)
  return none unless query.is_a?(String)

  query = query&.delete_prefix('@')
  return none if query.blank?

  query = query.downcase

  order = <<~SQL
    CASE
      WHEN LOWER(users.name) = :query THEN 0
      WHEN LOWER(users.username) = :query THEN 1
      WHEN LOWER(users.public_email) = :query THEN 2
      ELSE 3
    END
  SQL

  sanitized_order_sql = Arel.sql(sanitize_sql_array([order, query: query]))

  scope = options[:with_private_emails] ? with_primary_or_secondary_email(query) : with_public_email(query)
  scope = scope.or(search_by_name_or_username(query, use_minimum_char_limit: options[:use_minimum_char_limit]))

  order = Gitlab::Pagination::Keyset::Order.build(
    [
      Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
        attribute_name: 'users_match_priority',
        order_expression: sanitized_order_sql.asc,
        add_to_projections: true,
        distinct: false
      ),
      Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
        attribute_name: 'users_name',
        order_expression: arel_table[:name].asc,
        add_to_projections: true,
        nullable: :not_nullable,
        distinct: false
      ),
      Gitlab::Pagination::Keyset::ColumnOrderDefinition.new(
        attribute_name: 'users_id',
        order_expression: arel_table[:id].asc,
        add_to_projections: true,
        nullable: :not_nullable,
        distinct: true
      )
    ])
  scope.reorder(order)
end

.search_by_name_or_username(query, use_minimum_char_limit: nil) ⇒ Object

searches user by given pattern it compares name and username fields with given pattern This method uses ILIKE on PostgreSQL.



846
847
848
849
850
851
852
853
# File 'app/models/user.rb', line 846

def search_by_name_or_username(query, use_minimum_char_limit: nil)
  use_minimum_char_limit = user_search_minimum_char_limit if use_minimum_char_limit.nil?

  where(
    fuzzy_arel_match(:name, query, use_minimum_char_limit: use_minimum_char_limit)
      .or(fuzzy_arel_match(:username, query, use_minimum_char_limit: use_minimum_char_limit))
  )
end

.single_userObject



921
922
923
# File 'app/models/user.rb', line 921

def single_user
  User.non_internal.first if single_user?
end

.single_user?Boolean

Return true if there is only single non-internal user in the deployment, ghost user is ignored.

Returns:

  • (Boolean)


917
918
919
# File 'app/models/user.rb', line 917

def single_user?
  User.non_internal.limit(2).count == 1
end

.sort_by_attribute(method) ⇒ Object



704
705
706
707
708
709
710
711
712
713
714
715
# File 'app/models/user.rb', line 704

def sort_by_attribute(method)
  order_method = method || 'id_desc'

  case order_method.to_s
  when 'recent_sign_in' then 
  when 'oldest_sign_in' then 
  when 'last_activity_on_desc' then order_recent_last_activity
  when 'last_activity_on_asc' then order_oldest_last_activity
  else
    order_by(order_method)
  end
end

.union_with_user(user_id = nil) ⇒ Object

Returns a relation that optionally includes the given user.

user_id - The ID of the user to include.



659
660
661
662
663
664
665
666
667
# File 'app/models/user.rb', line 659

def self.union_with_user(user_id = nil)
  if user_id.present?
    # We use "unscoped" here so that any inner conditions are not repeated for
    # the outer query, which would be redundant.
    User.unscoped.from_union([all, User.unscoped.where(id: user_id)])
  else
    all
  end
end

.user_search_minimum_char_limitObject

This method is overridden in JiHu. gitlab.com/gitlab-org/gitlab/-/issues/348509



875
876
877
# File 'app/models/user.rb', line 875

def user_search_minimum_char_limit
  true
end

.where_not_in(users = nil) ⇒ Object

Limits the result set to users not in the given query/list of IDs.

users - The list of users to ignore. This can be an

`ActiveRecord::Relation`, or an Array.


835
836
837
# File 'app/models/user.rb', line 835

def where_not_in(users = nil)
  users ? where.not(id: users) : all
end

.with_primary_or_secondary_email(email_address) ⇒ Object



859
860
861
862
863
864
865
866
867
868
869
870
871
# File 'app/models/user.rb', line 859

def with_primary_or_secondary_email(email_address)
  email_table = Email.arel_table
  matched_by_email_user_id = email_table
    .project(email_table[:user_id])
    .where(email_table[:email].eq(email_address))
    .where(email_table[:confirmed_at].not_eq(nil))
    .take(1) # at most 1 record as there is a unique constraint

  where(
    arel_table[:email].eq(email_address)
    .or(arel_table[:id].eq(matched_by_email_user_id))
  )
end

.with_public_email(email_address) ⇒ Object



855
856
857
# File 'app/models/user.rb', line 855

def with_public_email(email_address)
  where(public_email: email_address)
end

.with_two_factorObject



669
670
671
672
# File 'app/models/user.rb', line 669

def self.with_two_factor
  where(otp_required_for_login: true)
    .or(where_exists(WebauthnRegistration.where(WebauthnRegistration.arel_table[:user_id].eq(arel_table[:id]))))
end

.with_visible_profile(user) ⇒ Object



630
631
632
633
634
635
636
637
638
# File 'app/models/user.rb', line 630

def self.with_visible_profile(user)
  return with_public_profile if user.nil?

  if user.admin?
    all
  else
    with_public_profile.or(where(id: user.id))
  end
end

.without_two_factorObject



674
675
676
677
678
# File 'app/models/user.rb', line 674

def self.without_two_factor
  where
    .missing(:webauthn_registrations)
    .where(otp_required_for_login: false)
end

Instance Method Details

#abuse_metadataObject



2223
2224
2225
2226
2227
2228
# File 'app/models/user.rb', line 2223

def 
  {
    account_age: ,
    two_factor_enabled: two_factor_enabled? ? 1 : 0
  }
end

#accept_pending_invitations!Object



1526
1527
1528
1529
1530
# File 'app/models/user.rb', line 1526

def accept_pending_invitations!
  pending_invitations.select do |member|
    member.accept_invite!(self)
  end
end

#access_levelObject

rubocop: enable CodeReuse/ServiceClass



1944
1945
1946
1947
1948
1949
1950
# File 'app/models/user.rb', line 1944

def access_level
  if admin?
    :admin
  else
    :regular
  end
end

#access_level=(new_level) ⇒ Object



1952
1953
1954
1955
1956
1957
# File 'app/models/user.rb', line 1952

def access_level=(new_level)
  new_level = new_level.to_s
  return unless %w[admin regular].include?(new_level)

  self.admin = (new_level == 'admin')
end

#accessible_deploy_keysObject



1402
1403
1404
1405
1406
1407
1408
# File 'app/models/user.rb', line 1402

def accessible_deploy_keys
  DeployKey.from_union(
    [
      DeployKey.where(id: project_deploy_keys.select(:deploy_key_id)),
      DeployKey.are_public
    ])
end

#account_age_in_daysObject



2208
2209
2210
# File 'app/models/user.rb', line 2208

def 
  (Date.current - created_at.to_date).to_i
end

#active_for_authentication?Boolean

Returns:

  • (Boolean)


609
610
611
612
613
614
615
# File 'app/models/user.rb', line 609

def active_for_authentication?
  return false unless super

  check_ldap_if_ldap_blocked!

  can?(:log_in)
end

#admin_unsubscribe!Object



1435
1436
1437
# File 'app/models/user.rb', line 1435

def admin_unsubscribe!
  update_column :admin_email_unsubscribed_at, Time.current
end

#all_emails(include_private_email: true) ⇒ Object



1536
1537
1538
1539
1540
1541
1542
# File 'app/models/user.rb', line 1536

def all_emails(include_private_email: true)
  all_emails = []
  all_emails << email unless temp_oauth_email?
  all_emails << private_commit_email if include_private_email
  all_emails.concat(emails.filter_map { |email| email.email if email.confirmed? })
  all_emails.uniq
end

#all_expanded_groupsObject

Returns a relation of groups the user has access to, including their parent and child groups (recursively).



1153
1154
1155
1156
1157
# File 'app/models/user.rb', line 1153

def all_expanded_groups
  return groups if groups.empty?

  Gitlab::ObjectHierarchy.new(groups).all_objects
end

#all_ssh_keysObject



1506
1507
1508
# File 'app/models/user.rb', line 1506

def all_ssh_keys
  keys.map(&:publishable_key)
end

#allow_password_authentication?Boolean

Returns:

  • (Boolean)


1268
1269
1270
# File 'app/models/user.rb', line 1268

def allow_password_authentication?
  allow_password_authentication_for_web? || allow_password_authentication_for_git?
end

#allow_password_authentication_for_git?Boolean

Returns:

  • (Boolean)


1276
1277
1278
# File 'app/models/user.rb', line 1276

def allow_password_authentication_for_git?
  Gitlab::CurrentSettings.password_authentication_enabled_for_git? && !password_based_omniauth_user?
end

#allow_password_authentication_for_web?Boolean

Returns:

  • (Boolean)


1272
1273
1274
# File 'app/models/user.rb', line 1272

def allow_password_authentication_for_web?
  Gitlab::CurrentSettings.password_authentication_enabled_for_web? && !ldap_user?
end

#allow_possible_spam?Boolean

Returns:

  • (Boolean)


2230
2231
2232
# File 'app/models/user.rb', line 2230

def allow_possible_spam?
  custom_attributes.by_key(UserCustomAttribute::ALLOW_POSSIBLE_SPAM).exists?
end

#already_forked?(project) ⇒ Boolean

Returns:

  • (Boolean)


1354
1355
1356
# File 'app/models/user.rb', line 1354

def already_forked?(project)
  !!fork_of(project)
end

#any_email?(check_email) ⇒ Boolean

Returns:

  • (Boolean)


1560
1561
1562
1563
1564
1565
1566
1567
1568
# File 'app/models/user.rb', line 1560

def any_email?(check_email)
  downcased = check_email.downcase

  # handle the outdated private commit email case
  return true if persisted? &&
      id == Gitlab::PrivateCommitEmail.user_id_for_email(downcased)

  all_emails.include?(check_email.downcase)
end

#assigned_open_issues_count(force: false) ⇒ Object



1869
1870
1871
1872
1873
# File 'app/models/user.rb', line 1869

def assigned_open_issues_count(force: false)
  Rails.cache.fetch(['users', id, 'assigned_open_issues_count'], force: force, expires_in: COUNT_CACHE_VALIDITY_PERIOD) do
    IssuesFinder.new(self, assignee_id: self.id, state: 'opened', non_archived: true).execute.count
  end
end

#assigned_open_merge_requests_count(force: false) ⇒ Object



1857
1858
1859
1860
1861
# File 'app/models/user.rb', line 1857

def assigned_open_merge_requests_count(force: false)
  Rails.cache.fetch(['users', id, 'assigned_open_merge_requests_count'], force: force, expires_in: COUNT_CACHE_VALIDITY_PERIOD) do
    MergeRequestsFinder.new(self, assignee_id: self.id, state: 'opened', non_archived: true).execute.count
  end
end

#authorizations_for_projects(min_access_level: nil, related_project_column: 'projects.id') ⇒ Object

Typically used in conjunction with projects table to get projects a user has been given access to. The param ‘related_project_column` is the column to compare to the project_authorizations. By default is projects.id

Example use: ‘Project.where(’EXISTS(?)‘, user.authorizations_for_projects)`



1199
1200
1201
1202
1203
1204
1205
1206
1207
# File 'app/models/user.rb', line 1199

def authorizations_for_projects(min_access_level: nil, related_project_column: 'projects.id')
  authorizations = project_authorizations
                    .select(1)
                    .where("project_authorizations.project_id = #{related_project_column}")

  return authorizations unless min_access_level.present?

  authorizations.where('project_authorizations.access_level >= ?', min_access_level)
end

#authorized_groupsObject

Returns the groups a user has access to, either through a membership or a project authorization



1140
1141
1142
1143
1144
# File 'app/models/user.rb', line 1140

def authorized_groups
  Group.unscoped do
    authorized_groups_with_shared_membership
  end
end

#authorized_project?(project, min_access_level = nil) ⇒ Boolean

Returns:

  • (Boolean)


1188
1189
1190
# File 'app/models/user.rb', line 1188

def authorized_project?(project, min_access_level = nil)
  authorized_projects(min_access_level).exists?({ id: project.id })
end

#authorized_project_mirrors(level) ⇒ Object



1789
1790
1791
1792
1793
1794
1795
# File 'app/models/user.rb', line 1789

def authorized_project_mirrors(level)
  projects = Ci::ProjectMirror.by_project_id(ci_project_ids_for_project_members(level))

  namespace_projects = Ci::ProjectMirror.by_namespace_id(ci_namespace_mirrors_for_group_members(level).select(:namespace_id))

  Ci::ProjectMirror.from_union([projects, namespace_projects])
end

#authorized_projects(min_access_level = nil) ⇒ Object

rubocop: enable CodeReuse/ServiceClass



1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
# File 'app/models/user.rb', line 1175

def authorized_projects(min_access_level = nil)
  # 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()

  if min_access_level
    projects = projects
      .where('project_authorizations.access_level >= ?', min_access_level)
  end

  projects
end

#avatar_url(size: nil, scale: 2, **args) ⇒ Object

rubocop: disable CodeReuse/ServiceClass



1515
1516
1517
# File 'app/models/user.rb', line 1515

def avatar_url(size: nil, scale: 2, **args)
  GravatarService.new.execute(email, size, scale, username: username)
end

#can?(action, subject = :global) ⇒ Boolean

Returns:

  • (Boolean)


1301
1302
1303
# File 'app/models/user.rb', line 1301

def can?(action, subject = :global)
  Ability.allowed?(self, action, subject)
end

#can_admin_all_resources?Boolean

Returns:

  • (Boolean)


1963
1964
1965
# File 'app/models/user.rb', line 1963

def can_admin_all_resources?
  can?(:admin_all_resources)
end

#can_be_deactivated?Boolean

Returns:

  • (Boolean)


2109
2110
2111
# File 'app/models/user.rb', line 2109

def can_be_deactivated?
  active? && no_recent_activity? && !internal?
end

#can_be_removed?Boolean

Returns true if the user can be removed, false otherwise. A user can be removed if they do not own any groups where they are the sole owner Method ‘none?` is used to ensure faster retrieval, See gitlab.com/gitlab-org/gitlab/-/issues/417105

Returns:

  • (Boolean)


1781
1782
1783
# File 'app/models/user.rb', line 1781

def can_be_removed?
  solo_owned_groups.none?
end

#can_change_username?Boolean

Returns:

  • (Boolean)


1285
1286
1287
# File 'app/models/user.rb', line 1285

def can_change_username?
  gitlab_config.username_changing_enabled
end

#can_create_group?Boolean

Returns:

  • (Boolean)


1293
1294
1295
# File 'app/models/user.rb', line 1293

def can_create_group?
  can?(:create_group)
end

#can_create_project?Boolean

Returns:

  • (Boolean)


1289
1290
1291
# File 'app/models/user.rb', line 1289

def can_create_project?
  projects_limit_left > 0
end

#can_leave_project?(project) ⇒ Boolean

Returns:

  • (Boolean)


1491
1492
1493
1494
# File 'app/models/user.rb', line 1491

def can_leave_project?(project)
  project.namespace != namespace &&
    project.member(self)
end

#can_log_in_with_non_expired_password?Boolean

Returns:

  • (Boolean)


2105
2106
2107
# File 'app/models/user.rb', line 2105

def 
  can?(:log_in) && !password_expired_if_applicable?
end

#can_read_all_resources?Boolean

Returns:

  • (Boolean)


1959
1960
1961
# File 'app/models/user.rb', line 1959

def can_read_all_resources?
  can?(:read_all_resources)
end

#can_remove_self?Boolean

Returns:

  • (Boolean)


1785
1786
1787
# File 'app/models/user.rb', line 1785

def can_remove_self?
  true
end

#can_select_namespace?Boolean

Returns:

  • (Boolean)


1297
1298
1299
# File 'app/models/user.rb', line 1297

def can_select_namespace?
  several_namespaces? || admin
end

#can_trigger_notifications?Boolean

Returns:

  • (Boolean)


2178
2179
2180
# File 'app/models/user.rb', line 2178

def can_trigger_notifications?
  confirmed? && !blocked? && !ghost?
end

#check_for_verified_emailObject

see if the new email is already a verified secondary email



1131
1132
1133
# File 'app/models/user.rb', line 1131

def check_for_verified_email
  skip_reconfirmation! if emails.confirmed.where(email: self.email).any?
end

#ci_job_token_scopeObject

This attribute hosts a Ci::JobToken::Scope object which is set when the user is authenticated successfully via CI_JOB_TOKEN.



2184
2185
2186
# File 'app/models/user.rb', line 2184

def ci_job_token_scope
  Gitlab::SafeRequestStore[ci_job_token_scope_cache_key]
end

#ci_owned_runnersObject



1797
1798
1799
1800
1801
1802
# File 'app/models/user.rb', line 1797

def ci_owned_runners
  @ci_owned_runners ||= Ci::Runner
      .from_union([ci_owned_project_runners_from_project_members,
                   ci_owned_project_runners_from_group_members,
                   ci_owned_group_runners])
end

#commit_email_or_defaultObject



1112
1113
1114
1115
1116
1117
1118
1119
# File 'app/models/user.rb', line 1112

def commit_email_or_default
  if self.commit_email == Gitlab::PrivateCommitEmail::TOKEN
    return private_commit_email
  end

  # The commit email is the same as the primary email if undefined
  self.commit_email.presence || self.email
end

#confirm_deletion_with_password?Boolean

Returns:

  • (Boolean)


1305
1306
1307
# File 'app/models/user.rb', line 1305

def confirm_deletion_with_password?
  !password_automatically_set? && allow_password_authentication?
end

#confirmation_required_on_sign_in?Boolean

Returns:

  • (Boolean)


2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
# File 'app/models/user.rb', line 2144

def confirmation_required_on_sign_in?
  return false if confirmed?

  if ::Gitlab::CurrentSettings.email_confirmation_setting_off?
    false
  elsif ::Gitlab::CurrentSettings.email_confirmation_setting_soft?
    !in_confirmation_period?
  elsif ::Gitlab::CurrentSettings.email_confirmation_setting_hard?
    true
  end
end

#contributed_projectsObject

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 ms on a database with a similar size to GitLab.com’s database. On the other hand, using a subquery means we can get the exact same data in about 40 ms.



1767
1768
1769
1770
1771
1772
1773
1774
1775
# File 'app/models/user.rb', line 1767

def contributed_projects
  events = Event.select(:project_id)
    .contributions.where(author_id: self)
    .where("created_at > ?", Time.current - 1.year)
    .distinct
    .reorder(nil)

  Project.where(id: events).not_aimed_for_deletion
end

#created_byObject



1410
1411
1412
# File 'app/models/user.rb', line 1410

def created_by
  User.find_by(id: created_by_id) if created_by_id
end

#created_recently?Boolean

Returns:

  • (Boolean)


2160
2161
2162
# File 'app/models/user.rb', line 2160

def created_recently?
  created_at > Devise.confirm_within.ago
end

#credit_card_validated_atObject



1398
1399
1400
# File 'app/models/user.rb', line 1398

def credit_card_validated_at
  credit_card_validation&.credit_card_validated_at
end

#crowd_user?Boolean

Returns:

  • (Boolean)


1366
1367
1368
1369
1370
1371
1372
# File 'app/models/user.rb', line 1366

def crowd_user?
  if identities.loaded?
    identities.find { |identity| identity.provider == 'crowd' && identity.extern_uid.present? }
  else
    identities.with_any_extern_uid('crowd').exists?
  end
end

#current_highest_access_levelObject

Load the current highest access by looking directly at the user’s memberships



2140
2141
2142
# File 'app/models/user.rb', line 2140

def current_highest_access_level
  members.non_request.maximum(:access_level)
end

#delete_async(deleted_by:, params: {}) ⇒ Object



1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
# File 'app/models/user.rb', line 1635

def delete_async(deleted_by:, params: {})
  if should_delay_delete?(deleted_by)
    new_note = format(_("User deleted own account on %{timestamp}"), timestamp: Time.zone.now)
    self.note = "#{new_note}\n#{note}".strip

    block_or_ban
    DeleteUserWorker.perform_in(DELETION_DELAY_IN_DAYS, deleted_by.id, id, params.to_h)

    return
  end

  block if params[:hard_delete]

  DeleteUserWorker.perform_async(deleted_by.id, id, params.to_h)
end

#disable_two_factor!Object



1034
1035
1036
1037
1038
1039
1040
# File 'app/models/user.rb', line 1034

def disable_two_factor!
  transaction do
    self.disable_webauthn!
    self.disable_two_factor_otp!
    self.reset_backup_codes!
  end
end

#disable_two_factor_otp!Object



1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
# File 'app/models/user.rb', line 1042

def disable_two_factor_otp!
  update(
    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_secret_expires_at: nil
  )
end

#disable_webauthn!Object



1053
1054
1055
# File 'app/models/user.rb', line 1053

def disable_webauthn!
  self.webauthn_registrations.destroy_all # rubocop:disable Cop/DestroyAll
end

#dismissed_callout?(feature_name:, ignore_dismissal_earlier_than: nil) ⇒ Boolean

Returns:

  • (Boolean)


2120
2121
2122
2123
2124
# File 'app/models/user.rb', line 2120

def dismissed_callout?(feature_name:, ignore_dismissal_earlier_than: nil)
  callout = callouts_by_feature_name[feature_name]

  callout_dismissed?(callout, ignore_dismissal_earlier_than)
end

#dismissed_callout_for_group?(feature_name:, group:, ignore_dismissal_earlier_than: nil) ⇒ Boolean

Returns:

  • (Boolean)


2126
2127
2128
2129
2130
2131
# File 'app/models/user.rb', line 2126

def dismissed_callout_for_group?(feature_name:, group:, ignore_dismissal_earlier_than: nil)
  source_feature_name = "#{feature_name}_#{group.id}"
  callout = group_callouts_by_feature_name[source_feature_name]

  callout_dismissed?(callout, ignore_dismissal_earlier_than)
end

#dismissed_callout_for_project?(feature_name:, project:, ignore_dismissal_earlier_than: nil) ⇒ Boolean

Returns:

  • (Boolean)


2133
2134
2135
2136
2137
# File 'app/models/user.rb', line 2133

def dismissed_callout_for_project?(feature_name:, project:, ignore_dismissal_earlier_than: nil)
  callout = project_callouts.find_by(feature_name: feature_name, project: project)

  callout_dismissed?(callout, ignore_dismissal_earlier_than)
end

#enabled_incoming_email_tokenObject



1994
1995
1996
# File 'app/models/user.rb', line 1994

def enabled_incoming_email_token
  incoming_email_token if Gitlab::Email::IncomingEmail.supports_issue_creation?
end

#enabled_static_object_tokenObject



1990
1991
1992
# File 'app/models/user.rb', line 1990

def enabled_static_object_token
  static_object_token if Gitlab::CurrentSettings.static_objects_external_storage_enabled?
end

#ensure_namespace_correctObject



1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
# File 'app/models/user.rb', line 1590

def ensure_namespace_correct
  if namespace
    namespace.path = username if username_changed?
    namespace.name = name if name_changed?
  else
    # TODO: we should no longer need the `type` parameter once we can make the
    #       the `has_one :namespace` association use the correct class.
    #       issue https://gitlab.com/gitlab-org/gitlab/-/issues/341070
    namespace = build_namespace(path: username, name: name, type: ::Namespaces::UserNamespace.sti_name)
    namespace.build_namespace_settings
  end
end

#expanded_groups_requiring_two_factor_authenticationObject



1159
1160
1161
# File 'app/models/user.rb', line 1159

def expanded_groups_requiring_two_factor_authentication
  all_expanded_groups.where(require_two_factor_authentication: true)
end

#feed_tokenObject

each existing user needs to have a ‘feed_token`. we do this on read since migrating all existing users is not a feasible solution.



1979
1980
1981
# File 'app/models/user.rb', line 1979

def feed_token
  ensure_feed_token! unless Gitlab::CurrentSettings.disable_feed_token
end

#find_or_initialize_callout(feature_name) ⇒ Object



2164
2165
2166
# File 'app/models/user.rb', line 2164

def find_or_initialize_callout(feature_name)
  callouts.find_or_initialize_by(feature_name: ::Users::Callout.feature_names[feature_name])
end

#find_or_initialize_group_callout(feature_name, group_id) ⇒ Object



2168
2169
2170
2171
# File 'app/models/user.rb', line 2168

def find_or_initialize_group_callout(feature_name, group_id)
  group_callouts
    .find_or_initialize_by(feature_name: ::Users::GroupCallout.feature_names[feature_name], group_id: group_id)
end

#find_or_initialize_project_callout(feature_name, project_id) ⇒ Object



2173
2174
2175
2176
# File 'app/models/user.rb', line 2173

def find_or_initialize_project_callout(feature_name, project_id)
  project_callouts
    .find_or_initialize_by(feature_name: ::Users::ProjectCallout.feature_names[feature_name], project_id: project_id)
end

#first_nameObject



1309
1310
1311
1312
1313
# File 'app/models/user.rb', line 1309

def first_name
  read_attribute(:first_name) || begin
    name.split(' ').first unless name.blank?
  end
end

#follow(user) ⇒ Object



1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
# File 'app/models/user.rb', line 1692

def follow(user)
  return false unless following_users_allowed?(user)

  begin
    followee = Users::UserFollowUser.create(follower_id: self.id, followee_id: user.id)
    self.followees.reset if followee.persisted?
    followee
  rescue ActiveRecord::RecordNotUnique
    nil
  end
end

#followed_by?(user) ⇒ Boolean

Returns:

  • (Boolean)


1688
1689
1690
# File 'app/models/user.rb', line 1688

def followed_by?(user)
  self.followers.include?(user)
end

#following?(user) ⇒ Boolean

Returns:

  • (Boolean)


1684
1685
1686
# File 'app/models/user.rb', line 1684

def following?(user)
  self.followees.exists?(user.id)
end

#following_users_allowed?(user) ⇒ Boolean

Returns:

  • (Boolean)


1712
1713
1714
1715
1716
# File 'app/models/user.rb', line 1712

def following_users_allowed?(user)
  return false if self.id == user.id

  enabled_following && user.enabled_following
end

#forget_me!Object



1019
1020
1021
# File 'app/models/user.rb', line 1019

def forget_me!
  super if ::Gitlab::Database.read_write?
end

#fork_of(project) ⇒ Object



1358
1359
1360
# File 'app/models/user.rb', line 1358

def fork_of(project)
  namespace.find_fork_of(project)
end

#forkable_namespacesObject



1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
# File 'app/models/user.rb', line 1718

def forkable_namespaces
  strong_memoize(:forkable_namespaces) do
    personal_namespace = Namespace.where(id: namespace_id)
    groups_allowing_project_creation = Groups::AcceptingProjectCreationsFinder.new(self).execute

    Namespace.from_union(
      [
        groups_allowing_project_creation,
        personal_namespace
      ])
  end
end

#from_ci_job_token?Boolean

Returns:

  • (Boolean)


2192
2193
2194
# File 'app/models/user.rb', line 2192

def from_ci_job_token?
  ci_job_token_scope.present?
end

#full_pathObject

Instance methods



938
939
940
# File 'app/models/user.rb', line 938

def full_path
  username
end

#full_website_urlObject



1496
1497
1498
1499
1500
# File 'app/models/user.rb', line 1496

def full_website_url
  return "http://#{website_url}" unless %r{\Ahttps?://}.match?(website_url)

  website_url
end

#generate_otp_backup_codes!Object



981
982
983
984
985
986
987
# File 'app/models/user.rb', line 981

def generate_otp_backup_codes!
  if Gitlab::FIPS.enabled?
    generate_otp_backup_codes_pbkdf2!
  else
    super
  end
end

#generate_reset_tokenObject



958
959
960
961
962
963
964
965
# File 'app/models/user.rb', line 958

def generate_reset_token
  @reset_token, enc = Devise.token_generator.generate(self.class, :reset_password_token)

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

  @reset_token
end

#global_notification_settingObject

Lazy load global notification setting Initializes User setting with Participating level if setting not persisted



1848
1849
1850
1851
1852
1853
1854
1855
# File 'app/models/user.rb', line 1848

def global_notification_setting
  return @global_notification_setting if defined?(@global_notification_setting)

  @global_notification_setting = notification_settings.find_or_initialize_by(source: nil)
  @global_notification_setting.update(level: NotificationSetting.levels[DEFAULT_NOTIFICATION_LEVEL]) unless @global_notification_setting.persisted?

  @global_notification_setting
end

#highest_roleObject



1394
1395
1396
# File 'app/models/user.rb', line 1394

def highest_role
  user_highest_role&.highest_access_level || Gitlab::Access::NO_ACCESS
end

#hook_attrsObject



1580
1581
1582
1583
1584
1585
1586
1587
1588
# File 'app/models/user.rb', line 1580

def hook_attrs
  {
    id: id,
    name: name,
    username: username,
    avatar_url: avatar_url(only_path: false),
    email: webhook_email
  }
end

#impersonated?Boolean

Returns:

  • (Boolean)


2156
2157
2158
# File 'app/models/user.rb', line 2156

def impersonated?
  impersonator.present?
end

#inactive_messageObject

The messages for these keys are defined in ‘devise.en.yml`



618
619
620
621
622
623
624
625
626
627
628
# File 'app/models/user.rb', line 618

def inactive_message
  if blocked_pending_approval?
    :blocked_pending_approval
  elsif blocked?
    :blocked
  elsif internal?
    :forbidden
  else
    super
  end
end

#increment_failed_attempts!Object

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.7.1/lib/devise/models/lockable.rb#L104>

rubocop: disable CodeReuse/ServiceClass



1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
# File 'app/models/user.rb', line 1931

def increment_failed_attempts!
  return if ::Gitlab::Database.read_only?

  increment_failed_attempts

  if attempts_exceeded?
    lock_access! unless access_locked?
  else
    Users::UpdateService.new(self, user: self).execute(validate: false)
  end
end

#invalidate_cache_countsObject



1898
1899
1900
1901
1902
1903
# File 'app/models/user.rb', line 1898

def invalidate_cache_counts
  invalidate_issue_cache_counts
  invalidate_merge_request_cache_counts
  invalidate_todos_cache_counts
  invalidate_personal_projects_count
end

#invalidate_issue_cache_countsObject



1905
1906
1907
1908
# File 'app/models/user.rb', line 1905

def invalidate_issue_cache_counts
  Rails.cache.delete(['users', id, 'assigned_open_issues_count'])
  Rails.cache.delete(['users', id, 'max_assigned_open_issues_count'])
end

#invalidate_merge_request_cache_countsObject



1910
1911
1912
1913
# File 'app/models/user.rb', line 1910

def invalidate_merge_request_cache_counts
  Rails.cache.delete(['users', id, 'assigned_open_merge_requests_count'])
  Rails.cache.delete(['users', id, 'review_requested_open_merge_requests_count'])
end

#invalidate_otp_backup_code!(code) ⇒ Object



989
990
991
992
993
994
995
# File 'app/models/user.rb', line 989

def invalidate_otp_backup_code!(code)
  if Gitlab::FIPS.enabled? && pbkdf2?
    invalidate_otp_backup_code_pdkdf2!(code)
  else
    super(code)
  end
end

#invalidate_personal_projects_countObject



1920
1921
1922
# File 'app/models/user.rb', line 1920

def invalidate_personal_projects_count
  Rails.cache.delete(['users', id, 'personal_projects_count'])
end

#invalidate_todos_cache_countsObject



1915
1916
1917
1918
# File 'app/models/user.rb', line 1915

def invalidate_todos_cache_counts
  Rails.cache.delete(['users', id, 'todos_done_count'])
  Rails.cache.delete(['users', id, 'todos_pending_count'])
end

#last_active_atObject



2113
2114
2115
2116
2117
2118
# File 'app/models/user.rb', line 2113

def last_active_at
  last_activity = last_activity_on&.to_time&.in_time_zone
   = 

  [last_activity, ].compact.max
end

#last_nameObject



1315
1316
1317
1318
1319
# File 'app/models/user.rb', line 1315

def last_name
  read_attribute(:last_name) || begin
    name.split(' ').drop(1).join(' ') unless name.blank?
  end
end

#ldap_identityObject



1382
1383
1384
# File 'app/models/user.rb', line 1382

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

#ldap_sync_timeObject



1458
1459
1460
1461
# File 'app/models/user.rb', line 1458

def ldap_sync_time
  # This number resides in this method so it can be redefined in EE.
  1.hour
end

#ldap_user?Boolean

Returns:

  • (Boolean)


1374
1375
1376
1377
1378
1379
1380
# File 'app/models/user.rb', line 1374

def ldap_user?
  if identities.loaded?
    identities.find { |identity| Gitlab::Auth::OAuth::Provider.ldap_provider?(identity.provider) && !identity.extern_uid.nil? }
  else
    identities.exists?(["provider LIKE ? AND extern_uid IS NOT NULL", "ldap%"])
  end
end

#lock_access!(opts = {}) ⇒ Object

override, from Devise



2015
2016
2017
2018
2019
# File 'app/models/user.rb', line 2015

def lock_access!(opts = {})
  Gitlab::AppLogger.info("Account Locked: username=#{username}")
  audit_lock_access(reason: opts.delete(:reason))
  super
end

#log_info(message) ⇒ Object

rubocop: enable CodeReuse/ServiceClass



1657
1658
1659
# File 'app/models/user.rb', line 1657

def log_info(message)
  Gitlab::AppLogger.info message
end

#manageable_groups(include_groups_with_developer_maintainer_access: false) ⇒ Object



1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
# File 'app/models/user.rb', line 1731

def manageable_groups(include_groups_with_developer_maintainer_access: false)
  owned_and_maintainer_group_hierarchy = owned_or_maintainers_groups.self_and_descendants

  if include_groups_with_developer_maintainer_access
    union_sql = ::Gitlab::SQL::Union.new(
      [owned_and_maintainer_group_hierarchy,
       groups_with_developer_maintainer_project_access]).to_sql

    ::Group.from("(#{union_sql}) #{::Group.table_name}")
  else
    owned_and_maintainer_group_hierarchy
  end
end

#matches_identity?(provider, extern_uid) ⇒ Boolean

Returns:

  • (Boolean)


1386
1387
1388
# File 'app/models/user.rb', line 1386

def matches_identity?(provider, extern_uid)
  identities.with_extern_uid(provider, extern_uid).exists?
end

#max_member_access_for_group(group_id) ⇒ Object



2060
2061
2062
# File 'app/models/user.rb', line 2060

def max_member_access_for_group(group_id)
  max_member_access_for_group_ids([group_id])[group_id]
end

#max_member_access_for_group_ids(group_ids) ⇒ Object

Determine the maximum access level for a group of groups in bulk.

Returns a Hash mapping project ID -> maximum access level.



2050
2051
2052
2053
2054
2055
2056
2057
2058
# File 'app/models/user.rb', line 2050

def max_member_access_for_group_ids(group_ids)
  Gitlab::SafeRequestLoader.execute(
    resource_key: max_member_access_for_resource_key(Group),
    resource_ids: group_ids,
    default_value: Gitlab::Access::NO_ACCESS
  ) do |group_ids|
    group_members.where(source: group_ids).group(:source_id).maximum(:access_level)
  end
end

#max_member_access_for_project(project_id) ⇒ Object



2043
2044
2045
# File 'app/models/user.rb', line 2043

def max_member_access_for_project(project_id)
  max_member_access_for_project_ids([project_id])[project_id]
end

#max_member_access_for_project_ids(project_ids) ⇒ Object

Determine the maximum access level for a group of projects in bulk.

Returns a Hash mapping project ID -> maximum access level.



2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
# File 'app/models/user.rb', line 2031

def max_member_access_for_project_ids(project_ids)
  Gitlab::SafeRequestLoader.execute(
    resource_key: max_member_access_for_resource_key(Project),
    resource_ids: project_ids,
    default_value: Gitlab::Access::NO_ACCESS
  ) do |project_ids|
    project_authorizations.where(project: project_ids)
                          .group(:project_id)
                          .maximum(:access_level)
  end
end

#membership_groupsObject

Returns the groups a user is a member of, either directly or through a parent group



1147
1148
1149
# File 'app/models/user.rb', line 1147

def membership_groups
  groups.self_and_descendants
end

#name_with_usernameObject



1350
1351
1352
# File 'app/models/user.rb', line 1350

def name_with_username
  "#{name} (#{username})"
end

#namespace_commit_email_for_namespace(namespace) ⇒ Object



2234
2235
2236
2237
2238
# File 'app/models/user.rb', line 2234

def namespace_commit_email_for_namespace(namespace)
  return if namespace.nil?

  namespace_commit_emails.find_by(namespace: namespace)
end

#namespace_commit_email_for_project(project) ⇒ Object



2216
2217
2218
2219
2220
2221
# File 'app/models/user.rb', line 2216

def namespace_commit_email_for_project(project)
  return if project.nil?

  namespace_commit_emails.find_by(namespace: project.project_namespace) ||
    namespace_commit_emails.find_by(namespace: project.root_namespace)
end

#namespace_idObject



1346
1347
1348
# File 'app/models/user.rb', line 1346

def namespace_id
  namespace.try :id
end

#namespace_move_dir_allowedObject



1091
1092
1093
1094
1095
# File 'app/models/user.rb', line 1091

def namespace_move_dir_allowed
  if namespace&.any_project_has_container_registry_tags?
    errors.add(:username, _('cannot be changed if a personal project has container registry tags.'))
  end
end

#namespaces(owned_only: false) ⇒ Object



1745
1746
1747
1748
1749
1750
# File 'app/models/user.rb', line 1745

def namespaces(owned_only: false)
  user_groups = owned_only ? owned_groups : groups
  personal_namespace = Namespace.where(id: namespace.id)

  Namespace.from_union([user_groups, personal_namespace])
end

#needs_new_otp_secret?Boolean

Returns:

  • (Boolean)


1076
1077
1078
# File 'app/models/user.rb', line 1076

def needs_new_otp_secret?
  !two_factor_enabled? && otp_secret_expired?
end

#notification_email_for(notification_group) ⇒ Object



1808
1809
1810
1811
1812
1813
1814
1815
# File 'app/models/user.rb', line 1808

def notification_email_for(notification_group)
  # Return group-specific email address if present, otherwise return global notification email address
  group_email = if notification_group && notification_group.respond_to?(:notification_email_for)
                  notification_group.notification_email_for(self)
                end

  group_email || notification_email_or_default
end

#notification_email_or_defaultObject



1121
1122
1123
1124
# File 'app/models/user.rb', line 1121

def notification_email_or_default
  # The notification email is the same as the primary email if undefined
  self.notification_email.presence || self.email
end

#notification_serviceObject

rubocop: disable CodeReuse/ServiceClass



1652
1653
1654
# File 'app/models/user.rb', line 1652

def notification_service
  NotificationService.new
end

#notification_settings_for(source, inherit: false) ⇒ Object



1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
# File 'app/models/user.rb', line 1817

def notification_settings_for(source, inherit: false)
  if notification_settings.loaded?
    notification_settings.find do |notification|
      notification.source_type == source.class.base_class.name &&
        notification.source_id == source.id
    end
  else
    notification_settings.find_or_initialize_by(source: source) do |ns|
      next unless source.is_a?(Group) && inherit

      # If we're here it means we're trying to create a NotificationSetting for a group that doesn't have one.
      # Find the closest parent with a notification_setting that's not Global level, or that has an email set.
      ancestor_ns = source
                      .notification_settings(hierarchy_order: :asc)
                      .where(user: self)
                      .find_by('level != ? OR notification_email IS NOT NULL', NotificationSetting.levels[:global])
      # Use it to seed the settings
      ns.assign_attributes(ancestor_ns&.slice(*NotificationSetting.allowed_fields))
      ns.source = source
      ns.user = self
    end
  end
end

#notification_settings_for_groups(groups) ⇒ Object



1841
1842
1843
1844
# File 'app/models/user.rb', line 1841

def notification_settings_for_groups(groups)
  ids = groups.is_a?(ActiveRecord::Relation) ? groups.select(:id) : groups.map(&:id)
  notification_settings.for_groups.where(source_id: ids)
end

#oauth_authorized_tokensObject



1752
1753
1754
# File 'app/models/user.rb', line 1752

def oauth_authorized_tokens
  OauthAccessToken.where(resource_owner_id: id, revoked_at: nil)
end

#otp_secret_expired?Boolean

Returns:

  • (Boolean)


1080
1081
1082
1083
1084
# File 'app/models/user.rb', line 1080

def otp_secret_expired?
  return true unless otp_secret_expires_at

  otp_secret_expires_at < Time.current
end

#owned_projectsObject



1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
# File 'app/models/user.rb', line 1219

def owned_projects
  @owned_projects ||= Project.from_union(
    [
      Project.where(namespace: namespace),
      Project.joins(:project_authorizations)
        .where.not('projects.namespace_id' => namespace.id)
        .where(project_authorizations: { user_id: id, access_level: Gitlab::Access::OWNER })
    ],
    remove_duplicates: false
  )
end

#owns_runner?(runner) ⇒ Boolean

Returns:

  • (Boolean)


1804
1805
1806
# File 'app/models/user.rb', line 1804

def owns_runner?(runner)
  ci_owned_runners.include?(runner)
end

#password_allowed?(password) ⇒ Boolean

Returns:

  • (Boolean)


1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'app/models/user.rb', line 1000

def password_allowed?(password)
  password_allowed = true

  DISALLOWED_PASSWORDS.each do |disallowed_password|
    password_allowed = false if Devise.secure_compare(password, disallowed_password)
  end

  password_allowed
end

#password_based_login_forbidden?Boolean

method overriden in EE

Returns:

  • (Boolean)


1281
1282
1283
# File 'app/models/user.rb', line 1281

def 
  false
end

#password_based_omniauth_user?Boolean

Returns:

  • (Boolean)


1362
1363
1364
# File 'app/models/user.rb', line 1362

def password_based_omniauth_user?
  ldap_user? || crowd_user?
end

#password_expired?Boolean

Returns:

  • (Boolean)


2092
2093
2094
# File 'app/models/user.rb', line 2092

def password_expired?
  !!(password_expires_at && password_expires_at < Time.current)
end

#password_expired_if_applicable?Boolean

Returns:

  • (Boolean)


2096
2097
2098
2099
2100
2101
2102
2103
# File 'app/models/user.rb', line 2096

def password_expired_if_applicable?
  return false if bot?
  return false unless password_expired?
  return false if password_automatically_set?
  return false unless allow_password_authentication?

  true
end

#pending_invitationsObject



1532
1533
1534
# File 'app/models/user.rb', line 1532

def pending_invitations
  Member.where(invite_email: verified_emails).invite
end

#pending_todo_for(target) ⇒ Object



2088
2089
2090
# File 'app/models/user.rb', line 2088

def pending_todo_for(target)
  todos.find_by(target: target, state: :pending)
end

#personal_projects_count(force: false) ⇒ Object



1887
1888
1889
1890
1891
# File 'app/models/user.rb', line 1887

def personal_projects_count(force: false)
  Rails.cache.fetch(['users', id, 'personal_projects_count'], force: force, expires_in: 24.hours, raw: true) do
    personal_projects.count
  end.to_i
end

#post_destroy_hookObject



1621
1622
1623
1624
1625
# File 'app/models/user.rb', line 1621

def post_destroy_hook
  log_info("User \"#{name}\" (#{email})  was removed")

  system_hook_service.execute_hooks_for(self, :destroy)
end

#preferred_languageObject



605
606
607
# File 'app/models/user.rb', line 605

def preferred_language
  read_attribute('preferred_language').presence || Gitlab::CurrentSettings.default_preferred_language
end

#preloaded_member_roles_for_projects(projects) ⇒ Object



1238
1239
1240
# File 'app/models/user.rb', line 1238

def preloaded_member_roles_for_projects(projects)
  # overridden in EE
end

#primary_email_verified?Boolean

rubocop: enable CodeReuse/ServiceClass

Returns:

  • (Boolean)


1520
1521
1522
1523
1524
# File 'app/models/user.rb', line 1520

def primary_email_verified?
  return false unless confirmed? && !temp_oauth_email?

  !email_changed? || new_record?
end

#private_commit_emailObject



1126
1127
1128
# File 'app/models/user.rb', line 1126

def private_commit_email
  Gitlab::PrivateCommitEmail.for_user(self)
end

#project_deploy_keysObject



1390
1391
1392
# File 'app/models/user.rb', line 1390

def project_deploy_keys
  @project_deploy_keys ||= DeployKey.in_projects(authorized_projects.select(:id)).distinct(:id)
end

#projects_limit_leftObject



1321
1322
1323
# File 'app/models/user.rb', line 1321

def projects_limit_left
  projects_limit - personal_projects_count
end

#projects_where_can_admin_issuesObject

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.



1234
1235
1236
# File 'app/models/user.rb', line 1234

def projects_where_can_admin_issues
  authorized_projects(Gitlab::Access::REPORTER).non_archived.with_issues_enabled
end

#projects_with_reporter_access_limited_to(projects) ⇒ Object

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.



1215
1216
1217
# File 'app/models/user.rb', line 1215

def projects_with_reporter_access_limited_to(projects)
  authorized_projects(Gitlab::Access::REPORTER).where(id: projects)
end

#public_verified_emailsObject



1552
1553
1554
1555
1556
1557
1558
# File 'app/models/user.rb', line 1552

def public_verified_emails
  strong_memoize(:public_verified_emails) do
    emails = verified_emails(include_private_email: false)
    emails << email unless temp_oauth_email?
    emails.uniq
  end
end

#read_only_attribute?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


2010
2011
2012
# File 'app/models/user.rb', line 2010

def read_only_attribute?(attribute)
  &.read_only?(attribute)
end

#recent_push(project = nil) ⇒ Object

rubocop: disable CodeReuse/ServiceClass



1326
1327
1328
1329
1330
1331
1332
1333
1334
# File 'app/models/user.rb', line 1326

def recent_push(project = nil)
  service = Users::LastPushEventService.new(self)

  if project
    service.last_event_for_project(project)
  else
    service.last_event_for_user
  end
end

#recently_sent_password_reset?Boolean

Returns:

  • (Boolean)


967
968
969
# File 'app/models/user.rb', line 967

def recently_sent_password_reset?
  reset_password_sent_at.present? && reset_password_sent_at >= 1.minute.ago
end

#refresh_authorized_projects(source: nil) ⇒ Object

rubocop: disable CodeReuse/ServiceClass



1170
1171
1172
# File 'app/models/user.rb', line 1170

def refresh_authorized_projects(source: nil)
  Users::RefreshAuthorizedProjectsService.new(self, source: source).execute
end

#remember_me!Object

Override Devise Rememberable#remember_me!

In Devise this method sets ‘remember_created_at` and writes the session token to the session cookie. When remember me is disabled this method ensures these values aren’t set.



1015
1016
1017
# File 'app/models/user.rb', line 1015

def remember_me!
  super if ::Gitlab::Database.read_write? && ::Gitlab::CurrentSettings.remember_me_enabled?
end

#remember_me?(token, generated_at) ⇒ Boolean

Override Devise Rememberable#remember_me?

In Devise this method compares the remember me token received from the user session and compares to the stored value. When remember me is disabled this method ensures the upstream comparison does not happen.

Returns:

  • (Boolean)


1028
1029
1030
1031
1032
# File 'app/models/user.rb', line 1028

def remember_me?(token, generated_at)
  return false unless ::Gitlab::CurrentSettings.remember_me_enabled?

  super
end

#remove_key_cacheObject

rubocop: disable CodeReuse/ServiceClass



1628
1629
1630
# File 'app/models/user.rb', line 1628

def remove_key_cache
  Users::KeysCountService.new(self).delete_cache
end

#require_extra_setup_for_git_auth?Boolean

Returns:

  • (Boolean)


1264
1265
1266
# File 'app/models/user.rb', line 1264

def require_extra_setup_for_git_auth?
  require_password_creation_for_git? || require_personal_access_token_creation_for_git_auth?
end

#require_password_creation_for_git?Boolean

Returns:

  • (Boolean)


1254
1255
1256
# File 'app/models/user.rb', line 1254

def require_password_creation_for_git?
  allow_password_authentication_for_git? && password_automatically_set?
end

#require_password_creation_for_web?Boolean

rubocop: enable CodeReuse/ServiceClass

Returns:

  • (Boolean)


1250
1251
1252
# File 'app/models/user.rb', line 1250

def require_password_creation_for_web?
  allow_password_authentication_for_web? && password_automatically_set?
end

#require_personal_access_token_creation_for_git_auth?Boolean

Returns:

  • (Boolean)


1258
1259
1260
1261
1262
# File 'app/models/user.rb', line 1258

def require_personal_access_token_creation_for_git_auth?
  return false if allow_password_authentication_for_git? || password_based_omniauth_user?

  PersonalAccessTokensFinder.new(user: self, impersonation: false, state: 'active').execute.none?
end

#require_ssh_key?Boolean

rubocop: disable CodeReuse/ServiceClass

Returns:

  • (Boolean)


1243
1244
1245
1246
1247
# File 'app/models/user.rb', line 1243

def require_ssh_key?
  count = Users::KeysCountService.new(self).count

  count == 0 && Gitlab::ProtocolAccess.allowed?('ssh')
end

#required_terms_not_accepted?Boolean

Returns:

  • (Boolean)


2070
2071
2072
2073
# File 'app/models/user.rb', line 2070

def required_terms_not_accepted?
  Gitlab::CurrentSettings.current_application_settings.enforce_terms? &&
    !terms_accepted?
end

#requires_ldap_check?Boolean

Returns:

  • (Boolean)


1448
1449
1450
1451
1452
1453
1454
1455
1456
# File 'app/models/user.rb', line 1448

def requires_ldap_check?
  if !Gitlab.config.ldap.enabled
    false
  elsif ldap_user?
    !last_credential_check_at || (last_credential_check_at + ldap_sync_time) < Time.current
  else
    false
  end
end

#requires_usage_stats_consent?Boolean

Returns:

  • (Boolean)


2075
2076
2077
# File 'app/models/user.rb', line 2075

def requires_usage_stats_consent?
  self.admin? && 7.days.ago > self.created_at && !has_current_license? && User.single_user? && !consented_usage_stats?
end

#reset_backup_codes!Object



1057
1058
1059
# File 'app/models/user.rb', line 1057

def reset_backup_codes!
  update(otp_backup_codes: nil)
end

#review_requested_open_merge_requests_count(force: false) ⇒ Object



1863
1864
1865
1866
1867
# File 'app/models/user.rb', line 1863

def review_requested_open_merge_requests_count(force: false)
  Rails.cache.fetch(['users', id, 'review_requested_open_merge_requests_count'], force: force, expires_in: COUNT_CACHE_VALIDITY_PERIOD) do
    MergeRequestsFinder.new(self, reviewer_id: id, state: 'opened', non_archived: true).execute.count
  end
end

#sanitize_attrsObject



1414
1415
1416
# File 'app/models/user.rb', line 1414

def sanitize_attrs
  sanitize_name
end

#sanitize_nameObject



1418
1419
1420
1421
1422
# File 'app/models/user.rb', line 1418

def sanitize_name
  return unless self.name

  self.name = self.name.gsub(%r{</?[^>]*>}, '')
end

#set_ci_job_token_scope!(job) ⇒ Object



2188
2189
2190
# File 'app/models/user.rb', line 2188

def set_ci_job_token_scope!(job)
  Gitlab::SafeRequestStore[ci_job_token_scope_cache_key] = Ci::JobToken::Scope.new(job.project)
end

#set_projects_limitObject



1439
1440
1441
1442
1443
1444
1445
1446
# File 'app/models/user.rb', line 1439

def set_projects_limit
  # `User.select(:id)` raises
  # `ActiveModel::MissingAttributeError: missing attribute: projects_limit`
  # without this safeguard!
  return unless has_attribute?(:projects_limit) && projects_limit.nil?

  self.projects_limit = Gitlab::CurrentSettings.default_projects_limit
end

#set_username_errorsObject



1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
# File 'app/models/user.rb', line 1603

def set_username_errors
  namespace_path_errors = self.errors.delete(:"namespace.path")

  return unless namespace_path_errors&.any?

  if namespace_path_errors.include?('has already been taken') && !User.exists?(username: username)
    self.errors.add(:base, :username_exists_as_a_different_namespace)
  else
    namespace_path_errors.each do |msg|
      self.errors.add(:username, msg)
    end
  end
end

#several_namespaces?Boolean

rubocop: enable CodeReuse/ServiceClass

Returns:

  • (Boolean)


1337
1338
1339
1340
1341
1342
1343
1344
# File 'app/models/user.rb', line 1337

def several_namespaces?
  union_sql = ::Gitlab::SQL::Union.new(
    [owned_groups,
     maintainers_groups,
     groups_with_developer_maintainer_project_access]).to_sql

  ::Group.from("(#{union_sql}) #{::Group.table_name}").any?
end

#short_website_urlObject



1502
1503
1504
# File 'app/models/user.rb', line 1502

def short_website_url
  website_url.sub(%r{\Ahttps?://}, '')
end

#skip_confirmation=(bool) ⇒ Object



950
951
952
# File 'app/models/user.rb', line 950

def skip_confirmation=(bool)
  skip_confirmation! if bool
end

#skip_reconfirmation=(bool) ⇒ Object



954
955
956
# File 'app/models/user.rb', line 954

def skip_reconfirmation=(bool)
  skip_reconfirmation! if bool
end

#solo_owned_groupsObject



1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
# File 'app/models/user.rb', line 1470

def solo_owned_groups
  # For each owned group, count the owners found in self and ancestors.
  counts = GroupMember
    .from('unnest(namespaces.traversal_ids) AS ancestors(ancestor_id), members')
    .where('members.source_id = ancestors.ancestor_id')
    .all_by_access_level(GroupMember::OWNER)
    .having('count(members.user_id) = 1')

  Group
    .from(owned_groups, :namespaces)
    .where_exists(counts)
end

#source_groups_of_two_factor_authentication_requirementObject



1163
1164
1165
1166
1167
# File 'app/models/user.rb', line 1163

def source_groups_of_two_factor_authentication_requirement
  Gitlab::ObjectHierarchy.new(expanded_groups_requiring_two_factor_authentication)
    .all_objects
    .where(id: groups)
end

#starred?(project) ⇒ Boolean

rubocop: enable CodeReuse/ServiceClass

Returns:

  • (Boolean)


1667
1668
1669
# File 'app/models/user.rb', line 1667

def starred?(project)
  starred_projects.exists?(project.id)
end

#static_object_tokenObject

Each existing user needs to have a ‘static_object_token`. We do this on read since migrating all existing users is not a feasible solution.



1986
1987
1988
# File 'app/models/user.rb', line 1986

def static_object_token
  ensure_static_object_token!
end

#sync_attribute?(attribute) ⇒ Boolean

Returns:

  • (Boolean)


1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
# File 'app/models/user.rb', line 1998

def sync_attribute?(attribute)
  return true if ldap_user? && attribute == :email

  attributes = Gitlab.config.omniauth.sync_profile_attributes

  if attributes.is_a?(Array)
    attributes.include?(attribute.to_s)
  else
    attributes
  end
end

#system_hook_serviceObject

rubocop: disable CodeReuse/ServiceClass



1662
1663
1664
# File 'app/models/user.rb', line 1662

def system_hook_service
  SystemHooksService.new
end

#temp_oauth_email?Boolean

Returns:

  • (Boolean)


1510
1511
1512
# File 'app/models/user.rb', line 1510

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

#terms_accepted?Boolean

Returns:

  • (Boolean)


2064
2065
2066
2067
2068
# File 'app/models/user.rb', line 2064

def terms_accepted?
  return true if project_bot? || service_account? || security_policy_bot?

  accepted_term_id.present?
end

#to_paramObject



942
943
944
# File 'app/models/user.rb', line 942

def to_param
  username
end

#to_reference(_from = nil, target_project: nil, full: nil) ⇒ Object



946
947
948
# File 'app/models/user.rb', line 946

def to_reference(_from = nil, target_project: nil, full: nil)
  "#{self.class.reference_prefix}#{username}"
end

#todos_done_count(force: false) ⇒ Object



1875
1876
1877
1878
1879
# File 'app/models/user.rb', line 1875

def todos_done_count(force: false)
  Rails.cache.fetch(['users', id, 'todos_done_count'], force: force, expires_in: COUNT_CACHE_VALIDITY_PERIOD) do
    TodosFinder.new(self, state: :done).execute.count
  end
end

#todos_pending_count(force: false) ⇒ Object



1881
1882
1883
1884
1885
# File 'app/models/user.rb', line 1881

def todos_pending_count(force: false)
  Rails.cache.fetch(['users', id, 'todos_pending_count'], force: force, expires_in: COUNT_CACHE_VALIDITY_PERIOD) do
    TodosFinder.new(self, state: :pending).execute.count
  end
end

#toggle_star(project) ⇒ Object



1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
# File 'app/models/user.rb', line 1671

def toggle_star(project)
  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
  end
end

#try_obtain_ldap_leaseObject



1463
1464
1465
1466
1467
1468
# File 'app/models/user.rb', line 1463

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

#two_factor_enabled?Boolean

Returns:

  • (Boolean)


1061
1062
1063
# File 'app/models/user.rb', line 1061

def two_factor_enabled?
  two_factor_otp_enabled? || two_factor_webauthn_enabled?
end

#two_factor_otp_enabled?Boolean

Returns:

  • (Boolean)


1065
1066
1067
1068
1069
1070
# File 'app/models/user.rb', line 1065

def two_factor_otp_enabled?
  otp_required_for_login? ||
  forti_authenticator_enabled?(self) ||
  forti_token_cloud_enabled?(self) ||
  duo_auth_enabled?(self)
end

#two_factor_webauthn_enabled?Boolean

Returns:

  • (Boolean)


1072
1073
1074
# File 'app/models/user.rb', line 1072

def two_factor_webauthn_enabled?
  (webauthn_registrations.loaded? && webauthn_registrations.any?) || (!webauthn_registrations.loaded? && webauthn_registrations.exists?)
end

#unfollow(user) ⇒ Object



1704
1705
1706
1707
1708
1709
1710
# File 'app/models/user.rb', line 1704

def unfollow(user)
  if Users::UserFollowUser.where(follower_id: self.id, followee_id: user.id).delete_all > 0
    self.followees.reset
  else
    false
  end
end

#unique_emailObject



1104
1105
1106
1107
1108
1109
1110
# File 'app/models/user.rb', line 1104

def unique_email
  return if errors.added?(:email, _('has already been taken'))

  if !emails.exists?(email: email) && Email.exists?(email: email)
    errors.add(:email, _('has already been taken'))
  end
end

#unlock_access!(unlocked_by: self) ⇒ Object

override, from Devise



2022
2023
2024
2025
2026
# File 'app/models/user.rb', line 2022

def unlock_access!(unlocked_by: self)
  audit_unlock_access(author: unlocked_by)

  super()
end

#unset_secondary_emails_matching_deleted_email!(deleted_email) ⇒ Object



1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
# File 'app/models/user.rb', line 1424

def unset_secondary_emails_matching_deleted_email!(deleted_email)
  secondary_email_attribute_changed = false
  SECONDARY_EMAIL_ATTRIBUTES.each do |attribute|
    if read_attribute(attribute) == deleted_email
      self.write_attribute(attribute, nil)
      secondary_email_attribute_changed = true
    end
  end
  save if secondary_email_attribute_changed
end

#update_invalid_gpg_signaturesObject



1135
1136
1137
# File 'app/models/user.rb', line 1135

def update_invalid_gpg_signatures
  gpg_keys.each(&:update_invalid_gpg_signatures)
end

#update_otp_secret!Object



1086
1087
1088
1089
# File 'app/models/user.rb', line 1086

def update_otp_secret!
  self.otp_secret = User.generate_otp_secret(OTP_SECRET_LENGTH)
  self.otp_secret_expires_at = Time.current + OTP_SECRET_TTL
end

#update_todos_count_cacheObject



1893
1894
1895
1896
# File 'app/models/user.rb', line 1893

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

#update_tracked_fields!(request) ⇒ Object

Override Devise::Models::Trackable#update_tracked_fields! to limit database writes to at most once every hour rubocop: disable CodeReuse/ServiceClass



134
135
136
137
138
139
140
141
142
143
144
# File 'app/models/user.rb', line 134

def update_tracked_fields!(request)
  return if Gitlab::Database.read_only?

  update_tracked_fields(request)

  Gitlab::ExclusiveLease.throttle(id) do
    ::Ability.forgetting(/admin/) do
      Users::UpdateService.new(self, user: self).execute(validate: false)
    end
  end
end

#update_two_factor_requirementObject



1967
1968
1969
1970
1971
1972
1973
1974
# File 'app/models/user.rb', line 1967

def update_two_factor_requirement
  periods = expanded_groups_requiring_two_factor_authentication.pluck(:two_factor_grace_period)

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

  save
end

#user_detailObject



2084
2085
2086
# File 'app/models/user.rb', line 2084

def user_detail
  super.presence || build_user_detail
end

#user_preferenceObject

Avoid migrations only building user preference object when needed.



2080
2081
2082
# File 'app/models/user.rb', line 2080

def user_preference
  super.presence || build_user_preference
end

#user_projectObject



2196
2197
2198
2199
2200
# File 'app/models/user.rb', line 2196

def user_project
  strong_memoize(:user_project) do
    personal_projects.find_by(path: username, visibility_level: Gitlab::VisibilityLevel::PUBLIC)
  end
end

#user_readmeObject



2202
2203
2204
2205
2206
# File 'app/models/user.rb', line 2202

def user_readme
  strong_memoize(:user_readme) do
    user_project&.repository&.readme
  end
end

#username_changed_hookObject



1617
1618
1619
# File 'app/models/user.rb', line 1617

def username_changed_hook
  system_hook_service.execute_hooks_for(self, :rename)
end

#valid_password?(password) ⇒ Boolean

Overwrites valid_password? from Devise::Models::DatabaseAuthenticatable In constant-time, check both that the password isn’t on a denylist AND that the password is the user’s password

Returns:

  • (Boolean)


974
975
976
977
978
979
# File 'app/models/user.rb', line 974

def valid_password?(password)
  return false unless password_allowed?(password)
  return false if password_automatically_set?

  super
end

#verified_email?(check_email) ⇒ Boolean

Returns:

  • (Boolean)


1570
1571
1572
1573
1574
1575
1576
1577
1578
# File 'app/models/user.rb', line 1570

def verified_email?(check_email)
  downcased = check_email.downcase

  # handle the outdated private commit email case
  return true if persisted? &&
      id == Gitlab::PrivateCommitEmail.user_id_for_email(downcased)

  verified_emails.include?(check_email.downcase)
end

#verified_emails(include_private_email: true) ⇒ Object



1544
1545
1546
1547
1548
1549
1550
# File 'app/models/user.rb', line 1544

def verified_emails(include_private_email: true)
  verified_emails = []
  verified_emails << email if primary_email_verified?
  verified_emails << private_commit_email if include_private_email
  verified_emails.concat(emails.confirmed.pluck(:email))
  verified_emails.uniq
end

#webhook_emailObject



2212
2213
2214
# File 'app/models/user.rb', line 2212

def webhook_email
  public_email.presence || _('[REDACTED]')
end

#will_save_change_to_login?Boolean

will_save_change_to_attribute? is used by Devise to check if it is necessary to clear any existing reset_password_tokens before updating an authentication_key and login in our case is a virtual attribute to allow login by username or email.

Returns:

  • (Boolean)


1100
1101
1102
# File 'app/models/user.rb', line 1100

def will_save_change_to_login?
  will_save_change_to_username? || will_save_change_to_email?
end

#with_defaultsObject



1483
1484
1485
1486
1487
1488
1489
# File 'app/models/user.rb', line 1483

def with_defaults
  User.defaults.each do |k, v|
    public_send("#{k}=", v) # rubocop:disable GitlabSecurity/PublicSend
  end

  self
end