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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006-2021 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. ['only_my_events', :label_user_mail_option_only_my_events],
  74. ['only_assigned', :label_user_mail_option_only_assigned],
  75. ['only_owner', :label_user_mail_option_only_owner],
  76. ['none', :label_user_mail_option_none]
  77. ]
  78. has_and_belongs_to_many :groups,
  79. :join_table => "#{table_name_prefix}groups_users#{table_name_suffix}",
  80. :after_add => Proc.new {|user, group| group.user_added(user)},
  81. :after_remove => Proc.new {|user, group| group.user_removed(user)}
  82. has_many :changesets, :dependent => :nullify
  83. has_one :preference, :dependent => :destroy, :class_name => 'UserPreference'
  84. has_one :rss_token, lambda {where "action='feeds'"}, :class_name => 'Token'
  85. has_one :api_token, lambda {where "action='api'"}, :class_name => 'Token'
  86. has_one :email_address, lambda {where :is_default => true}, :autosave => true
  87. has_many :email_addresses, :dependent => :delete_all
  88. belongs_to :auth_source
  89. scope :logged, lambda {where("#{User.table_name}.status <> #{STATUS_ANONYMOUS}")}
  90. scope :status, lambda {|arg| where(arg.blank? ? nil : {:status => arg.to_i})}
  91. acts_as_customizable
  92. attr_accessor :password, :password_confirmation, :generate_password
  93. attr_accessor :last_before_login_on
  94. attr_accessor :remote_ip
  95. LOGIN_LENGTH_LIMIT = 60
  96. MAIL_LENGTH_LIMIT = 60
  97. validates_presence_of :login, :firstname, :lastname, :if => Proc.new {|user| !user.is_a?(AnonymousUser)}
  98. validates_uniqueness_of :login, :if => Proc.new {|user| user.login_changed? && user.login.present?}, :case_sensitive => false
  99. # Login must contain letters, numbers, underscores only
  100. validates_format_of :login, :with => /\A[a-z0-9_\-@\.]*\z/i
  101. validates_length_of :login, :maximum => LOGIN_LENGTH_LIMIT
  102. validates_length_of :firstname, :lastname, :maximum => 30
  103. validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
  104. Setting::PASSWORD_CHAR_CLASSES.each do |k, v|
  105. validates_format_of :password, :with => v, :message => :"must_contain_#{k}", :allow_blank => true, :if => Proc.new {Setting.password_required_char_classes.include?(k)}
  106. end
  107. validate :validate_password_length
  108. validate do
  109. if password_confirmation && password != password_confirmation
  110. errors.add(:password, :confirmation)
  111. end
  112. end
  113. self.valid_statuses = [STATUS_ACTIVE, STATUS_REGISTERED, STATUS_LOCKED]
  114. before_validation :instantiate_email_address
  115. before_create :set_mail_notification
  116. before_save :generate_password_if_needed, :update_hashed_password
  117. before_destroy :remove_references_before_destroy
  118. after_save :update_notified_project_ids, :destroy_tokens, :deliver_security_notification
  119. after_destroy :deliver_security_notification
  120. scope :admin, (lambda do |*args|
  121. admin = args.size > 0 ? !!args.first : true
  122. where(:admin => admin)
  123. end)
  124. scope :in_group, (lambda do |group|
  125. group_id = group.is_a?(Group) ? group.id : group.to_i
  126. 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)
  127. end)
  128. scope :not_in_group, (lambda do |group|
  129. group_id = group.is_a?(Group) ? group.id : group.to_i
  130. 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)
  131. end)
  132. scope :sorted, lambda {order(*User.fields_for_order_statement)}
  133. scope :having_mail, (lambda do |arg|
  134. addresses = Array.wrap(arg).map {|a| a.to_s.downcase}
  135. if addresses.any?
  136. joins(:email_addresses).where("LOWER(#{EmailAddress.table_name}.address) IN (?)", addresses).distinct
  137. else
  138. none
  139. end
  140. end)
  141. def set_mail_notification
  142. self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
  143. true
  144. end
  145. def update_hashed_password
  146. # update hashed_password if password was set
  147. if self.password && self.auth_source_id.blank?
  148. salt_password(password)
  149. end
  150. end
  151. alias :base_reload :reload
  152. def reload(*args)
  153. @name = nil
  154. @roles = nil
  155. @projects_by_role = nil
  156. @project_ids_by_role = nil
  157. @membership_by_project_id = nil
  158. @notified_projects_ids = nil
  159. @notified_projects_ids_changed = false
  160. @builtin_role = nil
  161. @visible_project_ids = nil
  162. @managed_roles = nil
  163. base_reload(*args)
  164. end
  165. def mail
  166. email_address.try(:address)
  167. end
  168. def mail=(arg)
  169. email = email_address || build_email_address
  170. email.address = arg
  171. end
  172. def mail_changed?
  173. email_address.try(:address_changed?)
  174. end
  175. def mails
  176. email_addresses.pluck(:address)
  177. end
  178. # Returns the user that matches provided login and password, or nil
  179. # AuthSource errors are caught, logged and nil is returned.
  180. def self.try_to_login(login, password, active_only=true)
  181. try_to_login!(login, password, active_only)
  182. rescue AuthSourceException => e
  183. logger.error "An error occured when authenticating #{login}: #{e.message}"
  184. nil
  185. end
  186. # Returns the user that matches provided login and password, or nil
  187. # AuthSource errors are passed through.
  188. def self.try_to_login!(login, password, active_only=true)
  189. login = login.to_s.strip
  190. password = password.to_s
  191. # Make sure no one can sign in with an empty login or password
  192. return nil if login.empty? || password.empty?
  193. user = find_by_login(login)
  194. if user
  195. # user is already in local database
  196. return nil unless user.check_password?(password)
  197. return nil if !user.active? && active_only
  198. else
  199. # user is not yet registered, try to authenticate with available sources
  200. attrs = AuthSource.authenticate(login, password)
  201. if attrs
  202. user = new(attrs)
  203. user.login = login
  204. user.language = Setting.default_language
  205. if user.save
  206. user.reload
  207. logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
  208. end
  209. end
  210. end
  211. user.update_last_login_on! if user && !user.new_record? && user.active?
  212. user
  213. rescue => text
  214. raise text
  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. (
  338. Setting.twofa_required? ||
  339. (Setting.twofa_optional? && groups.any?(&:twofa_required?))
  340. ) && !twofa_active?
  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 RSS key (a 40 chars long string), used to access feeds
  362. def rss_key
  363. if rss_token.nil?
  364. create_rss_token(:action => 'feeds')
  365. end
  366. rss_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. scope.update_all(:updated_on => Time.now) == 1
  408. end
  409. # Return an array of project ids for which the user has explicitly turned mail notifications on
  410. def notified_projects_ids
  411. @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
  412. end
  413. def notified_project_ids=(ids)
  414. @notified_projects_ids_changed = true
  415. @notified_projects_ids = ids.map(&:to_i).uniq.select {|n| n > 0}
  416. end
  417. # Updates per project notifications (after_save callback)
  418. def update_notified_project_ids
  419. if @notified_projects_ids_changed
  420. ids = (mail_notification == 'selected' ? Array.wrap(notified_projects_ids).reject(&:blank?) : [])
  421. members.update_all(:mail_notification => false)
  422. members.where(:project_id => ids).update_all(:mail_notification => true) if ids.any?
  423. end
  424. end
  425. private :update_notified_project_ids
  426. def valid_notification_options
  427. self.class.valid_notification_options(self)
  428. end
  429. # Only users that belong to more than 1 project can select projects for which they are notified
  430. def self.valid_notification_options(user=nil)
  431. # Note that @user.membership.size would fail since AR ignores
  432. # :include association option when doing a count
  433. if user.nil? || user.memberships.length < 1
  434. MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
  435. else
  436. MAIL_NOTIFICATION_OPTIONS
  437. end
  438. end
  439. # Find a user account by matching the exact login and then a case-insensitive
  440. # version. Exact matches will be given priority.
  441. def self.find_by_login(login)
  442. login = Redmine::CodesetUtil.replace_invalid_utf8(login.to_s)
  443. if login.present?
  444. # First look for an exact match
  445. user = where(:login => login).detect {|u| u.login == login}
  446. unless user
  447. # Fail over to case-insensitive if none was found
  448. user = find_by("LOWER(login) = ?", login.downcase)
  449. end
  450. user
  451. end
  452. end
  453. def self.find_by_rss_key(key)
  454. Token.find_active_user('feeds', key)
  455. end
  456. def self.find_by_api_key(key)
  457. Token.find_active_user('api', key)
  458. end
  459. # Makes find_by_mail case-insensitive
  460. def self.find_by_mail(mail)
  461. having_mail(mail).first
  462. end
  463. # Returns true if the default admin account can no longer be used
  464. def self.default_admin_account_changed?
  465. !User.active.find_by_login("admin").try(:check_password?, "admin")
  466. end
  467. def to_s
  468. name
  469. end
  470. LABEL_BY_STATUS = {
  471. STATUS_ANONYMOUS => 'anon',
  472. STATUS_ACTIVE => 'active',
  473. STATUS_REGISTERED => 'registered',
  474. STATUS_LOCKED => 'locked'
  475. }
  476. def css_classes
  477. "user #{LABEL_BY_STATUS[status]}"
  478. end
  479. # Returns the current day according to user's time zone
  480. def today
  481. if time_zone.nil?
  482. Date.today
  483. else
  484. time_zone.today
  485. end
  486. end
  487. # Returns the day of +time+ according to user's time zone
  488. def time_to_date(time)
  489. self.convert_time_to_user_timezone(time).to_date
  490. end
  491. def convert_time_to_user_timezone(time)
  492. if self.time_zone
  493. time.in_time_zone(self.time_zone)
  494. else
  495. time.utc? ? time.localtime : time
  496. end
  497. end
  498. def logged?
  499. true
  500. end
  501. def anonymous?
  502. !logged?
  503. end
  504. # Returns user's membership for the given project
  505. # or nil if the user is not a member of project
  506. def membership(project)
  507. project_id = project.is_a?(Project) ? project.id : project
  508. @membership_by_project_id ||=
  509. Hash.new do |h, project_id|
  510. h[project_id] = memberships.where(:project_id => project_id).first
  511. end
  512. @membership_by_project_id[project_id]
  513. end
  514. def roles
  515. @roles ||=
  516. Role.joins(members: :project).
  517. where(["#{Project.table_name}.status <> ?", Project::STATUS_ARCHIVED]).
  518. where(Member.arel_table[:user_id].eq(id)).distinct
  519. end
  520. # Returns the user's bult-in role
  521. def builtin_role
  522. @builtin_role ||= Role.non_member
  523. end
  524. # Return user's roles for project
  525. def roles_for_project(project)
  526. # No role on archived projects
  527. return [] if project.nil? || project.archived?
  528. if membership = membership(project)
  529. membership.roles.to_a
  530. elsif project.is_public?
  531. project.override_roles(builtin_role)
  532. else
  533. []
  534. end
  535. end
  536. # Returns a hash of user's projects grouped by roles
  537. # TODO: No longer used, should be deprecated
  538. def projects_by_role
  539. return @projects_by_role if @projects_by_role
  540. result = Hash.new([])
  541. project_ids_by_role.each do |role, ids|
  542. result[role] = Project.where(:id => ids).to_a
  543. end
  544. @projects_by_role = result
  545. end
  546. # Returns a hash of project ids grouped by roles.
  547. # Includes the projects that the user is a member of and the projects
  548. # that grant custom permissions to the builtin groups.
  549. def project_ids_by_role
  550. # Clear project condition for when called from chained scopes
  551. # eg. project.children.visible(user)
  552. Project.unscoped do
  553. return @project_ids_by_role if @project_ids_by_role
  554. group_class = anonymous? ? GroupAnonymous.unscoped : GroupNonMember.unscoped
  555. group_id = group_class.pick(:id)
  556. members = Member.joins(:project, :member_roles).
  557. where("#{Project.table_name}.status <> 9").
  558. where("#{Member.table_name}.user_id = ? OR (#{Project.table_name}.is_public = ? AND #{Member.table_name}.user_id = ?)", self.id, true, group_id).
  559. pluck(:user_id, :role_id, :project_id)
  560. hash = {}
  561. members.each do |user_id, role_id, project_id|
  562. # Ignore the roles of the builtin group if the user is a member of the project
  563. next if user_id != id && project_ids.include?(project_id)
  564. hash[role_id] ||= []
  565. hash[role_id] << project_id
  566. end
  567. result = Hash.new([])
  568. if hash.present?
  569. roles = Role.where(:id => hash.keys).to_a
  570. hash.each do |role_id, proj_ids|
  571. role = roles.detect {|r| r.id == role_id}
  572. if role
  573. result[role] = proj_ids.uniq
  574. end
  575. end
  576. end
  577. @project_ids_by_role = result
  578. end
  579. end
  580. # Returns the ids of visible projects
  581. def visible_project_ids
  582. @visible_project_ids ||= Project.visible(self).pluck(:id)
  583. end
  584. # Returns the roles that the user is allowed to manage for the given project
  585. def managed_roles(project)
  586. if admin?
  587. @managed_roles ||= Role.givable.to_a
  588. else
  589. membership(project).try(:managed_roles) || []
  590. end
  591. end
  592. # Returns true if user is arg or belongs to arg
  593. def is_or_belongs_to?(arg)
  594. if arg.is_a?(User)
  595. self == arg
  596. elsif arg.is_a?(Group)
  597. arg.users.include?(self)
  598. else
  599. false
  600. end
  601. end
  602. # Return true if the user is allowed to do the specified action on a specific context
  603. # Action can be:
  604. # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
  605. # * a permission Symbol (eg. :edit_project)
  606. # Context can be:
  607. # * a project : returns true if user is allowed to do the specified action on this project
  608. # * an array of projects : returns true if user is allowed on every project
  609. # * nil with options[:global] set : check if user has at least one role allowed for this action,
  610. # or falls back to Non Member / Anonymous permissions depending if the user is logged
  611. def allowed_to?(action, context, options={}, &block)
  612. if context && context.is_a?(Project)
  613. return false unless context.allows_to?(action)
  614. # Admin users are authorized for anything else
  615. return true if admin?
  616. roles = roles_for_project(context)
  617. return false unless roles
  618. roles.any? do |role|
  619. (context.is_public? || role.member?) &&
  620. role.allowed_to?(action) &&
  621. (block_given? ? yield(role, self) : true)
  622. end
  623. elsif context && context.is_a?(Array)
  624. if context.empty?
  625. false
  626. else
  627. # Authorize if user is authorized on every element of the array
  628. context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&)
  629. end
  630. elsif context
  631. raise ArgumentError.new("#allowed_to? context argument must be a Project, an Array of projects or nil")
  632. elsif options[:global]
  633. # Admin users are always authorized
  634. return true if admin?
  635. # authorize if user has at least one role that has this permission
  636. roles = self.roles.to_a | [builtin_role]
  637. roles.any? do |role|
  638. role.allowed_to?(action) &&
  639. (block_given? ? yield(role, self) : true)
  640. end
  641. else
  642. false
  643. end
  644. end
  645. # Is the user allowed to do the specified action on any project?
  646. # See allowed_to? for the actions and valid options.
  647. #
  648. # NB: this method is not used anywhere in the core codebase as of
  649. # 2.5.2, but it's used by many plugins so if we ever want to remove
  650. # it it has to be carefully deprecated for a version or two.
  651. def allowed_to_globally?(action, options={}, &block)
  652. allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
  653. end
  654. def allowed_to_view_all_time_entries?(context)
  655. allowed_to?(:view_time_entries, context) do |role, user|
  656. role.time_entries_visibility == 'all'
  657. end
  658. end
  659. # Returns true if the user is allowed to delete the user's own account
  660. def own_account_deletable?
  661. Setting.unsubscribe? &&
  662. (!admin? || User.active.admin.where("id <> ?", id).exists?)
  663. end
  664. safe_attributes(
  665. 'firstname',
  666. 'lastname',
  667. 'mail',
  668. 'mail_notification',
  669. 'notified_project_ids',
  670. 'language',
  671. 'custom_field_values',
  672. 'custom_fields')
  673. safe_attributes(
  674. 'login',
  675. :if => lambda {|user, current_user| user.new_record?})
  676. safe_attributes(
  677. 'status',
  678. 'auth_source_id',
  679. 'generate_password',
  680. 'must_change_passwd',
  681. 'login',
  682. 'admin',
  683. :if => lambda {|user, current_user| current_user.admin?})
  684. safe_attributes(
  685. 'group_ids',
  686. :if => lambda {|user, current_user| current_user.admin? && !user.new_record?})
  687. # Utility method to help check if a user should be notified about an
  688. # event.
  689. #
  690. # TODO: only supports Issue events currently
  691. def notify_about?(object)
  692. if mail_notification == 'all'
  693. true
  694. elsif mail_notification.blank? || mail_notification == 'none'
  695. false
  696. else
  697. case object
  698. when Issue
  699. case mail_notification
  700. when 'selected', 'only_my_events'
  701. # user receives notifications for created/assigned issues on unselected projects
  702. object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.previous_assignee)
  703. when 'only_assigned'
  704. is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.previous_assignee)
  705. when 'only_owner'
  706. object.author == self
  707. end
  708. when News
  709. # always send to project members except when mail_notification is set to 'none'
  710. true
  711. end
  712. end
  713. end
  714. def notify_about_high_priority_issues?
  715. self.pref.notify_about_high_priority_issues
  716. end
  717. def self.current=(user)
  718. RequestStore.store[:current_user] = user
  719. end
  720. def self.current
  721. RequestStore.store[:current_user] ||= User.anonymous
  722. end
  723. # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only
  724. # one anonymous user per database.
  725. def self.anonymous
  726. anonymous_user = AnonymousUser.unscoped.find_by(:lastname => 'Anonymous')
  727. if anonymous_user.nil?
  728. anonymous_user = AnonymousUser.unscoped.create(:lastname => 'Anonymous', :firstname => '', :login => '', :status => 0)
  729. raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
  730. end
  731. anonymous_user
  732. end
  733. # Salts all existing unsalted passwords
  734. # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
  735. # This method is used in the SaltPasswords migration and is to be kept as is
  736. def self.salt_unsalted_passwords!
  737. transaction do
  738. User.where("salt IS NULL OR salt = ''").find_each do |user|
  739. next if user.hashed_password.blank?
  740. salt = User.generate_salt
  741. hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
  742. User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password)
  743. end
  744. end
  745. end
  746. def bookmarked_project_ids
  747. project_ids = []
  748. bookmarked_project_ids = self.pref[:bookmarked_project_ids]
  749. project_ids = bookmarked_project_ids.split(',') unless bookmarked_project_ids.nil?
  750. project_ids.map(&:to_i)
  751. end
  752. protected
  753. def validate_password_length
  754. return if password.blank? && generate_password?
  755. # Password length validation based on setting
  756. if !password.nil? && password.size < Setting.password_min_length.to_i
  757. errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
  758. end
  759. end
  760. def instantiate_email_address
  761. email_address || build_email_address
  762. end
  763. private
  764. def generate_password_if_needed
  765. if generate_password? && auth_source.nil?
  766. length = [Setting.password_min_length.to_i + 2, 10].max
  767. random_password(length)
  768. end
  769. end
  770. # Delete all outstanding password reset tokens on password change.
  771. # Delete the autologin tokens on password change to prohibit session leakage.
  772. # This helps to keep the account secure in case the associated email account
  773. # was compromised.
  774. def destroy_tokens
  775. if saved_change_to_hashed_password? || (saved_change_to_status? && !active?) || (saved_change_to_twofa_scheme? && twofa_scheme.present?)
  776. tokens = ['recovery', 'autologin', 'session']
  777. Token.where(:user_id => id, :action => tokens).delete_all
  778. end
  779. end
  780. # Removes references that are not handled by associations
  781. # Things that are not deleted are reassociated with the anonymous user
  782. def remove_references_before_destroy
  783. return if self.id.nil?
  784. substitute = User.anonymous
  785. Attachment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  786. Comment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  787. Issue.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  788. Issue.where(['assigned_to_id = ?', id]).update_all('assigned_to_id = NULL')
  789. Journal.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  790. JournalDetail.
  791. where(["property = 'attr' AND prop_key = 'assigned_to_id' AND old_value = ?", id.to_s]).
  792. update_all(['old_value = ?', substitute.id.to_s])
  793. JournalDetail.
  794. where(["property = 'attr' AND prop_key = 'assigned_to_id' AND value = ?", id.to_s]).
  795. update_all(['value = ?', substitute.id.to_s])
  796. Message.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  797. News.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  798. # Remove private queries and keep public ones
  799. ::Query.where('user_id = ? AND visibility = ?', id, ::Query::VISIBILITY_PRIVATE).delete_all
  800. ::Query.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  801. TimeEntry.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  802. Token.where('user_id = ?', id).delete_all
  803. Watcher.where('user_id = ?', id).delete_all
  804. WikiContent.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  805. WikiContentVersion.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  806. user_custom_field_ids = CustomField.where(field_format: 'user').ids
  807. if user_custom_field_ids.any?
  808. CustomValue.where(custom_field_id: user_custom_field_ids, value: self.id.to_s).delete_all
  809. end
  810. end
  811. # Singleton class method is public
  812. class << self
  813. # Return password digest
  814. def hash_password(clear_password)
  815. Digest::SHA1.hexdigest(clear_password || "")
  816. end
  817. # Returns a 128bits random salt as a hex string (32 chars long)
  818. def generate_salt
  819. Redmine::Utils.random_hex(16)
  820. end
  821. end
  822. # Send a security notification to all admins if the user has gained/lost admin privileges
  823. def deliver_security_notification
  824. options = {
  825. field: :field_admin,
  826. value: login,
  827. title: :label_user_plural,
  828. url: {controller: 'users', action: 'index'}
  829. }
  830. deliver = false
  831. if (admin? && saved_change_to_id? && active?) || # newly created admin
  832. (admin? && saved_change_to_admin? && active?) || # regular user became admin
  833. (admin? && saved_change_to_status? && active?) # locked admin became active again
  834. deliver = true
  835. options[:message] = :mail_body_security_notification_add
  836. elsif (admin? && destroyed? && active?) || # active admin user was deleted
  837. (!admin? && saved_change_to_admin? && active?) || # admin is no longer admin
  838. (admin? && saved_change_to_status? && !active?) # admin was locked
  839. deliver = true
  840. options[:message] = :mail_body_security_notification_remove
  841. end
  842. if deliver
  843. users = User.active.where(admin: true).to_a
  844. Mailer.deliver_security_notification(users, User.current, options)
  845. end
  846. end
  847. end