Chris@1494: # Redmine - project management software Chris@1494: # Copyright (C) 2006-2014 Jean-Philippe Lang Chris@1494: # Chris@1494: # This program is free software; you can redistribute it and/or Chris@1494: # modify it under the terms of the GNU General Public License Chris@1494: # as published by the Free Software Foundation; either version 2 Chris@1494: # of the License, or (at your option) any later version. Chris@1494: # Chris@1494: # This program is distributed in the hope that it will be useful, Chris@1494: # but WITHOUT ANY WARRANTY; without even the implied warranty of Chris@1494: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Chris@1494: # GNU General Public License for more details. Chris@1494: # Chris@1494: # You should have received a copy of the GNU General Public License Chris@1494: # along with this program; if not, write to the Free Software Chris@1494: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Chris@1494: Chris@1494: require "digest/sha1" Chris@1494: Chris@1494: class User < Principal Chris@1494: include Redmine::SafeAttributes Chris@1494: Chris@1494: # Different ways of displaying/sorting users Chris@1494: USER_FORMATS = { Chris@1494: :firstname_lastname => { Chris@1494: :string => '#{firstname} #{lastname}', Chris@1494: :order => %w(firstname lastname id), Chris@1494: :setting_order => 1 Chris@1494: }, Chris@1494: :firstname_lastinitial => { Chris@1494: :string => '#{firstname} #{lastname.to_s.chars.first}.', Chris@1494: :order => %w(firstname lastname id), Chris@1494: :setting_order => 2 Chris@1494: }, Chris@1494: :firstname => { Chris@1494: :string => '#{firstname}', Chris@1494: :order => %w(firstname id), Chris@1494: :setting_order => 3 Chris@1494: }, Chris@1494: :lastname_firstname => { Chris@1494: :string => '#{lastname} #{firstname}', Chris@1494: :order => %w(lastname firstname id), Chris@1494: :setting_order => 4 Chris@1494: }, Chris@1494: :lastname_coma_firstname => { Chris@1494: :string => '#{lastname}, #{firstname}', Chris@1494: :order => %w(lastname firstname id), Chris@1494: :setting_order => 5 Chris@1494: }, Chris@1494: :lastname => { Chris@1494: :string => '#{lastname}', Chris@1494: :order => %w(lastname id), Chris@1494: :setting_order => 6 Chris@1494: }, Chris@1494: :username => { Chris@1494: :string => '#{login}', Chris@1494: :order => %w(login id), Chris@1494: :setting_order => 7 Chris@1494: }, Chris@1494: } Chris@1494: Chris@1494: MAIL_NOTIFICATION_OPTIONS = [ Chris@1494: ['all', :label_user_mail_option_all], Chris@1494: ['selected', :label_user_mail_option_selected], Chris@1494: ['only_my_events', :label_user_mail_option_only_my_events], Chris@1494: ['only_assigned', :label_user_mail_option_only_assigned], Chris@1494: ['only_owner', :label_user_mail_option_only_owner], Chris@1494: ['none', :label_user_mail_option_none] Chris@1494: ] Chris@1494: Chris@1494: has_and_belongs_to_many :groups, :after_add => Proc.new {|user, group| group.user_added(user)}, Chris@1494: :after_remove => Proc.new {|user, group| group.user_removed(user)} Chris@1494: has_many :changesets, :dependent => :nullify Chris@1494: has_one :preference, :dependent => :destroy, :class_name => 'UserPreference' Chris@1494: has_one :rss_token, :class_name => 'Token', :conditions => "action='feeds'" Chris@1494: has_one :api_token, :class_name => 'Token', :conditions => "action='api'" Chris@1494: belongs_to :auth_source Chris@1494: Chris@1494: scope :logged, lambda { where("#{User.table_name}.status <> #{STATUS_ANONYMOUS}") } Chris@1494: scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) } Chris@1494: Chris@1494: acts_as_customizable Chris@1494: Chris@1494: attr_accessor :password, :password_confirmation, :generate_password Chris@1494: attr_accessor :last_before_login_on Chris@1494: # Prevents unauthorized assignments Chris@1494: attr_protected :login, :admin, :password, :password_confirmation, :hashed_password Chris@1494: Chris@1494: LOGIN_LENGTH_LIMIT = 60 Chris@1494: MAIL_LENGTH_LIMIT = 60 Chris@1494: Chris@1494: validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) } Chris@1494: validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false Chris@1494: validates_uniqueness_of :mail, :if => Proc.new { |user| user.mail_changed? && user.mail.present? }, :case_sensitive => false Chris@1494: # Login must contain letters, numbers, underscores only Chris@1494: validates_format_of :login, :with => /\A[a-z0-9_\-@\.]*\z/i Chris@1494: validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT Chris@1494: validates_length_of :firstname, :lastname, :maximum => 30 Chris@1494: validates_format_of :mail, :with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, :allow_blank => true Chris@1494: validates_length_of :mail, :maximum => MAIL_LENGTH_LIMIT, :allow_nil => true Chris@1494: validates_confirmation_of :password, :allow_nil => true Chris@1494: validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true Chris@1494: validate :validate_password_length Chris@1494: Chris@1494: before_create :set_mail_notification Chris@1494: before_save :generate_password_if_needed, :update_hashed_password Chris@1494: before_destroy :remove_references_before_destroy Chris@1494: after_save :update_notified_project_ids Chris@1494: Chris@1494: scope :in_group, lambda {|group| Chris@1494: group_id = group.is_a?(Group) ? group.id : group.to_i Chris@1494: 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@1494: } Chris@1494: scope :not_in_group, lambda {|group| Chris@1494: group_id = group.is_a?(Group) ? group.id : group.to_i Chris@1494: 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@1494: } Chris@1494: scope :sorted, lambda { order(*User.fields_for_order_statement)} Chris@1494: Chris@1494: def set_mail_notification Chris@1494: self.mail_notification = Setting.default_notification_option if self.mail_notification.blank? Chris@1494: true Chris@1494: end Chris@1494: Chris@1494: def update_hashed_password Chris@1494: # update hashed_password if password was set Chris@1494: if self.password && self.auth_source_id.blank? Chris@1494: salt_password(password) Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: alias :base_reload :reload Chris@1494: def reload(*args) Chris@1494: @name = nil Chris@1494: @projects_by_role = nil Chris@1494: @membership_by_project_id = nil Chris@1494: @notified_projects_ids = nil Chris@1494: @notified_projects_ids_changed = false Chris@1494: @builtin_role = nil Chris@1494: base_reload(*args) Chris@1494: end Chris@1494: Chris@1494: def mail=(arg) Chris@1494: write_attribute(:mail, arg.to_s.strip) Chris@1494: end Chris@1494: Chris@1494: def identity_url=(url) Chris@1494: if url.blank? Chris@1494: write_attribute(:identity_url, '') Chris@1494: else Chris@1494: begin Chris@1494: write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url)) Chris@1494: rescue OpenIdAuthentication::InvalidOpenId Chris@1494: # Invalid url, don't save Chris@1494: end Chris@1494: end Chris@1494: self.read_attribute(:identity_url) Chris@1494: end Chris@1494: Chris@1494: # Returns the user that matches provided login and password, or nil Chris@1494: def self.try_to_login(login, password, active_only=true) Chris@1494: login = login.to_s Chris@1494: password = password.to_s Chris@1494: Chris@1494: # Make sure no one can sign in with an empty login or password Chris@1494: return nil if login.empty? || password.empty? Chris@1494: user = find_by_login(login) Chris@1494: if user Chris@1494: # user is already in local database Chris@1494: return nil unless user.check_password?(password) Chris@1494: return nil if !user.active? && active_only Chris@1494: else Chris@1494: # user is not yet registered, try to authenticate with available sources Chris@1494: attrs = AuthSource.authenticate(login, password) Chris@1494: if attrs Chris@1494: user = new(attrs) Chris@1494: user.login = login Chris@1494: user.language = Setting.default_language Chris@1494: if user.save Chris@1494: user.reload Chris@1494: logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source Chris@1494: end Chris@1494: end Chris@1494: end Chris@1494: user.update_column(:last_login_on, Time.now) if user && !user.new_record? && user.active? Chris@1494: user Chris@1494: rescue => text Chris@1494: raise text Chris@1494: end Chris@1494: Chris@1494: # Returns the user who matches the given autologin +key+ or nil Chris@1494: def self.try_to_autologin(key) Chris@1494: user = Token.find_active_user('autologin', key, Setting.autologin.to_i) Chris@1494: if user Chris@1494: user.update_column(:last_login_on, Time.now) Chris@1494: user Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def self.name_formatter(formatter = nil) Chris@1494: USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname] Chris@1494: end Chris@1494: Chris@1494: # Returns an array of fields names than can be used to make an order statement for users Chris@1494: # according to how user names are displayed Chris@1494: # Examples: Chris@1494: # Chris@1494: # User.fields_for_order_statement => ['users.login', 'users.id'] Chris@1494: # User.fields_for_order_statement('authors') => ['authors.login', 'authors.id'] Chris@1494: def self.fields_for_order_statement(table=nil) Chris@1494: table ||= table_name Chris@1494: name_formatter[:order].map {|field| "#{table}.#{field}"} Chris@1494: end Chris@1494: Chris@1494: # Return user's full name for display Chris@1494: def name(formatter = nil) Chris@1494: f = self.class.name_formatter(formatter) Chris@1494: if formatter Chris@1494: eval('"' + f[:string] + '"') Chris@1494: else Chris@1494: @name ||= eval('"' + f[:string] + '"') Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def active? Chris@1494: self.status == STATUS_ACTIVE Chris@1494: end Chris@1494: Chris@1494: def registered? Chris@1494: self.status == STATUS_REGISTERED Chris@1494: end Chris@1494: Chris@1494: def locked? Chris@1494: self.status == STATUS_LOCKED Chris@1494: end Chris@1494: Chris@1494: def activate Chris@1494: self.status = STATUS_ACTIVE Chris@1494: end Chris@1494: Chris@1494: def register Chris@1494: self.status = STATUS_REGISTERED Chris@1494: end Chris@1494: Chris@1494: def lock Chris@1494: self.status = STATUS_LOCKED Chris@1494: end Chris@1494: Chris@1494: def activate! Chris@1494: update_attribute(:status, STATUS_ACTIVE) Chris@1494: end Chris@1494: Chris@1494: def register! Chris@1494: update_attribute(:status, STATUS_REGISTERED) Chris@1494: end Chris@1494: Chris@1494: def lock! Chris@1494: update_attribute(:status, STATUS_LOCKED) Chris@1494: end Chris@1494: Chris@1494: # Returns true if +clear_password+ is the correct user's password, otherwise false Chris@1494: def check_password?(clear_password) Chris@1494: if auth_source_id.present? Chris@1494: auth_source.authenticate(self.login, clear_password) Chris@1494: else Chris@1494: User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: # Generates a random salt and computes hashed_password for +clear_password+ Chris@1494: # The hashed password is stored in the following form: SHA1(salt + SHA1(password)) Chris@1494: def salt_password(clear_password) Chris@1494: self.salt = User.generate_salt Chris@1494: self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}") Chris@1494: end Chris@1494: Chris@1494: # Does the backend storage allow this user to change their password? Chris@1494: def change_password_allowed? Chris@1494: return true if auth_source.nil? Chris@1494: return auth_source.allow_password_changes? Chris@1494: end Chris@1494: Chris@1494: def must_change_password? Chris@1494: must_change_passwd? && change_password_allowed? Chris@1494: end Chris@1494: Chris@1494: def generate_password? Chris@1494: generate_password == '1' || generate_password == true Chris@1494: end Chris@1494: Chris@1494: # Generate and set a random password on given length Chris@1494: def random_password(length=40) Chris@1494: chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a Chris@1494: chars -= %w(0 O 1 l) Chris@1494: password = '' Chris@1494: length.times {|i| password << chars[SecureRandom.random_number(chars.size)] } Chris@1494: self.password = password Chris@1494: self.password_confirmation = password Chris@1494: self Chris@1494: end Chris@1494: Chris@1494: def pref Chris@1494: self.preference ||= UserPreference.new(:user => self) Chris@1494: end Chris@1494: Chris@1494: def time_zone Chris@1494: @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone]) Chris@1494: end Chris@1494: Chris@1494: def wants_comments_in_reverse_order? Chris@1494: self.pref[:comments_sorting] == 'desc' Chris@1494: end Chris@1494: Chris@1494: # Return user's RSS key (a 40 chars long string), used to access feeds Chris@1494: def rss_key Chris@1494: if rss_token.nil? Chris@1494: create_rss_token(:action => 'feeds') Chris@1494: end Chris@1494: rss_token.value Chris@1494: end Chris@1494: Chris@1494: # Return user's API key (a 40 chars long string), used to access the API Chris@1494: def api_key Chris@1494: if api_token.nil? Chris@1494: create_api_token(:action => 'api') Chris@1494: end Chris@1494: api_token.value Chris@1494: end Chris@1494: Chris@1494: # Return an array of project ids for which the user has explicitly turned mail notifications on Chris@1494: def notified_projects_ids Chris@1494: @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id) Chris@1494: end Chris@1494: Chris@1494: def notified_project_ids=(ids) Chris@1494: @notified_projects_ids_changed = true Chris@1494: @notified_projects_ids = ids Chris@1494: end Chris@1494: Chris@1494: # Updates per project notifications (after_save callback) Chris@1494: def update_notified_project_ids Chris@1494: if @notified_projects_ids_changed Chris@1494: ids = (mail_notification == 'selected' ? Array.wrap(notified_projects_ids).reject(&:blank?) : []) Chris@1494: members.update_all(:mail_notification => false) Chris@1494: members.where(:project_id => ids).update_all(:mail_notification => true) if ids.any? Chris@1494: end Chris@1494: end Chris@1494: private :update_notified_project_ids Chris@1494: Chris@1494: def valid_notification_options Chris@1494: self.class.valid_notification_options(self) Chris@1494: end Chris@1494: Chris@1494: # Only users that belong to more than 1 project can select projects for which they are notified Chris@1494: def self.valid_notification_options(user=nil) Chris@1494: # Note that @user.membership.size would fail since AR ignores Chris@1494: # :include association option when doing a count Chris@1494: if user.nil? || user.memberships.length < 1 Chris@1494: MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'} Chris@1494: else Chris@1494: MAIL_NOTIFICATION_OPTIONS Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: # Find a user account by matching the exact login and then a case-insensitive Chris@1494: # version. Exact matches will be given priority. Chris@1494: def self.find_by_login(login) Chris@1494: if login.present? Chris@1494: login = login.to_s Chris@1494: # First look for an exact match Chris@1494: user = where(:login => login).all.detect {|u| u.login == login} Chris@1494: unless user Chris@1494: # Fail over to case-insensitive if none was found Chris@1494: user = where("LOWER(login) = ?", login.downcase).first Chris@1494: end Chris@1494: user Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def self.find_by_rss_key(key) Chris@1494: Token.find_active_user('feeds', key) Chris@1494: end Chris@1494: Chris@1494: def self.find_by_api_key(key) Chris@1494: Token.find_active_user('api', key) Chris@1494: end Chris@1494: Chris@1494: # Makes find_by_mail case-insensitive Chris@1494: def self.find_by_mail(mail) Chris@1494: where("LOWER(mail) = ?", mail.to_s.downcase).first Chris@1494: end Chris@1494: Chris@1494: # Returns true if the default admin account can no longer be used Chris@1494: def self.default_admin_account_changed? Chris@1494: !User.active.find_by_login("admin").try(:check_password?, "admin") Chris@1494: end Chris@1494: Chris@1494: def to_s Chris@1494: name Chris@1494: end Chris@1494: Chris@1494: CSS_CLASS_BY_STATUS = { Chris@1494: STATUS_ANONYMOUS => 'anon', Chris@1494: STATUS_ACTIVE => 'active', Chris@1494: STATUS_REGISTERED => 'registered', Chris@1494: STATUS_LOCKED => 'locked' Chris@1494: } Chris@1494: Chris@1494: def css_classes Chris@1494: "user #{CSS_CLASS_BY_STATUS[status]}" Chris@1494: end Chris@1494: Chris@1494: # Returns the current day according to user's time zone Chris@1494: def today Chris@1494: if time_zone.nil? Chris@1494: Date.today Chris@1494: else Chris@1494: Time.now.in_time_zone(time_zone).to_date Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: # Returns the day of +time+ according to user's time zone Chris@1494: def time_to_date(time) Chris@1494: if time_zone.nil? Chris@1494: time.to_date Chris@1494: else Chris@1494: time.in_time_zone(time_zone).to_date Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def logged? Chris@1494: true Chris@1494: end Chris@1494: Chris@1494: def anonymous? Chris@1494: !logged? Chris@1494: end Chris@1494: Chris@1494: # Returns user's membership for the given project Chris@1494: # or nil if the user is not a member of project Chris@1494: def membership(project) Chris@1494: project_id = project.is_a?(Project) ? project.id : project Chris@1494: Chris@1494: @membership_by_project_id ||= Hash.new {|h, project_id| Chris@1494: h[project_id] = memberships.where(:project_id => project_id).first Chris@1494: } Chris@1494: @membership_by_project_id[project_id] Chris@1494: end Chris@1494: Chris@1494: # Returns the user's bult-in role Chris@1494: def builtin_role Chris@1494: @builtin_role ||= Role.non_member Chris@1494: end Chris@1494: Chris@1494: # Return user's roles for project Chris@1494: def roles_for_project(project) Chris@1494: roles = [] Chris@1494: # No role on archived projects Chris@1494: return roles if project.nil? || project.archived? Chris@1494: if membership = membership(project) Chris@1494: roles = membership.roles Chris@1494: else Chris@1494: roles << builtin_role Chris@1494: end Chris@1494: roles Chris@1494: end Chris@1494: Chris@1494: # Return true if the user is a member of project Chris@1494: def member_of?(project) Chris@1494: projects.to_a.include?(project) Chris@1494: end Chris@1494: Chris@1494: # Returns a hash of user's projects grouped by roles Chris@1494: def projects_by_role Chris@1494: return @projects_by_role if @projects_by_role Chris@1494: Chris@1494: @projects_by_role = Hash.new([]) Chris@1494: memberships.each do |membership| Chris@1494: if membership.project Chris@1494: membership.roles.each do |role| Chris@1494: @projects_by_role[role] = [] unless @projects_by_role.key?(role) Chris@1494: @projects_by_role[role] << membership.project Chris@1494: end Chris@1494: end Chris@1494: end Chris@1494: @projects_by_role.each do |role, projects| Chris@1494: projects.uniq! Chris@1494: end Chris@1494: Chris@1494: @projects_by_role Chris@1494: end Chris@1494: Chris@1494: # Returns true if user is arg or belongs to arg Chris@1494: def is_or_belongs_to?(arg) Chris@1494: if arg.is_a?(User) Chris@1494: self == arg Chris@1494: elsif arg.is_a?(Group) Chris@1494: arg.users.include?(self) Chris@1494: else Chris@1494: false Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: # Return true if the user is allowed to do the specified action on a specific context Chris@1494: # Action can be: Chris@1494: # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit') Chris@1494: # * a permission Symbol (eg. :edit_project) Chris@1494: # Context can be: Chris@1494: # * a project : returns true if user is allowed to do the specified action on this project Chris@1494: # * an array of projects : returns true if user is allowed on every project Chris@1494: # * nil with options[:global] set : check if user has at least one role allowed for this action, Chris@1494: # or falls back to Non Member / Anonymous permissions depending if the user is logged Chris@1494: def allowed_to?(action, context, options={}, &block) Chris@1494: if context && context.is_a?(Project) Chris@1494: return false unless context.allows_to?(action) Chris@1494: # Admin users are authorized for anything else Chris@1494: return true if admin? Chris@1494: Chris@1494: roles = roles_for_project(context) Chris@1494: return false unless roles Chris@1494: roles.any? {|role| Chris@1494: (context.is_public? || role.member?) && Chris@1494: role.allowed_to?(action) && Chris@1494: (block_given? ? yield(role, self) : true) Chris@1494: } Chris@1494: elsif context && context.is_a?(Array) Chris@1494: if context.empty? Chris@1494: false Chris@1494: else Chris@1494: # Authorize if user is authorized on every element of the array Chris@1494: context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&) Chris@1494: end Chris@1494: elsif options[:global] Chris@1494: # Admin users are always authorized Chris@1494: return true if admin? Chris@1494: Chris@1494: # authorize if user has at least one role that has this permission Chris@1494: roles = memberships.collect {|m| m.roles}.flatten.uniq Chris@1494: roles << (self.logged? ? Role.non_member : Role.anonymous) Chris@1494: roles.any? {|role| Chris@1494: role.allowed_to?(action) && Chris@1494: (block_given? ? yield(role, self) : true) Chris@1494: } Chris@1494: else Chris@1494: false Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: # Is the user allowed to do the specified action on any project? Chris@1494: # See allowed_to? for the actions and valid options. Chris@1494: def allowed_to_globally?(action, options, &block) Chris@1494: allowed_to?(action, nil, options.reverse_merge(:global => true), &block) Chris@1494: end Chris@1494: Chris@1494: # Returns true if the user is allowed to delete the user's own account Chris@1494: def own_account_deletable? Chris@1494: Setting.unsubscribe? && Chris@1494: (!admin? || User.active.where("admin = ? AND id <> ?", true, id).exists?) Chris@1494: end Chris@1494: Chris@1494: safe_attributes 'login', Chris@1494: 'firstname', Chris@1494: 'lastname', Chris@1494: 'mail', Chris@1494: 'mail_notification', Chris@1494: 'notified_project_ids', Chris@1494: 'language', Chris@1494: 'custom_field_values', Chris@1494: 'custom_fields', Chris@1494: 'identity_url' Chris@1494: Chris@1494: safe_attributes 'status', Chris@1494: 'auth_source_id', Chris@1494: 'generate_password', Chris@1494: 'must_change_passwd', Chris@1494: :if => lambda {|user, current_user| current_user.admin?} Chris@1494: Chris@1494: safe_attributes 'group_ids', Chris@1494: :if => lambda {|user, current_user| current_user.admin? && !user.new_record?} Chris@1494: Chris@1494: # Utility method to help check if a user should be notified about an Chris@1494: # event. Chris@1494: # Chris@1494: # TODO: only supports Issue events currently Chris@1494: def notify_about?(object) Chris@1494: if mail_notification == 'all' Chris@1494: true Chris@1494: elsif mail_notification.blank? || mail_notification == 'none' Chris@1494: false Chris@1494: else Chris@1494: case object Chris@1494: when Issue Chris@1494: case mail_notification Chris@1494: when 'selected', 'only_my_events' Chris@1494: # user receives notifications for created/assigned issues on unselected projects Chris@1494: object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was) Chris@1494: when 'only_assigned' Chris@1494: is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.assigned_to_was) Chris@1494: when 'only_owner' Chris@1494: object.author == self Chris@1494: end Chris@1494: when News Chris@1494: # always send to project members except when mail_notification is set to 'none' Chris@1494: true Chris@1494: end Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: def self.current=(user) Chris@1494: Thread.current[:current_user] = user Chris@1494: end Chris@1494: Chris@1494: def self.current Chris@1494: Thread.current[:current_user] ||= User.anonymous Chris@1494: end Chris@1494: Chris@1494: # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only Chris@1494: # one anonymous user per database. Chris@1494: def self.anonymous Chris@1494: anonymous_user = AnonymousUser.first Chris@1494: if anonymous_user.nil? Chris@1494: anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0) Chris@1494: raise 'Unable to create the anonymous user.' if anonymous_user.new_record? Chris@1494: end Chris@1494: anonymous_user Chris@1494: end Chris@1494: Chris@1494: # Salts all existing unsalted passwords Chris@1494: # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password)) Chris@1494: # This method is used in the SaltPasswords migration and is to be kept as is Chris@1494: def self.salt_unsalted_passwords! Chris@1494: transaction do Chris@1494: User.where("salt IS NULL OR salt = ''").find_each do |user| Chris@1494: next if user.hashed_password.blank? Chris@1494: salt = User.generate_salt Chris@1494: hashed_password = User.hash_password("#{salt}#{user.hashed_password}") Chris@1494: User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password) Chris@1494: end Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: protected Chris@1494: Chris@1494: def validate_password_length Chris@1494: return if password.blank? && generate_password? Chris@1494: # Password length validation based on setting Chris@1494: if !password.nil? && password.size < Setting.password_min_length.to_i Chris@1494: errors.add(:password, :too_short, :count => Setting.password_min_length.to_i) Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: private Chris@1494: Chris@1494: def generate_password_if_needed Chris@1494: if generate_password? && auth_source.nil? Chris@1494: length = [Setting.password_min_length.to_i + 2, 10].max Chris@1494: random_password(length) Chris@1494: end Chris@1494: end Chris@1494: Chris@1494: # Removes references that are not handled by associations Chris@1494: # Things that are not deleted are reassociated with the anonymous user Chris@1494: def remove_references_before_destroy Chris@1494: return if self.id.nil? Chris@1494: Chris@1494: substitute = User.anonymous Chris@1494: Attachment.update_all ['author_id = ?', substitute.id], ['author_id = ?', id] Chris@1494: Comment.update_all ['author_id = ?', substitute.id], ['author_id = ?', id] Chris@1494: Issue.update_all ['author_id = ?', substitute.id], ['author_id = ?', id] Chris@1494: Issue.update_all 'assigned_to_id = NULL', ['assigned_to_id = ?', id] Chris@1494: Journal.update_all ['user_id = ?', substitute.id], ['user_id = ?', id] Chris@1494: JournalDetail.update_all ['old_value = ?', substitute.id.to_s], ["property = 'attr' AND prop_key = 'assigned_to_id' AND old_value = ?", id.to_s] Chris@1494: JournalDetail.update_all ['value = ?', substitute.id.to_s], ["property = 'attr' AND prop_key = 'assigned_to_id' AND value = ?", id.to_s] Chris@1494: Message.update_all ['author_id = ?', substitute.id], ['author_id = ?', id] Chris@1494: News.update_all ['author_id = ?', substitute.id], ['author_id = ?', id] Chris@1494: # Remove private queries and keep public ones Chris@1494: ::Query.delete_all ['user_id = ? AND visibility = ?', id, ::Query::VISIBILITY_PRIVATE] Chris@1494: ::Query.update_all ['user_id = ?', substitute.id], ['user_id = ?', id] Chris@1494: TimeEntry.update_all ['user_id = ?', substitute.id], ['user_id = ?', id] Chris@1494: Token.delete_all ['user_id = ?', id] Chris@1494: Watcher.delete_all ['user_id = ?', id] Chris@1494: WikiContent.update_all ['author_id = ?', substitute.id], ['author_id = ?', id] Chris@1494: WikiContent::Version.update_all ['author_id = ?', substitute.id], ['author_id = ?', id] Chris@1494: end Chris@1494: Chris@1494: # Return password digest Chris@1494: def self.hash_password(clear_password) Chris@1494: Digest::SHA1.hexdigest(clear_password || "") Chris@1494: end Chris@1494: Chris@1494: # Returns a 128bits random salt as a hex string (32 chars long) Chris@1494: def self.generate_salt Chris@1494: Redmine::Utils.random_hex(16) Chris@1494: end Chris@1494: Chris@1494: end Chris@1494: Chris@1494: class AnonymousUser < User Chris@1494: validate :validate_anonymous_uniqueness, :on => :create Chris@1494: Chris@1494: def validate_anonymous_uniqueness Chris@1494: # There should be only one AnonymousUser in the database Chris@1494: errors.add :base, 'An anonymous user already exists.' if AnonymousUser.exists? Chris@1494: end Chris@1494: Chris@1494: def available_custom_fields Chris@1494: [] Chris@1494: end Chris@1494: Chris@1494: # Overrides a few properties Chris@1494: def logged?; false end Chris@1494: def admin; false end Chris@1494: def name(*args); I18n.t(:label_user_anonymous) end Chris@1494: def mail; nil end Chris@1494: def time_zone; nil end Chris@1494: def rss_key; nil end Chris@1494: Chris@1494: def pref Chris@1494: UserPreference.new(:user => self) Chris@1494: end Chris@1494: Chris@1494: # Returns the user's bult-in role Chris@1494: def builtin_role Chris@1494: @builtin_role ||= Role.anonymous Chris@1494: end Chris@1494: Chris@1494: def membership(*args) Chris@1494: nil Chris@1494: end Chris@1494: Chris@1494: def member_of?(*args) Chris@1494: false Chris@1494: end Chris@1494: Chris@1494: # Anonymous user can not be destroyed Chris@1494: def destroy Chris@1494: false Chris@1494: end Chris@1494: end