annotate app/models/user.rb @ 1519:afce8026aaeb redmine-2.4-integration

Merge from branch "live"
author Chris Cannam
date Tue, 09 Sep 2014 09:34:53 +0100
parents c86dacc2ef0a
children a1bdbf8a87d5
rev   line source
Chris@0 1 # Redmine - project management software
Chris@1494 2 # Copyright (C) 2006-2014 Jean-Philippe Lang
Chris@0 3 #
Chris@0 4 # This program is free software; you can redistribute it and/or
Chris@0 5 # modify it under the terms of the GNU General Public License
Chris@0 6 # as published by the Free Software Foundation; either version 2
Chris@0 7 # of the License, or (at your option) any later version.
Chris@909 8 #
Chris@0 9 # This program is distributed in the hope that it will be useful,
Chris@0 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@0 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@0 12 # GNU General Public License for more details.
Chris@909 13 #
Chris@0 14 # You should have received a copy of the GNU General Public License
Chris@0 15 # along with this program; if not, write to the Free Software
Chris@0 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@0 17
Chris@0 18 require "digest/sha1"
Chris@0 19
Chris@0 20 class User < Principal
Chris@119 21 include Redmine::SafeAttributes
Chris@909 22
Chris@909 23 # Different ways of displaying/sorting users
Chris@0 24 USER_FORMATS = {
Chris@1115 25 :firstname_lastname => {
Chris@1115 26 :string => '#{firstname} #{lastname}',
Chris@1115 27 :order => %w(firstname lastname id),
Chris@1115 28 :setting_order => 1
Chris@1115 29 },
Chris@1115 30 :firstname_lastinitial => {
Chris@1115 31 :string => '#{firstname} #{lastname.to_s.chars.first}.',
Chris@1115 32 :order => %w(firstname lastname id),
Chris@1115 33 :setting_order => 2
Chris@1115 34 },
Chris@1115 35 :firstname => {
Chris@1115 36 :string => '#{firstname}',
Chris@1115 37 :order => %w(firstname id),
Chris@1115 38 :setting_order => 3
Chris@1115 39 },
Chris@1115 40 :lastname_firstname => {
Chris@1115 41 :string => '#{lastname} #{firstname}',
Chris@1115 42 :order => %w(lastname firstname id),
Chris@1115 43 :setting_order => 4
Chris@1115 44 },
Chris@1115 45 :lastname_coma_firstname => {
Chris@1115 46 :string => '#{lastname}, #{firstname}',
Chris@1115 47 :order => %w(lastname firstname id),
Chris@1115 48 :setting_order => 5
Chris@1115 49 },
Chris@1115 50 :lastname => {
Chris@1115 51 :string => '#{lastname}',
Chris@1115 52 :order => %w(lastname id),
Chris@1115 53 :setting_order => 6
Chris@1115 54 },
Chris@1115 55 :username => {
Chris@1115 56 :string => '#{login}',
Chris@1115 57 :order => %w(login id),
Chris@1115 58 :setting_order => 7
Chris@1115 59 },
Chris@0 60 }
Chris@0 61
chris@37 62 MAIL_NOTIFICATION_OPTIONS = [
Chris@119 63 ['all', :label_user_mail_option_all],
Chris@119 64 ['selected', :label_user_mail_option_selected],
Chris@119 65 ['only_my_events', :label_user_mail_option_only_my_events],
Chris@119 66 ['only_assigned', :label_user_mail_option_only_assigned],
Chris@119 67 ['only_owner', :label_user_mail_option_only_owner],
Chris@119 68 ['none', :label_user_mail_option_none]
Chris@119 69 ]
chris@37 70
Chris@0 71 has_and_belongs_to_many :groups, :after_add => Proc.new {|user, group| group.user_added(user)},
Chris@0 72 :after_remove => Proc.new {|user, group| group.user_removed(user)}
Chris@0 73 has_many :changesets, :dependent => :nullify
Chris@0 74 has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
Chris@128 75 has_one :rss_token, :class_name => 'Token', :conditions => "action='feeds'"
Chris@128 76 has_one :api_token, :class_name => 'Token', :conditions => "action='api'"
Chris@0 77 belongs_to :auth_source
Chris@909 78
Chris@1464 79 scope :logged, lambda { where("#{User.table_name}.status <> #{STATUS_ANONYMOUS}") }
Chris@1464 80 scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) }
Chris@909 81
luisf@55 82 has_one :ssamr_user_detail, :dependent => :destroy, :class_name => 'SsamrUserDetail'
luisf@65 83 accepts_nested_attributes_for :ssamr_user_detail
luis@403 84
luis@403 85 has_one :author
luisf@64 86
Chris@0 87 acts_as_customizable
Chris@909 88
Chris@1464 89 attr_accessor :password, :password_confirmation, :generate_password
Chris@0 90 attr_accessor :last_before_login_on
Chris@0 91 # Prevents unauthorized assignments
Chris@119 92 attr_protected :login, :admin, :password, :password_confirmation, :hashed_password
Chris@1115 93
Chris@1115 94 LOGIN_LENGTH_LIMIT = 60
Chris@1115 95 MAIL_LENGTH_LIMIT = 60
Chris@1115 96
Chris@0 97 validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
Chris@1115 98 validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false
Chris@1115 99 validates_uniqueness_of :mail, :if => Proc.new { |user| user.mail_changed? && user.mail.present? }, :case_sensitive => false
Chris@1484 100
Chris@1464 101 # Login must contain letters, numbers, underscores only
Chris@1464 102 validates_format_of :login, :with => /\A[a-z0-9_\-@\.]*\z/i
Chris@1115 103 validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT
Chris@0 104 validates_length_of :firstname, :lastname, :maximum => 30
Chris@1464 105 validates_format_of :mail, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :allow_blank => true
Chris@1115 106 validates_length_of :mail, :maximum => MAIL_LENGTH_LIMIT, :allow_nil => true
Chris@0 107 validates_confirmation_of :password, :allow_nil => true
Chris@119 108 validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
Chris@909 109 validate :validate_password_length
Chris@0 110
Chris@909 111 before_create :set_mail_notification
Chris@1464 112 before_save :generate_password_if_needed, :update_hashed_password
Chris@128 113 before_destroy :remove_references_before_destroy
Chris@1464 114 after_save :update_notified_project_ids
Chris@909 115
luisf@190 116 validates_acceptance_of :terms_and_conditions, :on => :create, :message => :must_accept_terms_and_conditions
luisf@190 117
Chris@1115 118 scope :in_group, lambda {|group|
Chris@441 119 group_id = group.is_a?(Group) ? group.id : group.to_i
Chris@1115 120 where("#{User.table_name}.id IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id)
Chris@441 121 }
Chris@1115 122 scope :not_in_group, lambda {|group|
Chris@441 123 group_id = group.is_a?(Group) ? group.id : group.to_i
Chris@1115 124 where("#{User.table_name}.id NOT IN (SELECT gu.user_id FROM #{table_name_prefix}groups_users#{table_name_suffix} gu WHERE gu.group_id = ?)", group_id)
Chris@441 125 }
Chris@1464 126 scope :sorted, lambda { order(*User.fields_for_order_statement)}
Chris@909 127
Chris@909 128 def set_mail_notification
chris@37 129 self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
Chris@0 130 true
Chris@0 131 end
Chris@909 132
Chris@909 133 def update_hashed_password
Chris@0 134 # update hashed_password if password was set
Chris@245 135 if self.password && self.auth_source_id.blank?
Chris@245 136 salt_password(password)
Chris@245 137 end
Chris@0 138 end
Chris@909 139
Chris@1464 140 alias :base_reload :reload
Chris@0 141 def reload(*args)
Chris@0 142 @name = nil
Chris@441 143 @projects_by_role = nil
Chris@1464 144 @membership_by_project_id = nil
Chris@1464 145 @notified_projects_ids = nil
Chris@1464 146 @notified_projects_ids_changed = false
Chris@1464 147 @builtin_role = nil
Chris@1464 148 base_reload(*args)
Chris@0 149 end
Chris@909 150
Chris@1 151 def mail=(arg)
Chris@1 152 write_attribute(:mail, arg.to_s.strip)
Chris@1 153 end
Chris@909 154
luisf@59 155 def description=(arg)
luisf@59 156 write_attribute(:description, arg.to_s.strip)
luisf@59 157 end
luisf@59 158
Chris@0 159 def identity_url=(url)
Chris@0 160 if url.blank?
Chris@0 161 write_attribute(:identity_url, '')
Chris@0 162 else
Chris@0 163 begin
Chris@0 164 write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
Chris@0 165 rescue OpenIdAuthentication::InvalidOpenId
Chris@1464 166 # Invalid url, don't save
Chris@0 167 end
Chris@0 168 end
Chris@0 169 self.read_attribute(:identity_url)
Chris@0 170 end
Chris@909 171
Chris@0 172 # Returns the user that matches provided login and password, or nil
Chris@1464 173 def self.try_to_login(login, password, active_only=true)
Chris@1115 174 login = login.to_s
Chris@1115 175 password = password.to_s
Chris@1115 176
Chris@1464 177 # Make sure no one can sign in with an empty login or password
Chris@1464 178 return nil if login.empty? || password.empty?
Chris@0 179 user = find_by_login(login)
Chris@0 180 if user
Chris@0 181 # user is already in local database
Chris@1464 182 return nil unless user.check_password?(password)
Chris@1464 183 return nil if !user.active? && active_only
Chris@0 184 else
Chris@0 185 # user is not yet registered, try to authenticate with available sources
Chris@0 186 attrs = AuthSource.authenticate(login, password)
Chris@0 187 if attrs
Chris@0 188 user = new(attrs)
Chris@0 189 user.login = login
Chris@0 190 user.language = Setting.default_language
Chris@0 191 if user.save
Chris@0 192 user.reload
Chris@0 193 logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
Chris@0 194 end
Chris@0 195 end
Chris@909 196 end
Chris@1464 197 user.update_column(:last_login_on, Time.now) if user && !user.new_record? && user.active?
Chris@0 198 user
Chris@0 199 rescue => text
Chris@0 200 raise text
Chris@0 201 end
Chris@909 202
Chris@0 203 # Returns the user who matches the given autologin +key+ or nil
Chris@0 204 def self.try_to_autologin(key)
Chris@1464 205 user = Token.find_active_user('autologin', key, Setting.autologin.to_i)
Chris@1464 206 if user
Chris@1464 207 user.update_column(:last_login_on, Time.now)
Chris@1464 208 user
Chris@0 209 end
Chris@0 210 end
Chris@909 211
Chris@909 212 def self.name_formatter(formatter = nil)
Chris@909 213 USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
Chris@909 214 end
Chris@909 215
Chris@909 216 # Returns an array of fields names than can be used to make an order statement for users
Chris@909 217 # according to how user names are displayed
Chris@909 218 # Examples:
Chris@909 219 #
Chris@909 220 # User.fields_for_order_statement => ['users.login', 'users.id']
Chris@909 221 # User.fields_for_order_statement('authors') => ['authors.login', 'authors.id']
Chris@909 222 def self.fields_for_order_statement(table=nil)
Chris@909 223 table ||= table_name
Chris@909 224 name_formatter[:order].map {|field| "#{table}.#{field}"}
Chris@909 225 end
Chris@909 226
Chris@0 227 # Return user's full name for display
Chris@0 228 def name(formatter = nil)
Chris@909 229 f = self.class.name_formatter(formatter)
Chris@0 230 if formatter
Chris@909 231 eval('"' + f[:string] + '"')
Chris@0 232 else
Chris@909 233 @name ||= eval('"' + f[:string] + '"')
Chris@0 234 end
Chris@0 235 end
Chris@909 236
Chris@0 237 def active?
Chris@0 238 self.status == STATUS_ACTIVE
Chris@0 239 end
Chris@0 240
Chris@0 241 def registered?
Chris@0 242 self.status == STATUS_REGISTERED
Chris@0 243 end
Chris@909 244
Chris@0 245 def locked?
Chris@0 246 self.status == STATUS_LOCKED
Chris@0 247 end
Chris@0 248
Chris@14 249 def activate
Chris@14 250 self.status = STATUS_ACTIVE
Chris@14 251 end
Chris@14 252
Chris@14 253 def register
Chris@14 254 self.status = STATUS_REGISTERED
Chris@14 255 end
Chris@14 256
Chris@14 257 def lock
Chris@14 258 self.status = STATUS_LOCKED
Chris@14 259 end
Chris@14 260
Chris@14 261 def activate!
Chris@14 262 update_attribute(:status, STATUS_ACTIVE)
Chris@14 263 end
Chris@14 264
Chris@14 265 def register!
Chris@14 266 update_attribute(:status, STATUS_REGISTERED)
Chris@14 267 end
Chris@14 268
Chris@14 269 def lock!
Chris@14 270 update_attribute(:status, STATUS_LOCKED)
Chris@14 271 end
Chris@14 272
Chris@245 273 # Returns true if +clear_password+ is the correct user's password, otherwise false
Chris@0 274 def check_password?(clear_password)
Chris@0 275 if auth_source_id.present?
Chris@0 276 auth_source.authenticate(self.login, clear_password)
Chris@0 277 else
Chris@245 278 User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
Chris@0 279 end
Chris@0 280 end
Chris@909 281
Chris@245 282 # Generates a random salt and computes hashed_password for +clear_password+
Chris@245 283 # The hashed password is stored in the following form: SHA1(salt + SHA1(password))
Chris@245 284 def salt_password(clear_password)
Chris@245 285 self.salt = User.generate_salt
Chris@245 286 self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
Chris@245 287 end
Chris@0 288
Chris@0 289 # Does the backend storage allow this user to change their password?
Chris@0 290 def change_password_allowed?
Chris@1115 291 return true if auth_source.nil?
Chris@0 292 return auth_source.allow_password_changes?
Chris@0 293 end
Chris@0 294
Chris@1464 295 def must_change_password?
Chris@1464 296 must_change_passwd? && change_password_allowed?
Chris@1464 297 end
Chris@1464 298
Chris@1464 299 def generate_password?
Chris@1464 300 generate_password == '1' || generate_password == true
Chris@1464 301 end
Chris@1464 302
Chris@1464 303 # Generate and set a random password on given length
Chris@1464 304 def random_password(length=40)
Chris@0 305 chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
Chris@1464 306 chars -= %w(0 O 1 l)
Chris@0 307 password = ''
Chris@1464 308 length.times {|i| password << chars[SecureRandom.random_number(chars.size)] }
Chris@0 309 self.password = password
Chris@0 310 self.password_confirmation = password
Chris@0 311 self
Chris@0 312 end
Chris@909 313
Chris@0 314 def pref
Chris@0 315 self.preference ||= UserPreference.new(:user => self)
Chris@0 316 end
Chris@909 317
Chris@0 318 def time_zone
Chris@0 319 @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
Chris@0 320 end
Chris@909 321
Chris@0 322 def wants_comments_in_reverse_order?
Chris@0 323 self.pref[:comments_sorting] == 'desc'
Chris@0 324 end
Chris@909 325
Chris@0 326 # Return user's RSS key (a 40 chars long string), used to access feeds
Chris@0 327 def rss_key
Chris@1115 328 if rss_token.nil?
Chris@1115 329 create_rss_token(:action => 'feeds')
Chris@1115 330 end
Chris@1115 331 rss_token.value
Chris@0 332 end
Chris@0 333
Chris@0 334 # Return user's API key (a 40 chars long string), used to access the API
Chris@0 335 def api_key
Chris@1115 336 if api_token.nil?
Chris@1115 337 create_api_token(:action => 'api')
Chris@1115 338 end
Chris@1115 339 api_token.value
Chris@0 340 end
Chris@909 341
Chris@0 342 # Return an array of project ids for which the user has explicitly turned mail notifications on
Chris@0 343 def notified_projects_ids
Chris@0 344 @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
Chris@0 345 end
Chris@909 346
Chris@0 347 def notified_project_ids=(ids)
Chris@1464 348 @notified_projects_ids_changed = true
Chris@1464 349 @notified_projects_ids = ids
Chris@0 350 end
Chris@0 351
Chris@1464 352 # Updates per project notifications (after_save callback)
Chris@1464 353 def update_notified_project_ids
Chris@1464 354 if @notified_projects_ids_changed
Chris@1464 355 ids = (mail_notification == 'selected' ? Array.wrap(notified_projects_ids).reject(&:blank?) : [])
Chris@1464 356 members.update_all(:mail_notification => false)
Chris@1464 357 members.where(:project_id => ids).update_all(:mail_notification => true) if ids.any?
Chris@1464 358 end
Chris@1464 359 end
Chris@1464 360 private :update_notified_project_ids
Chris@1464 361
Chris@128 362 def valid_notification_options
Chris@128 363 self.class.valid_notification_options(self)
Chris@128 364 end
Chris@128 365
chris@37 366 # Only users that belong to more than 1 project can select projects for which they are notified
Chris@128 367 def self.valid_notification_options(user=nil)
chris@37 368 # Note that @user.membership.size would fail since AR ignores
chris@37 369 # :include association option when doing a count
Chris@128 370 if user.nil? || user.memberships.length < 1
Chris@128 371 MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
chris@37 372 else
chris@37 373 MAIL_NOTIFICATION_OPTIONS
chris@37 374 end
chris@37 375 end
chris@37 376
Chris@0 377 # Find a user account by matching the exact login and then a case-insensitive
Chris@0 378 # version. Exact matches will be given priority.
Chris@0 379 def self.find_by_login(login)
Chris@1464 380 if login.present?
Chris@1464 381 login = login.to_s
Chris@1464 382 # First look for an exact match
Chris@1464 383 user = where(:login => login).all.detect {|u| u.login == login}
Chris@1464 384 unless user
Chris@1464 385 # Fail over to case-insensitive if none was found
Chris@1464 386 user = where("LOWER(login) = ?", login.downcase).first
Chris@1464 387 end
Chris@1464 388 user
Chris@1115 389 end
Chris@0 390 end
Chris@0 391
Chris@0 392 def self.find_by_rss_key(key)
Chris@1464 393 Token.find_active_user('feeds', key)
Chris@0 394 end
Chris@909 395
Chris@0 396 def self.find_by_api_key(key)
Chris@1464 397 Token.find_active_user('api', key)
Chris@0 398 end
Chris@909 399
Chris@0 400 # Makes find_by_mail case-insensitive
Chris@0 401 def self.find_by_mail(mail)
Chris@1115 402 where("LOWER(mail) = ?", mail.to_s.downcase).first
Chris@0 403 end
Chris@909 404
Chris@929 405 # Returns true if the default admin account can no longer be used
Chris@929 406 def self.default_admin_account_changed?
Chris@929 407 !User.active.find_by_login("admin").try(:check_password?, "admin")
Chris@929 408 end
Chris@929 409
Chris@0 410 def to_s
Chris@0 411 name
Chris@0 412 end
Chris@909 413
Chris@1115 414 CSS_CLASS_BY_STATUS = {
Chris@1115 415 STATUS_ANONYMOUS => 'anon',
Chris@1115 416 STATUS_ACTIVE => 'active',
Chris@1115 417 STATUS_REGISTERED => 'registered',
Chris@1115 418 STATUS_LOCKED => 'locked'
Chris@1115 419 }
Chris@1115 420
Chris@1115 421 def css_classes
Chris@1115 422 "user #{CSS_CLASS_BY_STATUS[status]}"
Chris@1115 423 end
Chris@1115 424
Chris@0 425 # Returns the current day according to user's time zone
Chris@0 426 def today
Chris@0 427 if time_zone.nil?
Chris@0 428 Date.today
Chris@0 429 else
Chris@0 430 Time.now.in_time_zone(time_zone).to_date
Chris@0 431 end
Chris@0 432 end
Chris@909 433
Chris@1115 434 # Returns the day of +time+ according to user's time zone
Chris@1115 435 def time_to_date(time)
Chris@1115 436 if time_zone.nil?
Chris@1115 437 time.to_date
Chris@1115 438 else
Chris@1115 439 time.in_time_zone(time_zone).to_date
Chris@1115 440 end
Chris@1115 441 end
Chris@1115 442
Chris@0 443 def logged?
Chris@0 444 true
Chris@0 445 end
Chris@909 446
Chris@0 447 def anonymous?
Chris@0 448 !logged?
Chris@0 449 end
Chris@909 450
Chris@1464 451 # Returns user's membership for the given project
Chris@1464 452 # or nil if the user is not a member of project
Chris@1464 453 def membership(project)
Chris@1464 454 project_id = project.is_a?(Project) ? project.id : project
Chris@1464 455
Chris@1464 456 @membership_by_project_id ||= Hash.new {|h, project_id|
Chris@1464 457 h[project_id] = memberships.where(:project_id => project_id).first
Chris@1464 458 }
Chris@1464 459 @membership_by_project_id[project_id]
Chris@1464 460 end
Chris@1464 461
Chris@1464 462 # Returns the user's bult-in role
Chris@1464 463 def builtin_role
Chris@1464 464 @builtin_role ||= Role.non_member
Chris@1464 465 end
Chris@1464 466
Chris@0 467 # Return user's roles for project
Chris@0 468 def roles_for_project(project)
Chris@0 469 roles = []
Chris@0 470 # No role on archived projects
Chris@1115 471 return roles if project.nil? || project.archived?
Chris@1464 472 if membership = membership(project)
Chris@1464 473 roles = membership.roles
Chris@0 474 else
Chris@1464 475 roles << builtin_role
Chris@0 476 end
Chris@0 477 roles
Chris@0 478 end
Chris@909 479
Chris@0 480 # Return true if the user is a member of project
Chris@0 481 def member_of?(project)
Chris@1464 482 projects.to_a.include?(project)
Chris@0 483 end
Chris@909 484
Chris@441 485 # Returns a hash of user's projects grouped by roles
Chris@441 486 def projects_by_role
Chris@441 487 return @projects_by_role if @projects_by_role
Chris@909 488
Chris@1115 489 @projects_by_role = Hash.new([])
Chris@441 490 memberships.each do |membership|
Chris@1115 491 if membership.project
Chris@1115 492 membership.roles.each do |role|
Chris@1115 493 @projects_by_role[role] = [] unless @projects_by_role.key?(role)
Chris@1115 494 @projects_by_role[role] << membership.project
Chris@1115 495 end
Chris@441 496 end
Chris@441 497 end
Chris@441 498 @projects_by_role.each do |role, projects|
Chris@441 499 projects.uniq!
Chris@441 500 end
Chris@909 501
Chris@441 502 @projects_by_role
Chris@441 503 end
Chris@909 504
Chris@909 505 # Returns true if user is arg or belongs to arg
Chris@909 506 def is_or_belongs_to?(arg)
Chris@909 507 if arg.is_a?(User)
Chris@909 508 self == arg
Chris@909 509 elsif arg.is_a?(Group)
Chris@909 510 arg.users.include?(self)
Chris@909 511 else
Chris@909 512 false
Chris@909 513 end
Chris@909 514 end
Chris@909 515
chris@37 516 # Return true if the user is allowed to do the specified action on a specific context
chris@37 517 # Action can be:
Chris@0 518 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
Chris@0 519 # * a permission Symbol (eg. :edit_project)
chris@37 520 # Context can be:
chris@37 521 # * a project : returns true if user is allowed to do the specified action on this project
Chris@441 522 # * an array of projects : returns true if user is allowed on every project
Chris@909 523 # * nil with options[:global] set : check if user has at least one role allowed for this action,
chris@37 524 # or falls back to Non Member / Anonymous permissions depending if the user is logged
Chris@441 525 def allowed_to?(action, context, options={}, &block)
chris@37 526 if context && context.is_a?(Project)
chris@37 527 return false unless context.allows_to?(action)
Chris@0 528 # Admin users are authorized for anything else
Chris@0 529 return true if admin?
Chris@909 530
chris@37 531 roles = roles_for_project(context)
Chris@0 532 return false unless roles
Chris@1115 533 roles.any? {|role|
Chris@441 534 (context.is_public? || role.member?) &&
Chris@441 535 role.allowed_to?(action) &&
Chris@441 536 (block_given? ? yield(role, self) : true)
Chris@441 537 }
chris@37 538 elsif context && context.is_a?(Array)
Chris@1115 539 if context.empty?
Chris@1115 540 false
Chris@1115 541 else
Chris@1115 542 # Authorize if user is authorized on every element of the array
Chris@1115 543 context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&)
chris@37 544 end
Chris@0 545 elsif options[:global]
Chris@0 546 # Admin users are always authorized
Chris@0 547 return true if admin?
Chris@909 548
Chris@0 549 # authorize if user has at least one role that has this permission
Chris@0 550 roles = memberships.collect {|m| m.roles}.flatten.uniq
Chris@441 551 roles << (self.logged? ? Role.non_member : Role.anonymous)
Chris@1115 552 roles.any? {|role|
Chris@441 553 role.allowed_to?(action) &&
Chris@441 554 (block_given? ? yield(role, self) : true)
Chris@441 555 }
Chris@0 556 else
Chris@0 557 false
Chris@0 558 end
Chris@0 559 end
chris@22 560
chris@22 561 # Is the user allowed to do the specified action on any project?
chris@22 562 # See allowed_to? for the actions and valid options.
Chris@441 563 def allowed_to_globally?(action, options, &block)
Chris@441 564 allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
chris@22 565 end
Chris@119 566
Chris@1464 567 # Returns true if the user is allowed to delete the user's own account
Chris@1115 568 def own_account_deletable?
Chris@1115 569 Setting.unsubscribe? &&
Chris@1115 570 (!admin? || User.active.where("admin = ? AND id <> ?", true, id).exists?)
Chris@1115 571 end
Chris@1115 572
Chris@119 573 safe_attributes 'login',
Chris@119 574 'firstname',
Chris@119 575 'lastname',
Chris@119 576 'mail',
Chris@119 577 'mail_notification',
Chris@1464 578 'notified_project_ids',
Chris@119 579 'language',
Chris@119 580 'custom_field_values',
Chris@119 581 'custom_fields',
Chris@119 582 'identity_url'
Chris@909 583
Chris@119 584 safe_attributes 'status',
Chris@119 585 'auth_source_id',
Chris@1464 586 'generate_password',
Chris@1464 587 'must_change_passwd',
Chris@119 588 :if => lambda {|user, current_user| current_user.admin?}
Chris@909 589
Chris@119 590 safe_attributes 'group_ids',
Chris@119 591 :if => lambda {|user, current_user| current_user.admin? && !user.new_record?}
Chris@909 592
chris@37 593 # Utility method to help check if a user should be notified about an
chris@37 594 # event.
chris@37 595 #
chris@37 596 # TODO: only supports Issue events currently
chris@37 597 def notify_about?(object)
Chris@1464 598 if mail_notification == 'all'
chris@37 599 true
Chris@1464 600 elsif mail_notification.blank? || mail_notification == 'none'
Chris@1464 601 false
Chris@1464 602 else
Chris@1464 603 case object
Chris@1464 604 when Issue
Chris@1464 605 case mail_notification
Chris@1464 606 when 'selected', 'only_my_events'
Chris@1464 607 # user receives notifications for created/assigned issues on unselected projects
Chris@1464 608 object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
Chris@1464 609 when 'only_assigned'
Chris@1464 610 is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was)
Chris@1464 611 when 'only_owner'
Chris@1464 612 object.author == self
Chris@1464 613 end
Chris@1464 614 when News
Chris@1464 615 # always send to project members except when mail_notification is set to 'none'
Chris@210 616 true
Chris@210 617 end
chris@37 618 end
chris@37 619 end
Chris@909 620
Chris@0 621 def self.current=(user)
Chris@1464 622 Thread.current[:current_user] = user
Chris@0 623 end
Chris@909 624
Chris@0 625 def self.current
Chris@1464 626 Thread.current[:current_user] ||= User.anonymous
Chris@0 627 end
Chris@909 628
Chris@0 629 # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only
Chris@0 630 # one anonymous user per database.
Chris@0 631 def self.anonymous
Chris@1115 632 anonymous_user = AnonymousUser.first
Chris@0 633 if anonymous_user.nil?
Chris@0 634 anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
Chris@0 635 raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
Chris@0 636 end
Chris@0 637 anonymous_user
Chris@0 638 end
Chris@245 639
Chris@245 640 # Salts all existing unsalted passwords
Chris@245 641 # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
Chris@245 642 # This method is used in the SaltPasswords migration and is to be kept as is
Chris@245 643 def self.salt_unsalted_passwords!
Chris@245 644 transaction do
Chris@1115 645 User.where("salt IS NULL OR salt = ''").find_each do |user|
Chris@245 646 next if user.hashed_password.blank?
Chris@245 647 salt = User.generate_salt
Chris@245 648 hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
Chris@1115 649 User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password)
Chris@245 650 end
Chris@245 651 end
Chris@245 652 end
Chris@909 653
Chris@0 654 protected
Chris@909 655
Chris@909 656 def validate_password_length
Chris@1464 657 return if password.blank? && generate_password?
Chris@0 658 # Password length validation based on setting
Chris@0 659 if !password.nil? && password.size < Setting.password_min_length.to_i
Chris@0 660 errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
Chris@0 661 end
Chris@0 662 end
Chris@909 663
Chris@0 664 private
Chris@909 665
Chris@1464 666 def generate_password_if_needed
Chris@1464 667 if generate_password? && auth_source.nil?
Chris@1464 668 length = [Setting.password_min_length.to_i + 2, 10].max
Chris@1464 669 random_password(length)
Chris@1464 670 end
Chris@1464 671 end
Chris@1464 672
Chris@128 673 # Removes references that are not handled by associations
Chris@128 674 # Things that are not deleted are reassociated with the anonymous user
Chris@128 675 def remove_references_before_destroy
Chris@128 676 return if self.id.nil?
Chris@909 677
Chris@128 678 substitute = User.anonymous
Chris@128 679 Attachment.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
Chris@128 680 Comment.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
Chris@128 681 Issue.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
Chris@128 682 Issue.update_all 'assigned_to_id = NULL', ['assigned_to_id = ?', id]
Chris@128 683 Journal.update_all ['user_id = ?', substitute.id], ['user_id = ?', id]
Chris@128 684 JournalDetail.update_all ['old_value = ?', substitute.id.to_s], ["property = 'attr' AND prop_key = 'assigned_to_id' AND old_value = ?", id.to_s]
Chris@128 685 JournalDetail.update_all ['value = ?', substitute.id.to_s], ["property = 'attr' AND prop_key = 'assigned_to_id' AND value = ?", id.to_s]
Chris@128 686 Message.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
Chris@128 687 News.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
Chris@128 688 # Remove private queries and keep public ones
Chris@1464 689 ::Query.delete_all ['user_id = ? AND visibility = ?', id, ::Query::VISIBILITY_PRIVATE]
Chris@1115 690 ::Query.update_all ['user_id = ?', substitute.id], ['user_id = ?', id]
Chris@128 691 TimeEntry.update_all ['user_id = ?', substitute.id], ['user_id = ?', id]
Chris@128 692 Token.delete_all ['user_id = ?', id]
Chris@128 693 Watcher.delete_all ['user_id = ?', id]
Chris@128 694 WikiContent.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
Chris@128 695 WikiContent::Version.update_all ['author_id = ?', substitute.id], ['author_id = ?', id]
Chris@128 696 end
Chris@909 697
Chris@0 698 # Return password digest
Chris@0 699 def self.hash_password(clear_password)
Chris@0 700 Digest::SHA1.hexdigest(clear_password || "")
Chris@0 701 end
Chris@909 702
Chris@245 703 # Returns a 128bits random salt as a hex string (32 chars long)
Chris@245 704 def self.generate_salt
Chris@1115 705 Redmine::Utils.random_hex(16)
Chris@245 706 end
Chris@909 707
Chris@0 708 end
Chris@0 709
Chris@0 710 class AnonymousUser < User
Chris@1115 711 validate :validate_anonymous_uniqueness, :on => :create
Chris@909 712
Chris@1115 713 def validate_anonymous_uniqueness
Chris@0 714 # There should be only one AnonymousUser in the database
Chris@1464 715 errors.add :base, 'An anonymous user already exists.' if AnonymousUser.exists?
Chris@0 716 end
Chris@909 717
Chris@0 718 def available_custom_fields
Chris@0 719 []
Chris@0 720 end
Chris@909 721
Chris@0 722 # Overrides a few properties
Chris@0 723 def logged?; false end
Chris@0 724 def admin; false end
Chris@0 725 def name(*args); I18n.t(:label_user_anonymous) end
Chris@0 726 def mail; nil end
Chris@0 727 def time_zone; nil end
Chris@0 728 def rss_key; nil end
Chris@909 729
Chris@1115 730 def pref
Chris@1115 731 UserPreference.new(:user => self)
Chris@1115 732 end
Chris@1115 733
Chris@1464 734 # Returns the user's bult-in role
Chris@1464 735 def builtin_role
Chris@1464 736 @builtin_role ||= Role.anonymous
Chris@1464 737 end
Chris@1464 738
Chris@1464 739 def membership(*args)
Chris@1464 740 nil
Chris@1464 741 end
Chris@1464 742
Chris@1464 743 def member_of?(*args)
Chris@1464 744 false
Chris@1464 745 end
Chris@1464 746
Chris@128 747 # Anonymous user can not be destroyed
Chris@128 748 def destroy
Chris@128 749 false
Chris@128 750 end
Chris@0 751 end