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 31KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2019 Jean-Philippe Lang
  4. #
  5. # This program is free software; you can redistribute it and/or
  6. # modify it under the terms of the GNU General Public License
  7. # as published by the Free Software Foundation; either version 2
  8. # of the License, or (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. require "digest/sha1"
  19. class User < Principal
  20. include Redmine::SafeAttributes
  21. # Different ways of displaying/sorting users
  22. USER_FORMATS = {
  23. :firstname_lastname => {
  24. :string => '#{firstname} #{lastname}',
  25. :order => %w(firstname lastname id),
  26. :setting_order => 1
  27. },
  28. :firstname_lastinitial => {
  29. :string => '#{firstname} #{lastname.to_s.chars.first}.',
  30. :order => %w(firstname lastname id),
  31. :setting_order => 2
  32. },
  33. :firstinitial_lastname => {
  34. :string => '#{firstname.to_s.gsub(/(([[:alpha:]])[[:alpha:]]*\.?)/, \'\2.\')} #{lastname}',
  35. :order => %w(firstname lastname id),
  36. :setting_order => 2
  37. },
  38. :firstname => {
  39. :string => '#{firstname}',
  40. :order => %w(firstname id),
  41. :setting_order => 3
  42. },
  43. :lastname_firstname => {
  44. :string => '#{lastname} #{firstname}',
  45. :order => %w(lastname firstname id),
  46. :setting_order => 4
  47. },
  48. :lastnamefirstname => {
  49. :string => '#{lastname}#{firstname}',
  50. :order => %w(lastname firstname id),
  51. :setting_order => 5
  52. },
  53. :lastname_comma_firstname => {
  54. :string => '#{lastname}, #{firstname}',
  55. :order => %w(lastname firstname id),
  56. :setting_order => 6
  57. },
  58. :lastname => {
  59. :string => '#{lastname}',
  60. :order => %w(lastname id),
  61. :setting_order => 7
  62. },
  63. :username => {
  64. :string => '#{login}',
  65. :order => %w(login id),
  66. :setting_order => 8
  67. },
  68. }
  69. MAIL_NOTIFICATION_OPTIONS = [
  70. ['all', :label_user_mail_option_all],
  71. ['selected', :label_user_mail_option_selected],
  72. ['only_my_events', :label_user_mail_option_only_my_events],
  73. ['only_assigned', :label_user_mail_option_only_assigned],
  74. ['only_owner', :label_user_mail_option_only_owner],
  75. ['none', :label_user_mail_option_none]
  76. ]
  77. has_and_belongs_to_many :groups,
  78. :join_table => "#{table_name_prefix}groups_users#{table_name_suffix}",
  79. :after_add => Proc.new {|user, group| group.user_added(user)},
  80. :after_remove => Proc.new {|user, group| group.user_removed(user)}
  81. has_many :changesets, :dependent => :nullify
  82. has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
  83. has_one :rss_token, lambda {where "action='feeds'"}, :class_name => 'Token'
  84. has_one :api_token, lambda {where "action='api'"}, :class_name => 'Token'
  85. has_one :email_address, lambda {where :is_default => true}, :autosave => true
  86. has_many :email_addresses, :dependent => :delete_all
  87. belongs_to :auth_source
  88. scope :logged, lambda { where("#{User.table_name}.status <> #{STATUS_ANONYMOUS}") }
  89. scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i}) }
  90. acts_as_customizable
  91. attr_accessor :password, :password_confirmation, :generate_password
  92. attr_accessor :last_before_login_on
  93. attr_accessor :remote_ip
  94. LOGIN_LENGTH_LIMIT = 60
  95. MAIL_LENGTH_LIMIT = 60
  96. validates_presence_of :login, :firstname, :lastname, :if => Proc.new { |user| !user.is_a?(AnonymousUser) }
  97. validates_uniqueness_of :login, :if => Proc.new { |user| user.login_changed? && user.login.present? }, :case_sensitive => false
  98. # Login must contain letters, numbers, underscores only
  99. validates_format_of :login, :with => /\A[a-z0-9_\-@\.]*\z/i
  100. validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT
  101. validates_length_of :firstname, :lastname, :maximum => 30
  102. validates_length_of :identity_url, maximum: 255
  103. validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
  104. validate :validate_password_length
  105. validate do
  106. if password_confirmation && password != password_confirmation
  107. errors.add(:password, :confirmation)
  108. end
  109. end
  110. self.valid_statuses = [STATUS_ACTIVE, STATUS_REGISTERED, STATUS_LOCKED]
  111. before_validation :instantiate_email_address
  112. before_create :set_mail_notification
  113. before_save :generate_password_if_needed, :update_hashed_password
  114. before_destroy :remove_references_before_destroy
  115. after_save :update_notified_project_ids, :destroy_tokens, :deliver_security_notification
  116. after_destroy :deliver_security_notification
  117. scope :admin, lambda {|*args|
  118. admin = args.size > 0 ? !!args.first : true
  119. where(:admin => admin)
  120. }
  121. scope :in_group, lambda {|group|
  122. group_id = group.is_a?(Group) ? group.id : group.to_i
  123. 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)
  124. }
  125. scope :not_in_group, lambda {|group|
  126. group_id = group.is_a?(Group) ? group.id : group.to_i
  127. 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)
  128. }
  129. scope :sorted, lambda { order(*User.fields_for_order_statement)}
  130. scope :having_mail, lambda {|arg|
  131. addresses = Array.wrap(arg).map {|a| a.to_s.downcase}
  132. if addresses.any?
  133. joins(:email_addresses).where("LOWER(#{EmailAddress.table_name}.address) IN (?)", addresses).distinct
  134. else
  135. none
  136. end
  137. }
  138. def set_mail_notification
  139. self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
  140. true
  141. end
  142. def update_hashed_password
  143. # update hashed_password if password was set
  144. if self.password && self.auth_source_id.blank?
  145. salt_password(password)
  146. end
  147. end
  148. alias :base_reload :reload
  149. def reload(*args)
  150. @name = nil
  151. @roles = nil
  152. @projects_by_role = nil
  153. @project_ids_by_role = nil
  154. @membership_by_project_id = nil
  155. @notified_projects_ids = nil
  156. @notified_projects_ids_changed = false
  157. @builtin_role = nil
  158. @visible_project_ids = nil
  159. @managed_roles = nil
  160. base_reload(*args)
  161. end
  162. def mail
  163. email_address.try(:address)
  164. end
  165. def mail=(arg)
  166. email = email_address || build_email_address
  167. email.address = arg
  168. end
  169. def mail_changed?
  170. email_address.try(:address_changed?)
  171. end
  172. def mails
  173. email_addresses.pluck(:address)
  174. end
  175. def self.find_or_initialize_by_identity_url(url)
  176. user = where(:identity_url => url).first
  177. unless user
  178. user = User.new
  179. user.identity_url = url
  180. end
  181. user
  182. end
  183. def identity_url=(url)
  184. if url.blank?
  185. write_attribute(:identity_url, '')
  186. else
  187. begin
  188. write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
  189. rescue OpenIdAuthentication::InvalidOpenId
  190. # Invalid url, don't save
  191. end
  192. end
  193. self.read_attribute(:identity_url)
  194. end
  195. # Returns the user that matches provided login and password, or nil
  196. def self.try_to_login(login, password, active_only=true)
  197. login = login.to_s.strip
  198. password = password.to_s
  199. # Make sure no one can sign in with an empty login or password
  200. return nil if login.empty? || password.empty?
  201. user = find_by_login(login)
  202. if user
  203. # user is already in local database
  204. return nil unless user.check_password?(password)
  205. return nil if !user.active? && active_only
  206. else
  207. # user is not yet registered, try to authenticate with available sources
  208. attrs = AuthSource.authenticate(login, password)
  209. if attrs
  210. user = new(attrs)
  211. user.login = login
  212. user.language = Setting.default_language
  213. if user.save
  214. user.reload
  215. logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
  216. end
  217. end
  218. end
  219. user.update_last_login_on! if user && !user.new_record? && user.active?
  220. user
  221. rescue => text
  222. raise text
  223. end
  224. # Returns the user who matches the given autologin +key+ or nil
  225. def self.try_to_autologin(key)
  226. user = Token.find_active_user('autologin', key, Setting.autologin.to_i)
  227. if user
  228. user.update_last_login_on!
  229. user
  230. end
  231. end
  232. def self.name_formatter(formatter = nil)
  233. USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
  234. end
  235. # Returns an array of fields names than can be used to make an order statement for users
  236. # according to how user names are displayed
  237. # Examples:
  238. #
  239. # User.fields_for_order_statement => ['users.login', 'users.id']
  240. # User.fields_for_order_statement('authors') => ['authors.login', 'authors.id']
  241. def self.fields_for_order_statement(table=nil)
  242. table ||= table_name
  243. name_formatter[:order].map {|field| "#{table}.#{field}"}
  244. end
  245. # Return user's full name for display
  246. def name(formatter = nil)
  247. f = self.class.name_formatter(formatter)
  248. if formatter
  249. eval('"' + f[:string] + '"')
  250. else
  251. @name ||= eval('"' + f[:string] + '"')
  252. end
  253. end
  254. def active?
  255. self.status == STATUS_ACTIVE
  256. end
  257. def registered?
  258. self.status == STATUS_REGISTERED
  259. end
  260. def locked?
  261. self.status == STATUS_LOCKED
  262. end
  263. def activate
  264. self.status = STATUS_ACTIVE
  265. end
  266. def register
  267. self.status = STATUS_REGISTERED
  268. end
  269. def lock
  270. self.status = STATUS_LOCKED
  271. end
  272. def activate!
  273. update_attribute(:status, STATUS_ACTIVE)
  274. end
  275. def register!
  276. update_attribute(:status, STATUS_REGISTERED)
  277. end
  278. def lock!
  279. update_attribute(:status, STATUS_LOCKED)
  280. end
  281. def update_last_login_on!
  282. return if last_login_on.present? && last_login_on >= 1.minute.ago
  283. update_column(:last_login_on, Time.now)
  284. end
  285. # Returns true if +clear_password+ is the correct user's password, otherwise false
  286. def check_password?(clear_password)
  287. if auth_source_id.present?
  288. auth_source.authenticate(self.login, clear_password)
  289. else
  290. User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
  291. end
  292. end
  293. # Generates a random salt and computes hashed_password for +clear_password+
  294. # The hashed password is stored in the following form: SHA1(salt + SHA1(password))
  295. def salt_password(clear_password)
  296. self.salt = User.generate_salt
  297. self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
  298. self.passwd_changed_on = Time.now.change(:usec => 0)
  299. end
  300. # Does the backend storage allow this user to change their password?
  301. def change_password_allowed?
  302. return true if auth_source.nil?
  303. return auth_source.allow_password_changes?
  304. end
  305. # Returns true if the user password has expired
  306. def password_expired?
  307. period = Setting.password_max_age.to_i
  308. if period.zero?
  309. false
  310. else
  311. changed_on = self.passwd_changed_on || Time.at(0)
  312. changed_on < period.days.ago
  313. end
  314. end
  315. def must_change_password?
  316. (must_change_passwd? || password_expired?) && change_password_allowed?
  317. end
  318. def generate_password?
  319. ActiveRecord::Type::Boolean.new.deserialize(generate_password)
  320. end
  321. # Generate and set a random password on given length
  322. def random_password(length=40)
  323. chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
  324. chars -= %w(0 O 1 l)
  325. password = +''
  326. length.times {|i| password << chars[SecureRandom.random_number(chars.size)] }
  327. self.password = password
  328. self.password_confirmation = password
  329. self
  330. end
  331. def pref
  332. self.preference ||= UserPreference.new(:user => self)
  333. end
  334. def time_zone
  335. @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
  336. end
  337. def force_default_language?
  338. Setting.force_default_language_for_loggedin?
  339. end
  340. def language
  341. if force_default_language?
  342. Setting.default_language
  343. else
  344. super
  345. end
  346. end
  347. def wants_comments_in_reverse_order?
  348. self.pref[:comments_sorting] == 'desc'
  349. end
  350. # Return user's RSS key (a 40 chars long string), used to access feeds
  351. def rss_key
  352. if rss_token.nil?
  353. create_rss_token(:action => 'feeds')
  354. end
  355. rss_token.value
  356. end
  357. # Return user's API key (a 40 chars long string), used to access the API
  358. def api_key
  359. if api_token.nil?
  360. create_api_token(:action => 'api')
  361. end
  362. api_token.value
  363. end
  364. # Generates a new session token and returns its value
  365. def generate_session_token
  366. token = Token.create!(:user_id => id, :action => 'session')
  367. token.value
  368. end
  369. def delete_session_token(value)
  370. Token.where(:user_id => id, :action => 'session', :value => value).delete_all
  371. end
  372. # Generates a new autologin token and returns its value
  373. def generate_autologin_token
  374. token = Token.create!(:user_id => id, :action => 'autologin')
  375. token.value
  376. end
  377. def delete_autologin_token(value)
  378. Token.where(:user_id => id, :action => 'autologin', :value => value).delete_all
  379. end
  380. # Returns true if token is a valid session token for the user whose id is user_id
  381. def self.verify_session_token(user_id, token)
  382. return false if user_id.blank? || token.blank?
  383. scope = Token.where(:user_id => user_id, :value => token.to_s, :action => 'session')
  384. if Setting.session_lifetime?
  385. scope = scope.where("created_on > ?", Setting.session_lifetime.to_i.minutes.ago)
  386. end
  387. if Setting.session_timeout?
  388. scope = scope.where("updated_on > ?", Setting.session_timeout.to_i.minutes.ago)
  389. end
  390. scope.update_all(:updated_on => Time.now) == 1
  391. end
  392. # Return an array of project ids for which the user has explicitly turned mail notifications on
  393. def notified_projects_ids
  394. @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
  395. end
  396. def notified_project_ids=(ids)
  397. @notified_projects_ids_changed = true
  398. @notified_projects_ids = ids.map(&:to_i).uniq.select {|n| n > 0}
  399. end
  400. # Updates per project notifications (after_save callback)
  401. def update_notified_project_ids
  402. if @notified_projects_ids_changed
  403. ids = (mail_notification == 'selected' ? Array.wrap(notified_projects_ids).reject(&:blank?) : [])
  404. members.update_all(:mail_notification => false)
  405. members.where(:project_id => ids).update_all(:mail_notification => true) if ids.any?
  406. end
  407. end
  408. private :update_notified_project_ids
  409. def valid_notification_options
  410. self.class.valid_notification_options(self)
  411. end
  412. # Only users that belong to more than 1 project can select projects for which they are notified
  413. def self.valid_notification_options(user=nil)
  414. # Note that @user.membership.size would fail since AR ignores
  415. # :include association option when doing a count
  416. if user.nil? || user.memberships.length < 1
  417. MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
  418. else
  419. MAIL_NOTIFICATION_OPTIONS
  420. end
  421. end
  422. # Find a user account by matching the exact login and then a case-insensitive
  423. # version. Exact matches will be given priority.
  424. def self.find_by_login(login)
  425. login = Redmine::CodesetUtil.replace_invalid_utf8(login.to_s)
  426. if login.present?
  427. # First look for an exact match
  428. user = where(:login => login).detect {|u| u.login == login}
  429. unless user
  430. # Fail over to case-insensitive if none was found
  431. user = find_by("LOWER(login) = ?", login.downcase)
  432. end
  433. user
  434. end
  435. end
  436. def self.find_by_rss_key(key)
  437. Token.find_active_user('feeds', key)
  438. end
  439. def self.find_by_api_key(key)
  440. Token.find_active_user('api', key)
  441. end
  442. # Makes find_by_mail case-insensitive
  443. def self.find_by_mail(mail)
  444. having_mail(mail).first
  445. end
  446. # Returns true if the default admin account can no longer be used
  447. def self.default_admin_account_changed?
  448. !User.active.find_by_login("admin").try(:check_password?, "admin")
  449. end
  450. def to_s
  451. name
  452. end
  453. LABEL_BY_STATUS = {
  454. STATUS_ANONYMOUS => 'anon',
  455. STATUS_ACTIVE => 'active',
  456. STATUS_REGISTERED => 'registered',
  457. STATUS_LOCKED => 'locked'
  458. }
  459. def css_classes
  460. "user #{LABEL_BY_STATUS[status]}"
  461. end
  462. # Returns the current day according to user's time zone
  463. def today
  464. if time_zone.nil?
  465. Date.today
  466. else
  467. time_zone.today
  468. end
  469. end
  470. # Returns the day of +time+ according to user's time zone
  471. def time_to_date(time)
  472. if time_zone.nil?
  473. time.to_date
  474. else
  475. time.in_time_zone(time_zone).to_date
  476. end
  477. end
  478. def logged?
  479. true
  480. end
  481. def anonymous?
  482. !logged?
  483. end
  484. # Returns user's membership for the given project
  485. # or nil if the user is not a member of project
  486. def membership(project)
  487. project_id = project.is_a?(Project) ? project.id : project
  488. @membership_by_project_id ||= Hash.new {|h, project_id|
  489. h[project_id] = memberships.where(:project_id => project_id).first
  490. }
  491. @membership_by_project_id[project_id]
  492. end
  493. def roles
  494. @roles ||= Role.joins(members: :project).where(["#{Project.table_name}.status <> ?", Project::STATUS_ARCHIVED]).where(Member.arel_table[:user_id].eq(id)).distinct
  495. end
  496. # Returns the user's bult-in role
  497. def builtin_role
  498. @builtin_role ||= Role.non_member
  499. end
  500. # Return user's roles for project
  501. def roles_for_project(project)
  502. # No role on archived projects
  503. return [] if project.nil? || project.archived?
  504. if membership = membership(project)
  505. membership.roles.to_a
  506. elsif project.is_public?
  507. project.override_roles(builtin_role)
  508. else
  509. []
  510. end
  511. end
  512. # Returns a hash of user's projects grouped by roles
  513. # TODO: No longer used, should be deprecated
  514. def projects_by_role
  515. return @projects_by_role if @projects_by_role
  516. result = Hash.new([])
  517. project_ids_by_role.each do |role, ids|
  518. result[role] = Project.where(:id => ids).to_a
  519. end
  520. @projects_by_role = result
  521. end
  522. # Returns a hash of project ids grouped by roles.
  523. # Includes the projects that the user is a member of and the projects
  524. # that grant custom permissions to the builtin groups.
  525. def project_ids_by_role
  526. # Clear project condition for when called from chained scopes
  527. # eg. project.children.visible(user)
  528. Project.unscoped do
  529. return @project_ids_by_role if @project_ids_by_role
  530. group_class = anonymous? ? GroupAnonymous : GroupNonMember
  531. group_id = group_class.pluck(:id).first
  532. members = Member.joins(:project, :member_roles).
  533. where("#{Project.table_name}.status <> 9").
  534. where("#{Member.table_name}.user_id = ? OR (#{Project.table_name}.is_public = ? AND #{Member.table_name}.user_id = ?)", self.id, true, group_id).
  535. pluck(:user_id, :role_id, :project_id)
  536. hash = {}
  537. members.each do |user_id, role_id, project_id|
  538. # Ignore the roles of the builtin group if the user is a member of the project
  539. next if user_id != id && project_ids.include?(project_id)
  540. hash[role_id] ||= []
  541. hash[role_id] << project_id
  542. end
  543. result = Hash.new([])
  544. if hash.present?
  545. roles = Role.where(:id => hash.keys).to_a
  546. hash.each do |role_id, proj_ids|
  547. role = roles.detect {|r| r.id == role_id}
  548. if role
  549. result[role] = proj_ids.uniq
  550. end
  551. end
  552. end
  553. @project_ids_by_role = result
  554. end
  555. end
  556. # Returns the ids of visible projects
  557. def visible_project_ids
  558. @visible_project_ids ||= Project.visible(self).pluck(:id)
  559. end
  560. # Returns the roles that the user is allowed to manage for the given project
  561. def managed_roles(project)
  562. if admin?
  563. @managed_roles ||= Role.givable.to_a
  564. else
  565. membership(project).try(:managed_roles) || []
  566. end
  567. end
  568. # Returns true if user is arg or belongs to arg
  569. def is_or_belongs_to?(arg)
  570. if arg.is_a?(User)
  571. self == arg
  572. elsif arg.is_a?(Group)
  573. arg.users.include?(self)
  574. else
  575. false
  576. end
  577. end
  578. # Return true if the user is allowed to do the specified action on a specific context
  579. # Action can be:
  580. # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
  581. # * a permission Symbol (eg. :edit_project)
  582. # Context can be:
  583. # * a project : returns true if user is allowed to do the specified action on this project
  584. # * an array of projects : returns true if user is allowed on every project
  585. # * nil with options[:global] set : check if user has at least one role allowed for this action,
  586. # or falls back to Non Member / Anonymous permissions depending if the user is logged
  587. def allowed_to?(action, context, options={}, &block)
  588. if context && context.is_a?(Project)
  589. return false unless context.allows_to?(action)
  590. # Admin users are authorized for anything else
  591. return true if admin?
  592. roles = roles_for_project(context)
  593. return false unless roles
  594. roles.any? {|role|
  595. (context.is_public? || role.member?) &&
  596. role.allowed_to?(action) &&
  597. (block_given? ? yield(role, self) : true)
  598. }
  599. elsif context && context.is_a?(Array)
  600. if context.empty?
  601. false
  602. else
  603. # Authorize if user is authorized on every element of the array
  604. context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&)
  605. end
  606. elsif context
  607. raise ArgumentError.new("#allowed_to? context argument must be a Project, an Array of projects or nil")
  608. elsif options[:global]
  609. # Admin users are always authorized
  610. return true if admin?
  611. # authorize if user has at least one role that has this permission
  612. roles = self.roles.to_a | [builtin_role]
  613. roles.any? {|role|
  614. role.allowed_to?(action) &&
  615. (block_given? ? yield(role, self) : true)
  616. }
  617. else
  618. false
  619. end
  620. end
  621. # Is the user allowed to do the specified action on any project?
  622. # See allowed_to? for the actions and valid options.
  623. #
  624. # NB: this method is not used anywhere in the core codebase as of
  625. # 2.5.2, but it's used by many plugins so if we ever want to remove
  626. # it it has to be carefully deprecated for a version or two.
  627. def allowed_to_globally?(action, options={}, &block)
  628. allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
  629. end
  630. def allowed_to_view_all_time_entries?(context)
  631. allowed_to?(:view_time_entries, context) do |role, user|
  632. role.time_entries_visibility == 'all'
  633. end
  634. end
  635. # Returns true if the user is allowed to delete the user's own account
  636. def own_account_deletable?
  637. Setting.unsubscribe? &&
  638. (!admin? || User.active.admin.where("id <> ?", id).exists?)
  639. end
  640. safe_attributes 'firstname',
  641. 'lastname',
  642. 'mail',
  643. 'mail_notification',
  644. 'notified_project_ids',
  645. 'language',
  646. 'custom_field_values',
  647. 'custom_fields',
  648. 'identity_url'
  649. safe_attributes 'login',
  650. :if => lambda {|user, current_user| user.new_record?}
  651. safe_attributes 'status',
  652. 'auth_source_id',
  653. 'generate_password',
  654. 'must_change_passwd',
  655. 'login',
  656. 'admin',
  657. :if => lambda {|user, current_user| current_user.admin?}
  658. safe_attributes 'group_ids',
  659. :if => lambda {|user, current_user| current_user.admin? && !user.new_record?}
  660. # Utility method to help check if a user should be notified about an
  661. # event.
  662. #
  663. # TODO: only supports Issue events currently
  664. def notify_about?(object)
  665. if mail_notification == 'all'
  666. true
  667. elsif mail_notification.blank? || mail_notification == 'none'
  668. false
  669. else
  670. case object
  671. when Issue
  672. case mail_notification
  673. when 'selected', 'only_my_events'
  674. # user receives notifications for created/assigned issues on unselected projects
  675. object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.previous_assignee)
  676. when 'only_assigned'
  677. is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.previous_assignee)
  678. when 'only_owner'
  679. object.author == self
  680. end
  681. when News
  682. # always send to project members except when mail_notification is set to 'none'
  683. true
  684. end
  685. end
  686. end
  687. def self.current=(user)
  688. RequestStore.store[:current_user] = user
  689. end
  690. def self.current
  691. RequestStore.store[:current_user] ||= User.anonymous
  692. end
  693. # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only
  694. # one anonymous user per database.
  695. def self.anonymous
  696. anonymous_user = AnonymousUser.unscoped.find_by(:lastname => 'Anonymous')
  697. if anonymous_user.nil?
  698. anonymous_user = AnonymousUser.unscoped.create(:lastname => 'Anonymous', :firstname => '', :login => '', :status => 0)
  699. raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
  700. end
  701. anonymous_user
  702. end
  703. # Salts all existing unsalted passwords
  704. # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
  705. # This method is used in the SaltPasswords migration and is to be kept as is
  706. def self.salt_unsalted_passwords!
  707. transaction do
  708. User.where("salt IS NULL OR salt = ''").find_each do |user|
  709. next if user.hashed_password.blank?
  710. salt = User.generate_salt
  711. hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
  712. User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password)
  713. end
  714. end
  715. end
  716. protected
  717. def validate_password_length
  718. return if password.blank? && generate_password?
  719. # Password length validation based on setting
  720. if !password.nil? && password.size < Setting.password_min_length.to_i
  721. errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
  722. end
  723. end
  724. def instantiate_email_address
  725. email_address || build_email_address
  726. end
  727. private
  728. def generate_password_if_needed
  729. if generate_password? && auth_source.nil?
  730. length = [Setting.password_min_length.to_i + 2, 10].max
  731. random_password(length)
  732. end
  733. end
  734. # Delete all outstanding password reset tokens on password change.
  735. # Delete the autologin tokens on password change to prohibit session leakage.
  736. # This helps to keep the account secure in case the associated email account
  737. # was compromised.
  738. def destroy_tokens
  739. if saved_change_to_hashed_password? || (saved_change_to_status? && !active?)
  740. tokens = ['recovery', 'autologin', 'session']
  741. Token.where(:user_id => id, :action => tokens).delete_all
  742. end
  743. end
  744. # Removes references that are not handled by associations
  745. # Things that are not deleted are reassociated with the anonymous user
  746. def remove_references_before_destroy
  747. return if self.id.nil?
  748. substitute = User.anonymous
  749. Attachment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  750. Comment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  751. Issue.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  752. Issue.where(['assigned_to_id = ?', id]).update_all('assigned_to_id = NULL')
  753. Journal.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  754. JournalDetail.
  755. where(["property = 'attr' AND prop_key = 'assigned_to_id' AND old_value = ?", id.to_s]).
  756. update_all(['old_value = ?', substitute.id.to_s])
  757. JournalDetail.
  758. where(["property = 'attr' AND prop_key = 'assigned_to_id' AND value = ?", id.to_s]).
  759. update_all(['value = ?', substitute.id.to_s])
  760. Message.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  761. News.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  762. # Remove private queries and keep public ones
  763. ::Query.where('user_id = ? AND visibility = ?', id, ::Query::VISIBILITY_PRIVATE).delete_all
  764. ::Query.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  765. TimeEntry.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  766. Token.where('user_id = ?', id).delete_all
  767. Watcher.where('user_id = ?', id).delete_all
  768. WikiContent.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  769. WikiContent::Version.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  770. end
  771. # Return password digest
  772. def self.hash_password(clear_password)
  773. Digest::SHA1.hexdigest(clear_password || "")
  774. end
  775. # Returns a 128bits random salt as a hex string (32 chars long)
  776. def self.generate_salt
  777. Redmine::Utils.random_hex(16)
  778. end
  779. # Send a security notification to all admins if the user has gained/lost admin privileges
  780. def deliver_security_notification
  781. options = {
  782. field: :field_admin,
  783. value: login,
  784. title: :label_user_plural,
  785. url: {controller: 'users', action: 'index'}
  786. }
  787. deliver = false
  788. if (admin? && saved_change_to_id? && active?) || # newly created admin
  789. (admin? && saved_change_to_admin? && active?) || # regular user became admin
  790. (admin? && saved_change_to_status? && active?) # locked admin became active again
  791. deliver = true
  792. options[:message] = :mail_body_security_notification_add
  793. elsif (admin? && destroyed? && active?) || # active admin user was deleted
  794. (!admin? && saved_change_to_admin? && active?) || # admin is no longer admin
  795. (admin? && saved_change_to_status? && !active?) # admin was locked
  796. deliver = true
  797. options[:message] = :mail_body_security_notification_remove
  798. end
  799. if deliver
  800. users = User.active.where(admin: true).to_a
  801. Mailer.deliver_security_notification(users, User.current, options)
  802. end
  803. end
  804. end
  805. class AnonymousUser < User
  806. validate :validate_anonymous_uniqueness, :on => :create
  807. self.valid_statuses = [STATUS_ANONYMOUS]
  808. def validate_anonymous_uniqueness
  809. # There should be only one AnonymousUser in the database
  810. errors.add :base, 'An anonymous user already exists.' if AnonymousUser.exists?
  811. end
  812. def available_custom_fields
  813. []
  814. end
  815. # Overrides a few properties
  816. def logged?; false end
  817. def admin; false end
  818. def name(*args); I18n.t(:label_user_anonymous) end
  819. def mail=(*args); nil end
  820. def mail; nil end
  821. def time_zone; nil end
  822. def rss_key; nil end
  823. def pref
  824. UserPreference.new(:user => self)
  825. end
  826. # Returns the user's bult-in role
  827. def builtin_role
  828. @builtin_role ||= Role.anonymous
  829. end
  830. def membership(*args)
  831. nil
  832. end
  833. def member_of?(*args)
  834. false
  835. end
  836. # Anonymous user can not be destroyed
  837. def destroy
  838. false
  839. end
  840. protected
  841. def instantiate_email_address
  842. end
  843. end