user.rb 15.1 KB
Newer Older
D
Dmitriy Zaporozhets 已提交
1 2 3 4
# == Schema Information
#
# Table name: users
#
D
Dmitriy Zaporozhets 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
#  id                       :integer          not null, primary key
#  email                    :string(255)      default(""), not null
#  encrypted_password       :string(255)      default(""), not null
#  reset_password_token     :string(255)
#  reset_password_sent_at   :datetime
#  remember_created_at      :datetime
#  sign_in_count            :integer          default(0)
#  current_sign_in_at       :datetime
#  last_sign_in_at          :datetime
#  current_sign_in_ip       :string(255)
#  last_sign_in_ip          :string(255)
#  created_at               :datetime
#  updated_at               :datetime
#  name                     :string(255)
#  admin                    :boolean          default(FALSE), not null
#  projects_limit           :integer          default(10)
#  skype                    :string(255)      default(""), not null
#  linkedin                 :string(255)      default(""), not null
#  twitter                  :string(255)      default(""), not null
#  authentication_token     :string(255)
#  theme_id                 :integer          default(1), not null
#  bio                      :string(255)
#  failed_attempts          :integer          default(0)
#  locked_at                :datetime
#  extern_uid               :string(255)
#  provider                 :string(255)
#  username                 :string(255)
#  can_create_group         :boolean          default(TRUE), not null
#  can_create_team          :boolean          default(TRUE), not null
#  state                    :string(255)
#  color_scheme_id          :integer          default(1), not null
#  notification_level       :integer          default(1), not null
#  password_expires_at      :datetime
#  created_by_id            :integer
#  last_credential_check_at :datetime
#  avatar                   :string(255)
#  confirmation_token       :string(255)
#  confirmed_at             :datetime
#  confirmation_sent_at     :datetime
#  unconfirmed_email        :string(255)
#  hide_no_ssh_key          :boolean          default(FALSE)
#  website_url              :string(255)      default(""), not null
D
Dmitriy Zaporozhets 已提交
47 48
#

S
Steven Thonus 已提交
49 50 51
require 'carrierwave/orm/activerecord'
require 'file_size_validator'

G
gitlabhq 已提交
52
class User < ActiveRecord::Base
53 54
  include Gitlab::ConfigHelper
  extend Gitlab::ConfigHelper
55
  include TokenAuthenticatable
56

57
  default_value_for :admin, false
58
  default_value_for :can_create_group, gitlab_config.default_can_create_group
59 60
  default_value_for :can_create_team, false
  default_value_for :hide_no_ssh_key, false
61 62
  default_value_for :projects_limit, gitlab_config.default_projects_limit
  default_value_for :theme_id, gitlab_config.default_theme
63

64
  devise :database_authenticatable, :lockable, :async,
65
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :confirmable, :registerable
G
gitlabhq 已提交
66

67
  attr_accessor :force_random_password
G
gitlabhq 已提交
68

69 70 71
  # Virtual attribute for authenticating by either username or email
  attr_accessor :login

72 73 74 75
  #
  # Relations
  #

76
  # Namespace for personal projects
77
  has_one :namespace, -> { where type: nil }, dependent: :destroy, foreign_key: :owner_id, class_name: "Namespace"
78 79 80

  # Profile
  has_many :keys, dependent: :destroy
81
  has_many :emails, dependent: :destroy
82 83

  # Groups
84 85
  has_many :users_groups, dependent: :destroy
  has_many :groups, through: :users_groups
86
  has_many :owned_groups, -> { where users_groups: { group_access: UsersGroup::OWNER } }, through: :users_groups, source: :group
87 88
  has_many :masters_groups, -> { where users_groups: { group_access: UsersGroup::MASTER } }, through: :users_groups, source: :group

89
  # Projects
90 91 92 93 94
  has_many :groups_projects,          through: :groups, source: :projects
  has_many :personal_projects,        through: :namespace, source: :projects
  has_many :projects,                 through: :users_projects
  has_many :created_projects,         foreign_key: :creator_id, class_name: 'Project'

95
  has_many :snippets,                 dependent: :destroy, foreign_key: :author_id, class_name: "Snippet"
96 97 98 99 100
  has_many :users_projects,           dependent: :destroy
  has_many :issues,                   dependent: :destroy, foreign_key: :author_id
  has_many :notes,                    dependent: :destroy, foreign_key: :author_id
  has_many :merge_requests,           dependent: :destroy, foreign_key: :author_id
  has_many :events,                   dependent: :destroy, foreign_key: :author_id,   class_name: "Event"
101
  has_many :recent_events, -> { order "id DESC" }, foreign_key: :author_id,   class_name: "Event"
102 103 104
  has_many :assigned_issues,          dependent: :destroy, foreign_key: :assignee_id, class_name: "Issue"
  has_many :assigned_merge_requests,  dependent: :destroy, foreign_key: :assignee_id, class_name: "MergeRequest"

105

106 107 108
  #
  # Validations
  #
C
Cyril 已提交
109
  validates :name, presence: true
110
  validates :email, presence: true, email: {strict_mode: true}, uniqueness: true
111
  validates :bio, length: { maximum: 255 }, allow_blank: true
112
  validates :extern_uid, allow_blank: true, uniqueness: {scope: :provider}
N
Nihad Abbasov 已提交
113
  validates :projects_limit, presence: true, numericality: {greater_than_or_equal_to: 0}
114
  validates :username, presence: true, uniqueness: { case_sensitive: false },
D
Dmitriy Zaporozhets 已提交
115
            exclusion: { in: Gitlab::Blacklist.path },
116
            format: { with: Gitlab::Regex.username_regex,
117
                      message: Gitlab::Regex.username_regex_message }
118

A
Andrey Kumanyaev 已提交
119
  validates :notification_level, inclusion: { in: Notification.notification_levels }, presence: true
120
  validate :namespace_uniq, if: ->(user) { user.username_changed? }
121
  validate :avatar_type, if: ->(user) { user.avatar_changed? }
122
  validate :unique_email, if: ->(user) { user.email_changed? }
S
Steven Thonus 已提交
123
  validates :avatar, file_size: { maximum: 100.kilobytes.to_i }
124

125
  before_validation :generate_password, on: :create
126 127
  before_validation :sanitize_attrs

N
Nihad Abbasov 已提交
128
  before_save :ensure_authentication_token
D
Dmitriy Zaporozhets 已提交
129 130 131 132
  after_save :ensure_namespace_correct
  after_create :post_create_hook
  after_destroy :post_destroy_hook

133

N
Nihad Abbasov 已提交
134
  alias_attribute :private_token, :authentication_token
135

136
  delegate :path, to: :namespace, allow_nil: true, prefix: true
137

138 139 140 141
  state_machine :state, initial: :active do
    after_transition any => :blocked do |user, transition|
      # Remove user from all projects and
      user.users_projects.find_each do |membership|
D
Dmitriy Zaporozhets 已提交
142 143 144 145 146 147 148 149 150
        # skip owned resources
        next if membership.project.owner == user

        return false unless membership.destroy
      end

      # Remove user from all groups
      user.users_groups.find_each do |membership|
        # skip owned resources
151
        next if membership.group.last_owner?(user)
D
Dmitriy Zaporozhets 已提交
152

153 154 155 156 157 158 159 160 161 162 163 164 165
        return false unless membership.destroy
      end
    end

    event :block do
      transition active: :blocked
    end

    event :activate do
      transition blocked: :active
    end
  end

S
Steven Thonus 已提交
166 167
  mount_uploader :avatar, AttachmentUploader

A
Andrey Kumanyaev 已提交
168
  # Scopes
A
Andrew8xx8 已提交
169
  scope :admins, -> { where(admin:  true) }
170 171
  scope :blocked, -> { with_state(:blocked) }
  scope :active, -> { with_state(:active) }
A
Andrew8xx8 已提交
172
  scope :alphabetically, -> { order('name ASC') }
173 174
  scope :in_team, ->(team){ where(id: team.member_ids) }
  scope :not_in_team, ->(team){ where('users.id NOT IN (:ids)', ids: team.member_ids) }
S
skv 已提交
175
  scope :not_in_project, ->(project) { project.users.present? ? where("id not in (:ids)", ids: project.users.map(&:id) ) : all }
A
Andrey Kumanyaev 已提交
176
  scope :without_projects, -> { where('id NOT IN (SELECT DISTINCT(user_id) FROM users_projects)') }
177
  scope :ldap, -> { where(provider:  'ldap') }
A
Andrey Kumanyaev 已提交
178

179
  scope :potential_team_members, ->(team) { team.members.any? ? active.not_in_team(team) : active  }
A
Andrey Kumanyaev 已提交
180

181 182 183
  #
  # Class methods
  #
A
Andrey Kumanyaev 已提交
184
  class << self
185
    # Devise method overridden to allow sign in with email or username
186 187 188 189 190 191 192 193
    def find_for_database_authentication(warden_conditions)
      conditions = warden_conditions.dup
      if login = conditions.delete(:login)
        where(conditions).where(["lower(username) = :value OR lower(email) = :value", { value: login.downcase }]).first
      else
        where(conditions).first
      end
    end
194

195 196 197 198 199 200
    def find_for_commit(email, name)
      # Prefer email match over name match
      User.where(email: email).first ||
        User.joins(:emails).where(emails: { email: email }).first ||
        User.where(name: name).first
    end
201

A
Andrey Kumanyaev 已提交
202 203 204 205 206 207 208 209
    def filter filter_name
      case filter_name
      when "admins"; self.admins
      when "blocked"; self.blocked
      when "wop"; self.without_projects
      else
        self.active
      end
210 211
    end

A
Andrey Kumanyaev 已提交
212
    def search query
213
      where("lower(name) LIKE :query OR lower(email) LIKE :query OR lower(username) LIKE :query", query: "%#{query.downcase}%")
A
Andrey Kumanyaev 已提交
214
    end
215 216

    def by_username_or_id(name_or_id)
217
      where('users.username = ? OR users.id = ?', name_or_id.to_s, name_or_id.to_i).first
218
    end
219

220 221
    def build_user(attrs = {})
      User.new(attrs)
222
    end
V
vsizov 已提交
223
  end
R
randx 已提交
224

225 226 227
  #
  # Instance methods
  #
228 229 230 231 232

  def to_param
    username
  end

D
Dmitriy Zaporozhets 已提交
233 234 235 236
  def notification
    @notification ||= Notification.new(self)
  end

A
Andrey Kumanyaev 已提交
237 238 239 240
  def generate_password
    if self.force_random_password
      self.password = self.password_confirmation = Devise.friendly_token.first(8)
    end
R
randx 已提交
241
  end
242

243 244
  def namespace_uniq
    namespace_name = self.username
S
skv 已提交
245
    if Namespace.find_by(path: namespace_name)
L
lol768 已提交
246
      self.errors.add :username, "already exists"
247 248
    end
  end
249

250 251 252 253 254 255
  def avatar_type
    unless self.avatar.image?
      self.errors.add :avatar, "only images allowed"
    end
  end

256 257 258 259
  def unique_email
    self.errors.add(:email, 'has already been taken') if Email.exists?(email: self.email)
  end

260 261
  # Groups user has access to
  def authorized_groups
262
    @authorized_groups ||= begin
263
                             group_ids = (groups.pluck(:id) + authorized_projects.pluck(:namespace_id))
264
                             Group.where(id: group_ids).order('namespaces.name ASC')
265
                           end
266 267 268 269 270
  end


  # Projects user has access to
  def authorized_projects
271
    @authorized_projects ||= begin
272 273 274
                               project_ids = personal_projects.pluck(:id)
                               project_ids += groups_projects.pluck(:id)
                               project_ids += projects.pluck(:id).uniq
275
                               Project.where(id: project_ids).joins(:namespace).order('namespaces.name ASC')
276
                             end
277 278
  end

279 280 281 282 283 284
  def owned_projects
    @owned_projects ||= begin
                          Project.where(namespace_id: owned_groups.pluck(:id).push(namespace.id)).joins(:namespace)
                        end
  end

285 286
  # Team membership in authorized projects
  def tm_in_authorized_projects
A
Andrey Kumanyaev 已提交
287
    UsersProject.where(project_id: authorized_projects.map(&:id), user_id: self.id)
288
  end
D
Dmitriy Zaporozhets 已提交
289 290 291 292 293 294 295 296 297

  def is_admin?
    admin
  end

  def require_ssh_key?
    keys.count == 0
  end

298
  def can_change_username?
299
    gitlab_config.username_changing_enabled
300 301
  end

D
Dmitriy Zaporozhets 已提交
302
  def can_create_project?
303
    projects_limit_left > 0
D
Dmitriy Zaporozhets 已提交
304 305 306
  end

  def can_create_group?
307
    can?(:create_group, nil)
D
Dmitriy Zaporozhets 已提交
308 309 310 311 312 313 314 315 316 317
  end

  def abilities
    @abilities ||= begin
                     abilities = Six.new
                     abilities << Ability
                     abilities
                   end
  end

318 319 320 321
  def can_select_namespace?
    several_namespaces? || admin
  end

D
Dmitriy Zaporozhets 已提交
322 323 324 325 326 327 328 329 330
  def can? action, subject
    abilities.allowed?(self, action, subject)
  end

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

  def cared_merge_requests
331
    MergeRequest.cared(self)
D
Dmitriy Zaporozhets 已提交
332 333
  end

334
  def projects_limit_left
335
    projects_limit - personal_projects.count
336 337
  end

D
Dmitriy Zaporozhets 已提交
338 339
  def projects_limit_percent
    return 100 if projects_limit.zero?
340
    (personal_projects.count.to_f / projects_limit) * 100
D
Dmitriy Zaporozhets 已提交
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
  end

  def recent_push project_id = nil
    # Get push events not earlier than 2 hours ago
    events = recent_events.code_push.where("created_at > ?", Time.now - 2.hours)
    events = events.where(project_id: project_id) if project_id

    # Take only latest one
    events = events.recent.limit(1).first
  end

  def projects_sorted_by_activity
    authorized_projects.sorted_by_activity
  end

  def several_namespaces?
357
    owned_groups.any? || masters_groups.any?
D
Dmitriy Zaporozhets 已提交
358 359 360 361 362
  end

  def namespace_id
    namespace.try :id
  end
363

364 365 366
  def name_with_username
    "#{name} (#{username})"
  end
D
Dmitriy Zaporozhets 已提交
367 368 369 370

  def tm_of(project)
    project.team_member_by_id(self.id)
  end
371 372 373 374 375 376 377 378 379 380 381 382 383 384

  def already_forked? project
    !!fork_of(project)
  end

  def fork_of project
    links = ForkedProjectLink.where(forked_from_project_id: project, forked_to_project_id: personal_projects)

    if links.any?
      links.first.forked_to_project
    else
      nil
    end
  end
385 386 387 388

  def ldap_user?
    extern_uid && provider == 'ldap'
  end
389

390
  def accessible_deploy_keys
391
    DeployKey.in_projects(self.authorized_projects.pluck(:id)).uniq
392
  end
393 394

  def created_by
S
skv 已提交
395
    User.find_by(id: created_by_id) if created_by_id
396
  end
397 398 399 400 401 402 403

  def sanitize_attrs
    %w(name username skype linkedin twitter bio).each do |attr|
      value = self.send(attr)
      self.send("#{attr}=", Sanitize.clean(value)) if value.present?
    end
  end
404

405 406 407 408 409 410 411 412
  def requires_ldap_check?
    if ldap_user?
      !last_credential_check_at || (last_credential_check_at + 1.hour) < Time.now
    else
      false
    end
  end

413 414 415 416 417
  def solo_owned_groups
    @solo_owned_groups ||= owned_groups.select do |group|
      group.owners == [self]
    end
  end
418 419

  def with_defaults
420 421
    User.defaults.each do |k, v|
      self.send("#{k}=", v)
422
    end
423 424

    self
425
  end
426

427 428 429 430
  def can_leave_project?(project)
    project.namespace != namespace &&
      project.project_member(self)
  end
431 432 433 434 435 436 437 438 439 440 441 442 443 444

  # Reset project events cache related to this user
  #
  # Since we do cache @event we need to reset cache in special cases:
  # * when the user changes their avatar
  # Events cache stored like  events/23-20130109142513.
  # The cache key includes updated_at timestamp.
  # Thus it will automatically generate a new fragment
  # when the event is updated because the key changes.
  def reset_events_cache
    Event.where(author_id: self.id).
      order('id DESC').limit(1000).
      update_all(updated_at: Time.now)
  end
J
Jerome Dalbert 已提交
445 446 447 448 449 450 451 452 453 454

  def full_website_url
    return "http://#{website_url}" if website_url !~ /^https?:\/\//

    website_url
  end

  def short_website_url
    website_url.gsub(/https?:\/\//, '')
  end
G
GitLab 已提交
455

456
  def all_ssh_keys
G
GitLab 已提交
457
    keys.map(&:key)
458
  end
459 460 461 462 463 464

  def temp_oauth_email?
    email =~ /\Atemp-email-for-oauth/
  end

  def generate_tmp_oauth_email
465
    self.email = "temp-email-for-oauth-#{username}@gitlab.localhost"
466
  end
D
Dmitriy Zaporozhets 已提交
467 468 469 470

  def public_profile?
    authorized_projects.public_only.any?
  end
471 472 473

  def avatar_url(size = nil)
    if avatar.present?
D
Drew Blessing 已提交
474
      [gitlab_config.url, avatar.url].join("/")
475
    else
476
      GravatarService.new.execute(email, size)
477 478
    end
  end
D
Dmitriy Zaporozhets 已提交
479 480 481 482 483 484 485 486 487 488 489 490

  def ensure_namespace_correct
    # Ensure user has namespace
    self.create_namespace!(path: self.username, name: self.username) unless self.namespace

    if self.username_changed?
      self.namespace.update_attributes(path: self.username, name: self.username)
    end
  end

  def post_create_hook
    log_info("User \"#{self.name}\" (#{self.email}) was created")
D
Dmitriy Zaporozhets 已提交
491
    notification_service.new_user(self)
D
Dmitriy Zaporozhets 已提交
492 493 494 495 496 497 498 499
    system_hook_service.execute_hooks_for(self, :create)
  end

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

D
Dmitriy Zaporozhets 已提交
500
  def notification_service
D
Dmitriy Zaporozhets 已提交
501 502 503 504 505 506 507 508 509 510
    NotificationService.new
  end

  def log_info message
    Gitlab::AppLogger.info message
  end

  def system_hook_service
    SystemHooksService.new
  end
G
gitlabhq 已提交
511
end