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