annotate .svn/pristine/c6/c68a764ff663d1fa551848f69b2759490df8f986.svn-base @ 1298:4f746d8966dd redmine_2.3_integration

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