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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045
  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_length_of :identity_url, maximum: 255
  104. validates_inclusion_of :mail_notification, :in => MAIL_NOTIFICATION_OPTIONS.collect(&:first), :allow_blank => true
  105. Setting::PASSWORD_CHAR_CLASSES.each do |k, v|
  106. validates_format_of :password, :with => v, :message => :"must_contain_#{k}", :allow_blank => true, :if => Proc.new {Setting.password_required_char_classes.include?(k)}
  107. end
  108. validate :validate_password_length
  109. validate do
  110. if password_confirmation && password != password_confirmation
  111. errors.add(:password, :confirmation)
  112. end
  113. end
  114. self.valid_statuses = [STATUS_ACTIVE, STATUS_REGISTERED, STATUS_LOCKED]
  115. before_validation :instantiate_email_address
  116. before_create :set_mail_notification
  117. before_save :generate_password_if_needed, :update_hashed_password
  118. before_destroy :remove_references_before_destroy
  119. after_save :update_notified_project_ids, :destroy_tokens, :deliver_security_notification
  120. after_destroy :deliver_security_notification
  121. scope :admin, (lambda do |*args|
  122. admin = args.size > 0 ? !!args.first : true
  123. where(:admin => admin)
  124. end)
  125. scope :in_group, (lambda do |group|
  126. group_id = group.is_a?(Group) ? group.id : group.to_i
  127. 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)
  128. end)
  129. scope :not_in_group, (lambda do |group|
  130. group_id = group.is_a?(Group) ? group.id : group.to_i
  131. 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)
  132. end)
  133. scope :sorted, lambda {order(*User.fields_for_order_statement)}
  134. scope :having_mail, (lambda do |arg|
  135. addresses = Array.wrap(arg).map {|a| a.to_s.downcase}
  136. if addresses.any?
  137. joins(:email_addresses).where("LOWER(#{EmailAddress.table_name}.address) IN (?)", addresses).distinct
  138. else
  139. none
  140. end
  141. end)
  142. def set_mail_notification
  143. self.mail_notification = Setting.default_notification_option if self.mail_notification.blank?
  144. true
  145. end
  146. def update_hashed_password
  147. # update hashed_password if password was set
  148. if self.password && self.auth_source_id.blank?
  149. salt_password(password)
  150. end
  151. end
  152. alias :base_reload :reload
  153. def reload(*args)
  154. @name = nil
  155. @roles = nil
  156. @projects_by_role = nil
  157. @project_ids_by_role = nil
  158. @membership_by_project_id = nil
  159. @notified_projects_ids = nil
  160. @notified_projects_ids_changed = false
  161. @builtin_role = nil
  162. @visible_project_ids = nil
  163. @managed_roles = nil
  164. base_reload(*args)
  165. end
  166. def mail
  167. email_address.try(:address)
  168. end
  169. def mail=(arg)
  170. email = email_address || build_email_address
  171. email.address = arg
  172. end
  173. def mail_changed?
  174. email_address.try(:address_changed?)
  175. end
  176. def mails
  177. email_addresses.pluck(:address)
  178. end
  179. def self.find_or_initialize_by_identity_url(url)
  180. user = where(:identity_url => url).first
  181. unless user
  182. user = User.new
  183. user.identity_url = url
  184. end
  185. user
  186. end
  187. def identity_url=(url)
  188. if url.blank?
  189. write_attribute(:identity_url, '')
  190. else
  191. begin
  192. write_attribute(:identity_url, OpenIdAuthentication.normalize_identifier(url))
  193. rescue OpenIdAuthentication::InvalidOpenId
  194. # Invalid url, don't save
  195. end
  196. end
  197. self.read_attribute(:identity_url)
  198. end
  199. # Returns the user that matches provided login and password, or nil
  200. # AuthSource errors are caught, logged and nil is returned.
  201. def self.try_to_login(login, password, active_only=true)
  202. try_to_login!(login, password, active_only)
  203. rescue AuthSourceException => e
  204. logger.error "An error occured when authenticating #{login}: #{e.message}"
  205. nil
  206. end
  207. # Returns the user that matches provided login and password, or nil
  208. # AuthSource errors are passed through.
  209. def self.try_to_login!(login, password, active_only=true)
  210. login = login.to_s.strip
  211. password = password.to_s
  212. # Make sure no one can sign in with an empty login or password
  213. return nil if login.empty? || password.empty?
  214. user = find_by_login(login)
  215. if user
  216. # user is already in local database
  217. return nil unless user.check_password?(password)
  218. return nil if !user.active? && active_only
  219. else
  220. # user is not yet registered, try to authenticate with available sources
  221. attrs = AuthSource.authenticate(login, password)
  222. if attrs
  223. user = new(attrs)
  224. user.login = login
  225. user.language = Setting.default_language
  226. if user.save
  227. user.reload
  228. logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
  229. end
  230. end
  231. end
  232. user.update_last_login_on! if user && !user.new_record? && user.active?
  233. user
  234. rescue => text
  235. raise text
  236. end
  237. # Returns the user who matches the given autologin +key+ or nil
  238. def self.try_to_autologin(key)
  239. user = Token.find_active_user('autologin', key, Setting.autologin.to_i)
  240. if user
  241. user.update_last_login_on!
  242. user
  243. end
  244. end
  245. def self.name_formatter(formatter = nil)
  246. USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
  247. end
  248. # Returns an array of fields names than can be used to make an order statement for users
  249. # according to how user names are displayed
  250. # Examples:
  251. #
  252. # User.fields_for_order_statement => ['users.login', 'users.id']
  253. # User.fields_for_order_statement('authors') => ['authors.login', 'authors.id']
  254. def self.fields_for_order_statement(table=nil)
  255. table ||= table_name
  256. name_formatter[:order].map {|field| "#{table}.#{field}"}
  257. end
  258. # Return user's full name for display
  259. def name(formatter = nil)
  260. f = self.class.name_formatter(formatter)
  261. if formatter
  262. eval('"' + f[:string] + '"')
  263. else
  264. @name ||= eval('"' + f[:string] + '"')
  265. end
  266. end
  267. def active?
  268. self.status == STATUS_ACTIVE
  269. end
  270. def registered?
  271. self.status == STATUS_REGISTERED
  272. end
  273. def locked?
  274. self.status == STATUS_LOCKED
  275. end
  276. def activate
  277. self.status = STATUS_ACTIVE
  278. end
  279. def register
  280. self.status = STATUS_REGISTERED
  281. end
  282. def lock
  283. self.status = STATUS_LOCKED
  284. end
  285. def activate!
  286. update_attribute(:status, STATUS_ACTIVE)
  287. end
  288. def register!
  289. update_attribute(:status, STATUS_REGISTERED)
  290. end
  291. def lock!
  292. update_attribute(:status, STATUS_LOCKED)
  293. end
  294. def update_last_login_on!
  295. return if last_login_on.present? && last_login_on >= 1.minute.ago
  296. update_column(:last_login_on, Time.now)
  297. end
  298. # Returns true if +clear_password+ is the correct user's password, otherwise false
  299. def check_password?(clear_password)
  300. if auth_source_id.present?
  301. auth_source.authenticate(self.login, clear_password)
  302. else
  303. User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
  304. end
  305. end
  306. # Generates a random salt and computes hashed_password for +clear_password+
  307. # The hashed password is stored in the following form: SHA1(salt + SHA1(password))
  308. def salt_password(clear_password)
  309. self.salt = User.generate_salt
  310. self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
  311. self.passwd_changed_on = Time.now.change(:usec => 0)
  312. end
  313. # Does the backend storage allow this user to change their password?
  314. def change_password_allowed?
  315. auth_source.nil? ? true : auth_source.allow_password_changes?
  316. end
  317. # Returns true if the user password has expired
  318. def password_expired?
  319. period = Setting.password_max_age.to_i
  320. if period.zero?
  321. false
  322. else
  323. changed_on = self.passwd_changed_on || Time.at(0)
  324. changed_on < period.days.ago
  325. end
  326. end
  327. def must_change_password?
  328. (must_change_passwd? || password_expired?) && change_password_allowed?
  329. end
  330. def generate_password?
  331. ActiveRecord::Type::Boolean.new.deserialize(generate_password)
  332. end
  333. # Generate and set a random password on given length
  334. def random_password(length=40)
  335. chars_list = [('A'..'Z').to_a, ('a'..'z').to_a, ('0'..'9').to_a]
  336. # auto-generated passwords contain special characters only when admins
  337. # require users to use passwords which contains special characters
  338. if Setting.password_required_char_classes.include?('special_chars')
  339. chars_list << ("\x20".."\x7e").to_a.select {|c| c =~ Setting::PASSWORD_CHAR_CLASSES['special_chars']}
  340. end
  341. chars_list.each {|v| v.reject! {|c| %(0O1l|'"`*).include?(c)}}
  342. password = +''
  343. chars_list.each do |chars|
  344. password << chars[SecureRandom.random_number(chars.size)]
  345. length -= 1
  346. end
  347. chars = chars_list.flatten
  348. length.times {password << chars[SecureRandom.random_number(chars.size)]}
  349. password = password.split('').shuffle(random: SecureRandom).join
  350. self.password = password
  351. self.password_confirmation = password
  352. self
  353. end
  354. def twofa_active?
  355. twofa_scheme.present?
  356. end
  357. def must_activate_twofa?
  358. Setting.twofa == '2' && !twofa_active?
  359. end
  360. def pref
  361. self.preference ||= UserPreference.new(:user => self)
  362. end
  363. def time_zone
  364. @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
  365. end
  366. def force_default_language?
  367. Setting.force_default_language_for_loggedin?
  368. end
  369. def language
  370. if force_default_language?
  371. Setting.default_language
  372. else
  373. super
  374. end
  375. end
  376. def wants_comments_in_reverse_order?
  377. self.pref[:comments_sorting] == 'desc'
  378. end
  379. # Return user's RSS key (a 40 chars long string), used to access feeds
  380. def rss_key
  381. if rss_token.nil?
  382. create_rss_token(:action => 'feeds')
  383. end
  384. rss_token.value
  385. end
  386. # Return user's API key (a 40 chars long string), used to access the API
  387. def api_key
  388. if api_token.nil?
  389. create_api_token(:action => 'api')
  390. end
  391. api_token.value
  392. end
  393. # Generates a new session token and returns its value
  394. def generate_session_token
  395. token = Token.create!(:user_id => id, :action => 'session')
  396. token.value
  397. end
  398. def delete_session_token(value)
  399. Token.where(:user_id => id, :action => 'session', :value => value).delete_all
  400. end
  401. # Generates a new autologin token and returns its value
  402. def generate_autologin_token
  403. token = Token.create!(:user_id => id, :action => 'autologin')
  404. token.value
  405. end
  406. def delete_autologin_token(value)
  407. Token.where(:user_id => id, :action => 'autologin', :value => value).delete_all
  408. end
  409. def twofa_totp_key
  410. read_ciphered_attribute(:twofa_totp_key)
  411. end
  412. def twofa_totp_key=(key)
  413. write_ciphered_attribute(:twofa_totp_key, key)
  414. end
  415. # Returns true if token is a valid session token for the user whose id is user_id
  416. def self.verify_session_token(user_id, token)
  417. return false if user_id.blank? || token.blank?
  418. scope = Token.where(:user_id => user_id, :value => token.to_s, :action => 'session')
  419. if Setting.session_lifetime?
  420. scope = scope.where("created_on > ?", Setting.session_lifetime.to_i.minutes.ago)
  421. end
  422. if Setting.session_timeout?
  423. scope = scope.where("updated_on > ?", Setting.session_timeout.to_i.minutes.ago)
  424. end
  425. scope.update_all(:updated_on => Time.now) == 1
  426. end
  427. # Return an array of project ids for which the user has explicitly turned mail notifications on
  428. def notified_projects_ids
  429. @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
  430. end
  431. def notified_project_ids=(ids)
  432. @notified_projects_ids_changed = true
  433. @notified_projects_ids = ids.map(&:to_i).uniq.select {|n| n > 0}
  434. end
  435. # Updates per project notifications (after_save callback)
  436. def update_notified_project_ids
  437. if @notified_projects_ids_changed
  438. ids = (mail_notification == 'selected' ? Array.wrap(notified_projects_ids).reject(&:blank?) : [])
  439. members.update_all(:mail_notification => false)
  440. members.where(:project_id => ids).update_all(:mail_notification => true) if ids.any?
  441. end
  442. end
  443. private :update_notified_project_ids
  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_rss_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. end
  538. # Returns the user's bult-in role
  539. def builtin_role
  540. @builtin_role ||= Role.non_member
  541. end
  542. # Return user's roles for project
  543. def roles_for_project(project)
  544. # No role on archived projects
  545. return [] if project.nil? || project.archived?
  546. if membership = membership(project)
  547. membership.roles.to_a
  548. elsif project.is_public?
  549. project.override_roles(builtin_role)
  550. else
  551. []
  552. end
  553. end
  554. # Returns a hash of user's projects grouped by roles
  555. # TODO: No longer used, should be deprecated
  556. def projects_by_role
  557. return @projects_by_role if @projects_by_role
  558. result = Hash.new([])
  559. project_ids_by_role.each do |role, ids|
  560. result[role] = Project.where(:id => ids).to_a
  561. end
  562. @projects_by_role = result
  563. end
  564. # Returns a hash of project ids grouped by roles.
  565. # Includes the projects that the user is a member of and the projects
  566. # that grant custom permissions to the builtin groups.
  567. def project_ids_by_role
  568. # Clear project condition for when called from chained scopes
  569. # eg. project.children.visible(user)
  570. Project.unscoped do
  571. return @project_ids_by_role if @project_ids_by_role
  572. group_class = anonymous? ? GroupAnonymous.unscoped : GroupNonMember.unscoped
  573. group_id = group_class.pick(:id)
  574. members = Member.joins(:project, :member_roles).
  575. where("#{Project.table_name}.status <> 9").
  576. where("#{Member.table_name}.user_id = ? OR (#{Project.table_name}.is_public = ? AND #{Member.table_name}.user_id = ?)", self.id, true, group_id).
  577. pluck(:user_id, :role_id, :project_id)
  578. hash = {}
  579. members.each do |user_id, role_id, project_id|
  580. # Ignore the roles of the builtin group if the user is a member of the project
  581. next if user_id != id && project_ids.include?(project_id)
  582. hash[role_id] ||= []
  583. hash[role_id] << project_id
  584. end
  585. result = Hash.new([])
  586. if hash.present?
  587. roles = Role.where(:id => hash.keys).to_a
  588. hash.each do |role_id, proj_ids|
  589. role = roles.detect {|r| r.id == role_id}
  590. if role
  591. result[role] = proj_ids.uniq
  592. end
  593. end
  594. end
  595. @project_ids_by_role = result
  596. end
  597. end
  598. # Returns the ids of visible projects
  599. def visible_project_ids
  600. @visible_project_ids ||= Project.visible(self).pluck(:id)
  601. end
  602. # Returns the roles that the user is allowed to manage for the given project
  603. def managed_roles(project)
  604. if admin?
  605. @managed_roles ||= Role.givable.to_a
  606. else
  607. membership(project).try(:managed_roles) || []
  608. end
  609. end
  610. # Returns true if user is arg or belongs to arg
  611. def is_or_belongs_to?(arg)
  612. if arg.is_a?(User)
  613. self == arg
  614. elsif arg.is_a?(Group)
  615. arg.users.include?(self)
  616. else
  617. false
  618. end
  619. end
  620. # Return true if the user is allowed to do the specified action on a specific context
  621. # Action can be:
  622. # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
  623. # * a permission Symbol (eg. :edit_project)
  624. # Context can be:
  625. # * a project : returns true if user is allowed to do the specified action on this project
  626. # * an array of projects : returns true if user is allowed on every project
  627. # * nil with options[:global] set : check if user has at least one role allowed for this action,
  628. # or falls back to Non Member / Anonymous permissions depending if the user is logged
  629. def allowed_to?(action, context, options={}, &block)
  630. if context && context.is_a?(Project)
  631. return false unless context.allows_to?(action)
  632. # Admin users are authorized for anything else
  633. return true if admin?
  634. roles = roles_for_project(context)
  635. return false unless roles
  636. roles.any? do |role|
  637. (context.is_public? || role.member?) &&
  638. role.allowed_to?(action) &&
  639. (block_given? ? yield(role, self) : true)
  640. end
  641. elsif context && context.is_a?(Array)
  642. if context.empty?
  643. false
  644. else
  645. # Authorize if user is authorized on every element of the array
  646. context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&)
  647. end
  648. elsif context
  649. raise ArgumentError.new("#allowed_to? context argument must be a Project, an Array of projects or nil")
  650. elsif options[:global]
  651. # Admin users are always authorized
  652. return true if admin?
  653. # authorize if user has at least one role that has this permission
  654. roles = self.roles.to_a | [builtin_role]
  655. roles.any? do |role|
  656. role.allowed_to?(action) &&
  657. (block_given? ? yield(role, self) : true)
  658. end
  659. else
  660. false
  661. end
  662. end
  663. # Is the user allowed to do the specified action on any project?
  664. # See allowed_to? for the actions and valid options.
  665. #
  666. # NB: this method is not used anywhere in the core codebase as of
  667. # 2.5.2, but it's used by many plugins so if we ever want to remove
  668. # it it has to be carefully deprecated for a version or two.
  669. def allowed_to_globally?(action, options={}, &block)
  670. allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
  671. end
  672. def allowed_to_view_all_time_entries?(context)
  673. allowed_to?(:view_time_entries, context) do |role, user|
  674. role.time_entries_visibility == 'all'
  675. end
  676. end
  677. # Returns true if the user is allowed to delete the user's own account
  678. def own_account_deletable?
  679. Setting.unsubscribe? &&
  680. (!admin? || User.active.admin.where("id <> ?", id).exists?)
  681. end
  682. safe_attributes(
  683. 'firstname',
  684. 'lastname',
  685. 'mail',
  686. 'mail_notification',
  687. 'notified_project_ids',
  688. 'language',
  689. 'custom_field_values',
  690. 'custom_fields',
  691. 'identity_url')
  692. safe_attributes(
  693. 'login',
  694. :if => lambda {|user, current_user| user.new_record?})
  695. safe_attributes(
  696. 'status',
  697. 'auth_source_id',
  698. 'generate_password',
  699. 'must_change_passwd',
  700. 'login',
  701. 'admin',
  702. :if => lambda {|user, current_user| current_user.admin?})
  703. safe_attributes(
  704. 'group_ids',
  705. :if => lambda {|user, current_user| current_user.admin? && !user.new_record?})
  706. # Utility method to help check if a user should be notified about an
  707. # event.
  708. #
  709. # TODO: only supports Issue events currently
  710. def notify_about?(object)
  711. if mail_notification == 'all'
  712. true
  713. elsif mail_notification.blank? || mail_notification == 'none'
  714. false
  715. else
  716. case object
  717. when Issue
  718. case mail_notification
  719. when 'selected', 'only_my_events'
  720. # user receives notifications for created/assigned issues on unselected projects
  721. object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.previous_assignee)
  722. when 'only_assigned'
  723. is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.previous_assignee)
  724. when 'only_owner'
  725. object.author == self
  726. end
  727. when News
  728. # always send to project members except when mail_notification is set to 'none'
  729. true
  730. end
  731. end
  732. end
  733. def notify_about_high_priority_issues?
  734. self.pref.notify_about_high_priority_issues
  735. end
  736. def self.current=(user)
  737. RequestStore.store[:current_user] = user
  738. end
  739. def self.current
  740. RequestStore.store[:current_user] ||= User.anonymous
  741. end
  742. # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only
  743. # one anonymous user per database.
  744. def self.anonymous
  745. anonymous_user = AnonymousUser.unscoped.find_by(:lastname => 'Anonymous')
  746. if anonymous_user.nil?
  747. anonymous_user = AnonymousUser.unscoped.create(:lastname => 'Anonymous', :firstname => '', :login => '', :status => 0)
  748. raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
  749. end
  750. anonymous_user
  751. end
  752. # Salts all existing unsalted passwords
  753. # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
  754. # This method is used in the SaltPasswords migration and is to be kept as is
  755. def self.salt_unsalted_passwords!
  756. transaction do
  757. User.where("salt IS NULL OR salt = ''").find_each do |user|
  758. next if user.hashed_password.blank?
  759. salt = User.generate_salt
  760. hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
  761. User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password)
  762. end
  763. end
  764. end
  765. def bookmarked_project_ids
  766. project_ids = []
  767. bookmarked_project_ids = self.pref[:bookmarked_project_ids]
  768. project_ids = bookmarked_project_ids.split(',') unless bookmarked_project_ids.nil?
  769. project_ids.map(&:to_i)
  770. end
  771. protected
  772. def validate_password_length
  773. return if password.blank? && generate_password?
  774. # Password length validation based on setting
  775. if !password.nil? && password.size < Setting.password_min_length.to_i
  776. errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
  777. end
  778. end
  779. def instantiate_email_address
  780. email_address || build_email_address
  781. end
  782. private
  783. def generate_password_if_needed
  784. if generate_password? && auth_source.nil?
  785. length = [Setting.password_min_length.to_i + 2, 10].max
  786. random_password(length)
  787. end
  788. end
  789. # Delete all outstanding password reset tokens on password change.
  790. # Delete the autologin tokens on password change to prohibit session leakage.
  791. # This helps to keep the account secure in case the associated email account
  792. # was compromised.
  793. def destroy_tokens
  794. if saved_change_to_hashed_password? || (saved_change_to_status? && !active?)
  795. tokens = ['recovery', 'autologin', 'session']
  796. Token.where(:user_id => id, :action => tokens).delete_all
  797. end
  798. end
  799. # Removes references that are not handled by associations
  800. # Things that are not deleted are reassociated with the anonymous user
  801. def remove_references_before_destroy
  802. return if self.id.nil?
  803. substitute = User.anonymous
  804. Attachment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  805. Comment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  806. Issue.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  807. Issue.where(['assigned_to_id = ?', id]).update_all('assigned_to_id = NULL')
  808. Journal.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  809. JournalDetail.
  810. where(["property = 'attr' AND prop_key = 'assigned_to_id' AND old_value = ?", id.to_s]).
  811. update_all(['old_value = ?', substitute.id.to_s])
  812. JournalDetail.
  813. where(["property = 'attr' AND prop_key = 'assigned_to_id' AND value = ?", id.to_s]).
  814. update_all(['value = ?', substitute.id.to_s])
  815. Message.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  816. News.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  817. # Remove private queries and keep public ones
  818. ::Query.where('user_id = ? AND visibility = ?', id, ::Query::VISIBILITY_PRIVATE).delete_all
  819. ::Query.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  820. TimeEntry.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  821. Token.where('user_id = ?', id).delete_all
  822. Watcher.where('user_id = ?', id).delete_all
  823. WikiContent.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  824. WikiContent::Version.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  825. end
  826. # Singleton class method is public
  827. class << self
  828. # Return password digest
  829. def hash_password(clear_password)
  830. Digest::SHA1.hexdigest(clear_password || "")
  831. end
  832. # Returns a 128bits random salt as a hex string (32 chars long)
  833. def generate_salt
  834. Redmine::Utils.random_hex(16)
  835. end
  836. end
  837. # Send a security notification to all admins if the user has gained/lost admin privileges
  838. def deliver_security_notification
  839. options = {
  840. field: :field_admin,
  841. value: login,
  842. title: :label_user_plural,
  843. url: {controller: 'users', action: 'index'}
  844. }
  845. deliver = false
  846. if (admin? && saved_change_to_id? && active?) || # newly created admin
  847. (admin? && saved_change_to_admin? && active?) || # regular user became admin
  848. (admin? && saved_change_to_status? && active?) # locked admin became active again
  849. deliver = true
  850. options[:message] = :mail_body_security_notification_add
  851. elsif (admin? && destroyed? && active?) || # active admin user was deleted
  852. (!admin? && saved_change_to_admin? && active?) || # admin is no longer admin
  853. (admin? && saved_change_to_status? && !active?) # admin was locked
  854. deliver = true
  855. options[:message] = :mail_body_security_notification_remove
  856. end
  857. if deliver
  858. users = User.active.where(admin: true).to_a
  859. Mailer.deliver_security_notification(users, User.current, options)
  860. end
  861. end
  862. end
  863. class AnonymousUser < User
  864. validate :validate_anonymous_uniqueness, :on => :create
  865. self.valid_statuses = [STATUS_ANONYMOUS]
  866. def validate_anonymous_uniqueness
  867. # There should be only one AnonymousUser in the database
  868. errors.add :base, 'An anonymous user already exists.' if AnonymousUser.unscoped.exists?
  869. end
  870. def available_custom_fields
  871. []
  872. end
  873. # Overrides a few properties
  874. def logged?; false end
  875. def admin; false end
  876. def name(*args); I18n.t(:label_user_anonymous) end
  877. def mail=(*args); nil end
  878. def mail; nil end
  879. def time_zone; nil end
  880. def rss_key; nil end
  881. def pref
  882. UserPreference.new(:user => self)
  883. end
  884. # Returns the user's bult-in role
  885. def builtin_role
  886. @builtin_role ||= Role.anonymous
  887. end
  888. def membership(*args)
  889. nil
  890. end
  891. def member_of?(*args)
  892. false
  893. end
  894. # Anonymous user can not be destroyed
  895. def destroy
  896. false
  897. end
  898. protected
  899. def instantiate_email_address
  900. end
  901. end