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

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