You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.rb 9.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. # redMine - project management software
  2. # Copyright (C) 2006-2007 Jean-Philippe Lang
  3. #
  4. # This program is free software; you can redistribute it and/or
  5. # modify it under the terms of the GNU General Public License
  6. # as published by the Free Software Foundation; either version 2
  7. # of the License, or (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  17. require "digest/sha1"
  18. class User < ActiveRecord::Base
  19. class OnTheFlyCreationFailure < Exception; end
  20. # Account statuses
  21. STATUS_ANONYMOUS = 0
  22. STATUS_ACTIVE = 1
  23. STATUS_REGISTERED = 2
  24. STATUS_LOCKED = 3
  25. USER_FORMATS = {
  26. :firstname_lastname => '#{firstname} #{lastname}',
  27. :firstname => '#{firstname}',
  28. :lastname_firstname => '#{lastname} #{firstname}',
  29. :lastname_coma_firstname => '#{lastname}, #{firstname}',
  30. :username => '#{login}'
  31. }
  32. has_many :memberships, :class_name => 'Member', :include => [ :project, :role ], :conditions => "#{Project.table_name}.status=#{Project::STATUS_ACTIVE}", :order => "#{Project.table_name}.name", :dependent => :delete_all
  33. has_many :projects, :through => :memberships
  34. has_many :custom_values, :dependent => :delete_all, :as => :customized
  35. has_many :issue_categories, :foreign_key => 'assigned_to_id', :dependent => :nullify
  36. has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
  37. has_one :rss_token, :dependent => :destroy, :class_name => 'Token', :conditions => "action='feeds'"
  38. belongs_to :auth_source
  39. attr_accessor :password, :password_confirmation
  40. attr_accessor :last_before_login_on
  41. # Prevents unauthorized assignments
  42. attr_protected :login, :admin, :password, :password_confirmation, :hashed_password
  43. validates_presence_of :login, :firstname, :lastname, :mail, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
  44. validates_uniqueness_of :login, :if => Proc.new { |user| !user.login.blank? }
  45. validates_uniqueness_of :mail, :if => Proc.new { |user| !user.mail.blank? }
  46. # Login must contain lettres, numbers, underscores only
  47. validates_format_of :login, :with => /^[a-z0-9_\-@\.]*$/i
  48. validates_length_of :login, :maximum => 30
  49. validates_format_of :firstname, :lastname, :with => /^[\w\s\'\-\.]*$/i
  50. validates_length_of :firstname, :lastname, :maximum => 30
  51. validates_format_of :mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i, :allow_nil => true
  52. validates_length_of :mail, :maximum => 60, :allow_nil => true
  53. validates_length_of :password, :minimum => 4, :allow_nil => true
  54. validates_confirmation_of :password, :allow_nil => true
  55. validates_associated :custom_values, :on => :update
  56. def before_create
  57. self.mail_notification = false
  58. true
  59. end
  60. def before_save
  61. # update hashed_password if password was set
  62. self.hashed_password = User.hash_password(self.password) if self.password
  63. end
  64. def self.active
  65. with_scope :find => { :conditions => [ "status = ?", STATUS_ACTIVE ] } do
  66. yield
  67. end
  68. end
  69. def self.find_active(*args)
  70. active do
  71. find(*args)
  72. end
  73. end
  74. # Returns the user that matches provided login and password, or nil
  75. def self.try_to_login(login, password)
  76. # Make sure no one can sign in with an empty password
  77. return nil if password.to_s.empty?
  78. user = find(:first, :conditions => ["login=?", login])
  79. if user
  80. # user is already in local database
  81. return nil if !user.active?
  82. if user.auth_source
  83. # user has an external authentication method
  84. return nil unless user.auth_source.authenticate(login, password)
  85. else
  86. # authentication with local password
  87. return nil unless User.hash_password(password) == user.hashed_password
  88. end
  89. else
  90. # user is not yet registered, try to authenticate with available sources
  91. attrs = AuthSource.authenticate(login, password)
  92. if attrs
  93. onthefly = new(*attrs)
  94. onthefly.login = login
  95. onthefly.language = Setting.default_language
  96. if onthefly.save
  97. user = find(:first, :conditions => ["login=?", login])
  98. logger.info("User '#{user.login}' created from the LDAP") if logger
  99. else
  100. logger.error("User '#{onthefly.login}' found in LDAP but could not be created (#{onthefly.errors.full_messages.join(', ')})") if logger
  101. raise OnTheFlyCreationFailure.new
  102. end
  103. end
  104. end
  105. user.update_attribute(:last_login_on, Time.now) if user
  106. user
  107. rescue => text
  108. raise text
  109. end
  110. # Return user's full name for display
  111. def name(formatter = nil)
  112. f = USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
  113. eval '"' + f + '"'
  114. end
  115. def active?
  116. self.status == STATUS_ACTIVE
  117. end
  118. def registered?
  119. self.status == STATUS_REGISTERED
  120. end
  121. def locked?
  122. self.status == STATUS_LOCKED
  123. end
  124. def check_password?(clear_password)
  125. User.hash_password(clear_password) == self.hashed_password
  126. end
  127. def pref
  128. self.preference ||= UserPreference.new(:user => self)
  129. end
  130. def time_zone
  131. self.pref.time_zone.nil? ? nil : TimeZone[self.pref.time_zone]
  132. end
  133. def wants_comments_in_reverse_order?
  134. self.pref[:comments_sorting] == 'desc'
  135. end
  136. # Return user's RSS key (a 40 chars long string), used to access feeds
  137. def rss_key
  138. token = self.rss_token || Token.create(:user => self, :action => 'feeds')
  139. token.value
  140. end
  141. # Return an array of project ids for which the user has explicitly turned mail notifications on
  142. def notified_projects_ids
  143. @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
  144. end
  145. def notified_project_ids=(ids)
  146. Member.update_all("mail_notification = #{connection.quoted_false}", ['user_id = ?', id])
  147. Member.update_all("mail_notification = #{connection.quoted_true}", ['user_id = ? AND project_id IN (?)', id, ids]) if ids && !ids.empty?
  148. @notified_projects_ids = nil
  149. notified_projects_ids
  150. end
  151. def self.find_by_rss_key(key)
  152. token = Token.find_by_value(key)
  153. token && token.user.active? ? token.user : nil
  154. end
  155. def self.find_by_autologin_key(key)
  156. token = Token.find_by_action_and_value('autologin', key)
  157. token && (token.created_on > Setting.autologin.to_i.day.ago) && token.user.active? ? token.user : nil
  158. end
  159. def <=>(user)
  160. if user.nil?
  161. -1
  162. elsif lastname.to_s.downcase == user.lastname.to_s.downcase
  163. firstname.to_s.downcase <=> user.firstname.to_s.downcase
  164. else
  165. lastname.to_s.downcase <=> user.lastname.to_s.downcase
  166. end
  167. end
  168. def to_s
  169. name
  170. end
  171. def logged?
  172. true
  173. end
  174. # Return user's role for project
  175. def role_for_project(project)
  176. # No role on archived projects
  177. return nil unless project && project.active?
  178. if logged?
  179. # Find project membership
  180. membership = memberships.detect {|m| m.project_id == project.id}
  181. if membership
  182. membership.role
  183. else
  184. @role_non_member ||= Role.non_member
  185. end
  186. else
  187. @role_anonymous ||= Role.anonymous
  188. end
  189. end
  190. # Return true if the user is a member of project
  191. def member_of?(project)
  192. role_for_project(project).member?
  193. end
  194. # Return true if the user is allowed to do the specified action on project
  195. # action can be:
  196. # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
  197. # * a permission Symbol (eg. :edit_project)
  198. def allowed_to?(action, project, options={})
  199. if project
  200. # No action allowed on archived projects
  201. return false unless project.active?
  202. # No action allowed on disabled modules
  203. return false unless project.allows_to?(action)
  204. # Admin users are authorized for anything else
  205. return true if admin?
  206. role = role_for_project(project)
  207. return false unless role
  208. role.allowed_to?(action) && (project.is_public? || role.member?)
  209. elsif options[:global]
  210. # authorize if user has at least one role that has this permission
  211. roles = memberships.collect {|m| m.role}.uniq
  212. roles.detect {|r| r.allowed_to?(action)}
  213. else
  214. false
  215. end
  216. end
  217. def self.current=(user)
  218. @current_user = user
  219. end
  220. def self.current
  221. @current_user ||= User.anonymous
  222. end
  223. def self.anonymous
  224. anonymous_user = AnonymousUser.find(:first)
  225. if anonymous_user.nil?
  226. anonymous_user = AnonymousUser.create(:lastname => 'Anonymous', :firstname => '', :mail => '', :login => '', :status => 0)
  227. raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
  228. end
  229. anonymous_user
  230. end
  231. private
  232. # Return password digest
  233. def self.hash_password(clear_password)
  234. Digest::SHA1.hexdigest(clear_password || "")
  235. end
  236. end
  237. class AnonymousUser < User
  238. def validate_on_create
  239. # There should be only one AnonymousUser in the database
  240. errors.add_to_base 'An anonymous user already exists.' if AnonymousUser.find(:first)
  241. end
  242. # Overrides a few properties
  243. def logged?; false end
  244. def admin; false end
  245. def name; 'Anonymous' end
  246. def mail; nil end
  247. def time_zone; nil end
  248. def rss_key; nil end
  249. end