annotate .svn/pristine/c6/c68a764ff663d1fa551848f69b2759490df8f986.svn-base @ 1327:287f201c2802 redmine-2.2-integration

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