annotate app/models/user.rb @ 403:b15397a5341c feature_36

model changes;
author luisf <luis.figueira@eecs.qmul.ac.uk>
date Tue, 12 Apr 2011 16:35:30 +0100
parents 440c4f4bf2d6
children ec7c78040115
rev   line source
Chris@0 1 # Redmine - project management software
Chris@0 2 # Copyright (C) 2006-2009 Jean-Philippe Lang
Chris@0 3 #
Chris@0 4 # This program is free software; you can redistribute it and/or
Chris@0 5 # modify it under the terms of the GNU General Public License
Chris@0 6 # as published by the Free Software Foundation; either version 2
Chris@0 7 # of the License, or (at your option) any later version.
Chris@0 8 #
Chris@0 9 # This program is distributed in the hope that it will be useful,
Chris@0 10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
Chris@0 11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
Chris@0 12 # GNU General Public License for more details.
Chris@0 13 #
Chris@0 14 # You should have received a copy of the GNU General Public License
Chris@0 15 # along with this program; if not, write to the Free Software
Chris@0 16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Chris@0 17
Chris@0 18 require "digest/sha1"
Chris@0 19
Chris@0 20 class User < Principal
Chris@0 21
Chris@0 22 # Account statuses
Chris@0 23 STATUS_ANONYMOUS = 0
Chris@0 24 STATUS_ACTIVE = 1
Chris@0 25 STATUS_REGISTERED = 2
Chris@0 26 STATUS_LOCKED = 3
Chris@0 27
Chris@0 28 USER_FORMATS = {
Chris@0 29 :firstname_lastname => '#{firstname} #{lastname}',
Chris@0 30 :firstname => '#{firstname}',
Chris@0 31 :lastname_firstname => '#{lastname} #{firstname}',
Chris@0 32 :lastname_coma_firstname => '#{lastname}, #{firstname}',
Chris@0 33 :username => '#{login}'
Chris@0 34 }
Chris@0 35
chris@37 36 MAIL_NOTIFICATION_OPTIONS = [
chris@37 37 [:all, :label_user_mail_option_all],
chris@37 38 [:selected, :label_user_mail_option_selected],
chris@37 39 [:none, :label_user_mail_option_none],
chris@37 40 [:only_my_events, :label_user_mail_option_only_my_events],
chris@37 41 [:only_assigned, :label_user_mail_option_only_assigned],
chris@37 42 [:only_owner, :label_user_mail_option_only_owner]
chris@37 43 ]
chris@37 44
Chris@0 45 has_and_belongs_to_many :groups, :after_add => Proc.new {|user, group| group.user_added(user)},
Chris@0 46 :after_remove => Proc.new {|user, group| group.user_removed(user)}
Chris@0 47 has_many :issue_categories, :foreign_key => 'assigned_to_id', :dependent => :nullify
Chris@0 48 has_many :changesets, :dependent => :nullify
Chris@0 49 has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
Chris@0 50 has_one :rss_token, :dependent => :destroy, :class_name => 'Token', :conditions => "action='feeds'"
Chris@0 51 has_one :api_token, :dependent => :destroy, :class_name => 'Token', :conditions => "action='api'"
Chris@0 52 belongs_to :auth_source
Chris@0 53
luisf@55 54 has_one :ssamr_user_detail, :dependent => :destroy, :class_name => 'SsamrUserDetail'
luisf@65 55 accepts_nested_attributes_for :ssamr_user_detail
luis@403 56
luis@403 57 has_one :author
luisf@64 58
Chris@0 59 # Active non-anonymous users scope
Chris@0 60 named_scope :active, :conditions => "#{User.table_name}.status = #{STATUS_ACTIVE}"
Chris@0 61
Chris@0 62 acts_as_customizable
Chris@0 63
Chris@0 64 attr_accessor :password, :password_confirmation
Chris@0 65 attr_accessor :last_before_login_on
Chris@0 66 # Prevents unauthorized assignments
Chris@0 67 attr_protected :login, :admin, :password, :password_confirmation, :hashed_password, :group_ids
Chris@0 68
Chris@0 69 validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
luisf@60 70
luisf@60 71 # TODO: is this validation correct validates_presence_of :ssamr_user_detail
luisf@60 72
Chris@0 73 validates_uniqueness_of :login, :if => Proc.new { |user| !user.login.blank? }, :case_sensitive => false
Chris@0 74 validates_uniqueness_of :mail, :if => Proc.new { |user| !user.mail.blank? }, :case_sensitive => false
Chris@0 75 # Login must contain lettres, numbers, underscores only
Chris@0 76 validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
Chris@0 77 validates_length_of :login, :maximum => 30
Chris@0 78 validates_format_of :firstname, :lastname, :with => /^[\w\s\'\-\.]*$/i
Chris@0 79 validates_length_of :firstname, :lastname, :maximum => 30
Chris@0 80 validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_nil => true
Chris@0 81 validates_length_of :mail, :maximum => 60, :allow_nil => true
Chris@0 82 validates_confirmation_of :password, :allow_nil => true
Chris@0 83
luisf@190 84 validates_acceptance_of :terms_and_conditions, :on => :create, :message => :must_accept_terms_and_conditions
luisf@190 85
Chris@0 86 def before_create
chris@37 87 self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
Chris@0 88 true
Chris@0 89 end
Chris@0 90
Chris@0 91 def before_save
Chris@0 92 # update hashed_password if password was set
Chris@0 93 self.hashed_password = User.hash_password(self.password) if self.password && self.auth_source_id.blank?
Chris@0 94 end
Chris@0 95
Chris@0 96 def reload(*args)
Chris@0 97 @name = nil
Chris@0 98 super
Chris@0 99 end
Chris@0 100
Chris@1 101 def mail=(arg)
Chris@1 102 write_attribute(:mail, arg.to_s.strip)
Chris@1 103 end
Chris@1 104
luisf@59 105 def description=(arg)
luisf@59 106 write_attribute(:description, arg.to_s.strip)
luisf@59 107 end
luisf@59 108
Chris@0 109 def identity_url=(url)
Chris@0 110 if url.blank?
Chris@0 111 write_attribute(:identity_url, '')
Chris@0 112 else
Chris@0 113 begin
Chris@0 114 write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
Chris@0 115 rescue OpenIdAuthentication::InvalidOpenId
Chris@0 116 # Invlaid url, don't save
Chris@0 117 end
Chris@0 118 end
Chris@0 119 self.read_attribute(:identity_url)
Chris@0 120 end
Chris@0 121
Chris@0 122 # Returns the user that matches provided login and password, or nil
Chris@0 123 def self.try_to_login(login, password)
Chris@0 124 # Make sure no one can sign in with an empty password
Chris@0 125 return nil if password.to_s.empty?
Chris@0 126 user = find_by_login(login)
Chris@0 127 if user
Chris@0 128 # user is already in local database
Chris@0 129 return nil if !user.active?
Chris@0 130 if user.auth_source
Chris@0 131 # user has an external authentication method
Chris@0 132 return nil unless user.auth_source.authenticate(login, password)
Chris@0 133 else
Chris@0 134 # authentication with local password
Chris@0 135 return nil unless User.hash_password(password) == user.hashed_password
Chris@0 136 end
Chris@0 137 else
Chris@0 138 # user is not yet registered, try to authenticate with available sources
Chris@0 139 attrs = AuthSource.authenticate(login, password)
Chris@0 140 if attrs
Chris@0 141 user = new(attrs)
Chris@0 142 user.login = login
Chris@0 143 user.language = Setting.default_language
Chris@0 144 if user.save
Chris@0 145 user.reload
Chris@0 146 logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
Chris@0 147 end
Chris@0 148 end
Chris@0 149 end
Chris@0 150 user.update_attribute(:last_login_on, Time.now) if user && !user.new_record?
Chris@0 151 user
Chris@0 152 rescue => text
Chris@0 153 raise text
Chris@0 154 end
Chris@0 155
Chris@0 156 # Returns the user who matches the given autologin +key+ or nil
Chris@0 157 def self.try_to_autologin(key)
Chris@0 158 tokens = Token.find_all_by_action_and_value('autologin', key)
Chris@0 159 # Make sure there's only 1 token that matches the key
Chris@0 160 if tokens.size == 1
Chris@0 161 token = tokens.first
Chris@0 162 if (token.created_on > Setting.autologin.to_i.day.ago) && token.user && token.user.active?
Chris@0 163 token.user.update_attribute(:last_login_on, Time.now)
Chris@0 164 token.user
Chris@0 165 end
Chris@0 166 end
Chris@0 167 end
Chris@0 168
Chris@0 169 # Return user's full name for display
Chris@0 170 def name(formatter = nil)
Chris@0 171 if formatter
Chris@0 172 eval('"' + (USER_FORMATS[formatter] || USER_FORMATS[:firstname_lastname]) + '"')
Chris@0 173 else
Chris@0 174 @name ||= eval('"' + (USER_FORMATS[Setting.user_format] || USER_FORMATS[:firstname_lastname]) + '"')
Chris@0 175 end
Chris@0 176 end
Chris@0 177
Chris@0 178 def active?
Chris@0 179 self.status == STATUS_ACTIVE
Chris@0 180 end
Chris@0 181
Chris@0 182 def registered?
Chris@0 183 self.status == STATUS_REGISTERED
Chris@0 184 end
Chris@0 185
Chris@0 186 def locked?
Chris@0 187 self.status == STATUS_LOCKED
Chris@0 188 end
Chris@0 189
Chris@14 190 def activate
Chris@14 191 self.status = STATUS_ACTIVE
Chris@14 192 end
Chris@14 193
Chris@14 194 def register
Chris@14 195 self.status = STATUS_REGISTERED
Chris@14 196 end
Chris@14 197
Chris@14 198 def lock
Chris@14 199 self.status = STATUS_LOCKED
Chris@14 200 end
Chris@14 201
Chris@14 202 def activate!
Chris@14 203 update_attribute(:status, STATUS_ACTIVE)
Chris@14 204 end
Chris@14 205
Chris@14 206 def register!
Chris@14 207 update_attribute(:status, STATUS_REGISTERED)
Chris@14 208 end
Chris@14 209
Chris@14 210 def lock!
Chris@14 211 update_attribute(:status, STATUS_LOCKED)
Chris@14 212 end
Chris@14 213
Chris@0 214 def check_password?(clear_password)
Chris@0 215 if auth_source_id.present?
Chris@0 216 auth_source.authenticate(self.login, clear_password)
Chris@0 217 else
Chris@0 218 User.hash_password(clear_password) == self.hashed_password
Chris@0 219 end
Chris@0 220 end
Chris@0 221
Chris@0 222 # Does the backend storage allow this user to change their password?
Chris@0 223 def change_password_allowed?
Chris@0 224 return true if auth_source_id.blank?
Chris@0 225 return auth_source.allow_password_changes?
Chris@0 226 end
Chris@0 227
Chris@0 228 # Generate and set a random password. Useful for automated user creation
Chris@0 229 # Based on Token#generate_token_value
Chris@0 230 #
Chris@0 231 def random_password
Chris@0 232 chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
Chris@0 233 password = ''
Chris@0 234 40.times { |i| password << chars[rand(chars.size-1)] }
Chris@0 235 self.password = password
Chris@0 236 self.password_confirmation = password
Chris@0 237 self
Chris@0 238 end
Chris@0 239
Chris@0 240 def pref
Chris@0 241 self.preference ||= UserPreference.new(:user => self)
Chris@0 242 end
Chris@0 243
Chris@0 244 def time_zone
Chris@0 245 @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
Chris@0 246 end
Chris@0 247
Chris@0 248 def wants_comments_in_reverse_order?
Chris@0 249 self.pref[:comments_sorting] == 'desc'
Chris@0 250 end
Chris@0 251
Chris@0 252 # Return user's RSS key (a 40 chars long string), used to access feeds
Chris@0 253 def rss_key
Chris@0 254 token = self.rss_token || Token.create(:user => self, :action => 'feeds')
Chris@0 255 token.value
Chris@0 256 end
Chris@0 257
Chris@0 258 # Return user's API key (a 40 chars long string), used to access the API
Chris@0 259 def api_key
Chris@0 260 token = self.api_token || self.create_api_token(:action => 'api')
Chris@0 261 token.value
Chris@0 262 end
Chris@0 263
Chris@0 264 # Return an array of project ids for which the user has explicitly turned mail notifications on
Chris@0 265 def notified_projects_ids
Chris@0 266 @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
Chris@0 267 end
Chris@0 268
Chris@0 269 def notified_project_ids=(ids)
Chris@0 270 Member.update_all("mail_notification = #{connection.quoted_false}", ['user_id = ?', id])
Chris@0 271 Member.update_all("mail_notification = #{connection.quoted_true}", ['user_id = ? AND project_id IN (?)', id, ids]) if ids && !ids.empty?
Chris@0 272 @notified_projects_ids = nil
Chris@0 273 notified_projects_ids
Chris@0 274 end
Chris@0 275
chris@37 276 # Only users that belong to more than 1 project can select projects for which they are notified
chris@37 277 def valid_notification_options
chris@37 278 # Note that @user.membership.size would fail since AR ignores
chris@37 279 # :include association option when doing a count
chris@37 280 if memberships.length < 1
chris@37 281 MAIL_NOTIFICATION_OPTIONS.delete_if {|option| option.first == :selected}
chris@37 282 else
chris@37 283 MAIL_NOTIFICATION_OPTIONS
chris@37 284 end
chris@37 285 end
chris@37 286
Chris@0 287 # Find a user account by matching the exact login and then a case-insensitive
Chris@0 288 # version. Exact matches will be given priority.
Chris@0 289 def self.find_by_login(login)
Chris@0 290 # force string comparison to be case sensitive on MySQL
Chris@0 291 type_cast = (ActiveRecord::Base.connection.adapter_name == 'MySQL') ? 'BINARY' : ''
Chris@0 292
Chris@0 293 # First look for an exact match
Chris@0 294 user = first(:conditions => ["#{type_cast} login = ?", login])
Chris@0 295 # Fail over to case-insensitive if none was found
Chris@0 296 user ||= first(:conditions => ["#{type_cast} LOWER(login) = ?", login.to_s.downcase])
Chris@0 297 end
Chris@0 298
Chris@0 299 def self.find_by_rss_key(key)
Chris@0 300 token = Token.find_by_value(key)
Chris@0 301 token && token.user.active? ? token.user : nil
Chris@0 302 end
Chris@0 303
Chris@0 304 def self.find_by_api_key(key)
Chris@0 305 token = Token.find_by_action_and_value('api', key)
Chris@0 306 token && token.user.active? ? token.user : nil
Chris@0 307 end
Chris@0 308
Chris@0 309 # Makes find_by_mail case-insensitive
Chris@0 310 def self.find_by_mail(mail)
Chris@0 311 find(:first, :conditions => ["LOWER(mail) = ?", mail.to_s.downcase])
Chris@0 312 end
Chris@0 313
Chris@0 314 def to_s
Chris@0 315 name
Chris@0 316 end
Chris@0 317
Chris@0 318 # Returns the current day according to user's time zone
Chris@0 319 def today
Chris@0 320 if time_zone.nil?
Chris@0 321 Date.today
Chris@0 322 else
Chris@0 323 Time.now.in_time_zone(time_zone).to_date
Chris@0 324 end
Chris@0 325 end
Chris@0 326
Chris@0 327 def logged?
Chris@0 328 true
Chris@0 329 end
Chris@0 330
Chris@0 331 def anonymous?
Chris@0 332 !logged?
Chris@0 333 end
Chris@0 334
Chris@0 335 # Return user's roles for project
Chris@0 336 def roles_for_project(project)
Chris@0 337 roles = []
Chris@0 338 # No role on archived projects
Chris@0 339 return roles unless project && project.active?
Chris@0 340 if logged?
Chris@0 341 # Find project membership
Chris@0 342 membership = memberships.detect {|m| m.project_id == project.id}
Chris@0 343 if membership
Chris@0 344 roles = membership.roles
Chris@0 345 else
Chris@0 346 @role_non_member ||= Role.non_member
Chris@0 347 roles << @role_non_member
Chris@0 348 end
Chris@0 349 else
Chris@0 350 @role_anonymous ||= Role.anonymous
Chris@0 351 roles << @role_anonymous
Chris@0 352 end
Chris@0 353 roles
Chris@0 354 end
Chris@0 355
Chris@0 356 # Return true if the user is a member of project
Chris@0 357 def member_of?(project)
Chris@0 358 !roles_for_project(project).detect {|role| role.member?}.nil?
Chris@0 359 end
Chris@0 360
chris@37 361 # Return true if the user is allowed to do the specified action on a specific context
chris@37 362 # Action can be:
Chris@0 363 # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
Chris@0 364 # * a permission Symbol (eg. :edit_project)
chris@37 365 # Context can be:
chris@37 366 # * a project : returns true if user is allowed to do the specified action on this project
chris@37 367 # * a group of projects : returns true if user is allowed on every project
chris@37 368 # * nil with options[:global] set : check if user has at least one role allowed for this action,
chris@37 369 # or falls back to Non Member / Anonymous permissions depending if the user is logged
chris@37 370 def allowed_to?(action, context, options={})
chris@37 371 if context && context.is_a?(Project)
Chris@0 372 # No action allowed on archived projects
chris@37 373 return false unless context.active?
Chris@0 374 # No action allowed on disabled modules
chris@37 375 return false unless context.allows_to?(action)
Chris@0 376 # Admin users are authorized for anything else
Chris@0 377 return true if admin?
Chris@0 378
chris@37 379 roles = roles_for_project(context)
Chris@0 380 return false unless roles
chris@37 381 roles.detect {|role| (context.is_public? || role.member?) && role.allowed_to?(action)}
Chris@0 382
chris@37 383 elsif context && context.is_a?(Array)
chris@37 384 # Authorize if user is authorized on every element of the array
chris@37 385 context.map do |project|
chris@37 386 allowed_to?(action,project,options)
chris@37 387 end.inject do |memo,allowed|
chris@37 388 memo && allowed
chris@37 389 end
Chris@0 390 elsif options[:global]
Chris@0 391 # Admin users are always authorized
Chris@0 392 return true if admin?
Chris@0 393
Chris@0 394 # authorize if user has at least one role that has this permission
Chris@0 395 roles = memberships.collect {|m| m.roles}.flatten.uniq
Chris@0 396 roles.detect {|r| r.allowed_to?(action)} || (self.logged? ? Role.non_member.allowed_to?(action) : Role.anonymous.allowed_to?(action))
Chris@0 397 else
Chris@0 398 false
Chris@0 399 end
Chris@0 400 end
chris@22 401
chris@22 402 # Is the user allowed to do the specified action on any project?
chris@22 403 # See allowed_to? for the actions and valid options.
chris@22 404 def allowed_to_globally?(action, options)
chris@22 405 allowed_to?(action, nil, options.reverse_merge(:global => true))
chris@22 406 end
Chris@0 407
chris@37 408 # Utility method to help check if a user should be notified about an
chris@37 409 # event.
chris@37 410 #
chris@37 411 # TODO: only supports Issue events currently
chris@37 412 def notify_about?(object)
chris@37 413 case mail_notification.to_sym
chris@37 414 when :all
chris@37 415 true
chris@37 416 when :selected
chris@37 417 # Handled by the Project
chris@37 418 when :none
chris@37 419 false
chris@37 420 when :only_my_events
chris@37 421 if object.is_a?(Issue) && (object.author == self || object.assigned_to == self)
chris@37 422 true
chris@37 423 else
chris@37 424 false
chris@37 425 end
chris@37 426 when :only_assigned
chris@37 427 if object.is_a?(Issue) && object.assigned_to == self
chris@37 428 true
chris@37 429 else
chris@37 430 false
chris@37 431 end
chris@37 432 when :only_owner
chris@37 433 if object.is_a?(Issue) && object.author == self
chris@37 434 true
chris@37 435 else
chris@37 436 false
chris@37 437 end
chris@37 438 else
chris@37 439 false
chris@37 440 end
chris@37 441 end
chris@37 442
Chris@0 443 def self.current=(user)
Chris@0 444 @current_user = user
Chris@0 445 end
Chris@0 446
Chris@0 447 def self.current
Chris@0 448 @current_user ||= User.anonymous
Chris@0 449 end
Chris@0 450
Chris@0 451 # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only
Chris@0 452 # one anonymous user per database.
Chris@0 453 def self.anonymous
Chris@0 454 anonymous_user = AnonymousUser.find(:first)
Chris@0 455 if anonymous_user.nil?
Chris@0 456 anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
Chris@0 457 raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
Chris@0 458 end
Chris@0 459 anonymous_user
Chris@0 460 end
Chris@0 461
Chris@0 462 protected
Chris@0 463
Chris@0 464 def validate
Chris@0 465 # Password length validation based on setting
Chris@0 466 if !password.nil? && password.size < Setting.password_min_length.to_i
Chris@0 467 errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
Chris@0 468 end
Chris@0 469 end
Chris@0 470
Chris@0 471 private
Chris@0 472
Chris@0 473 # Return password digest
Chris@0 474 def self.hash_password(clear_password)
Chris@0 475 Digest::SHA1.hexdigest(clear_password || "")
Chris@0 476 end
Chris@0 477 end
Chris@0 478
Chris@0 479 class AnonymousUser < User
Chris@0 480
Chris@0 481 def validate_on_create
Chris@0 482 # There should be only one AnonymousUser in the database
Chris@0 483 errors.add_to_base 'An anonymous user already exists.' if AnonymousUser.find(:first)
Chris@0 484 end
Chris@0 485
Chris@0 486 def available_custom_fields
Chris@0 487 []
Chris@0 488 end
Chris@0 489
Chris@0 490 # Overrides a few properties
Chris@0 491 def logged?; false end
Chris@0 492 def admin; false end
Chris@0 493 def name(*args); I18n.t(:label_user_anonymous) end
Chris@0 494 def mail; nil end
Chris@0 495 def time_zone; nil end
Chris@0 496 def rss_key; nil end
Chris@0 497 end