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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001
  1. # frozen_string_literal: true
  2. # Redmine - project management software
  3. # Copyright (C) 2006- 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 :atom_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 = 254
  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, :maximum => 30
  103. validates_length_of :lastname, :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. # Returns the user that matches provided login and password, or nil
  180. # AuthSource errors are caught, logged and nil is returned.
  181. def self.try_to_login(login, password, active_only=true)
  182. try_to_login!(login, password, active_only)
  183. rescue AuthSourceException => e
  184. logger.error "An error occured when authenticating #{login}: #{e.message}"
  185. nil
  186. end
  187. # Returns the user that matches provided login and password, or nil
  188. # AuthSource errors are passed through.
  189. def self.try_to_login!(login, password, active_only=true)
  190. login = login.to_s.strip
  191. password = password.to_s
  192. # Make sure no one can sign in with an empty login or password
  193. return nil if login.empty? || password.empty?
  194. user = find_by_login(login)
  195. if user
  196. # user is already in local database
  197. return nil unless user.check_password?(password)
  198. return nil if !user.active? && active_only
  199. else
  200. # user is not yet registered, try to authenticate with available sources
  201. attrs = AuthSource.authenticate(login, password)
  202. if attrs
  203. user = new(attrs)
  204. user.login = login
  205. user.language = Setting.default_language
  206. if user.save
  207. user.reload
  208. logger.info("User '#{user.login}' created from external auth source: #{user.auth_source.type} - #{user.auth_source.name}") if logger && user.auth_source
  209. end
  210. end
  211. end
  212. user.update_last_login_on! if user && !user.new_record? && user.active?
  213. user
  214. end
  215. # Returns the user who matches the given autologin +key+ or nil
  216. def self.try_to_autologin(key)
  217. user = Token.find_active_user('autologin', key, Setting.autologin.to_i)
  218. if user
  219. user.update_last_login_on!
  220. user
  221. end
  222. end
  223. def self.name_formatter(formatter = nil)
  224. USER_FORMATS[formatter || Setting.user_format] || USER_FORMATS[:firstname_lastname]
  225. end
  226. # Returns an array of fields names than can be used to make an order statement for users
  227. # according to how user names are displayed
  228. # Examples:
  229. #
  230. # User.fields_for_order_statement => ['users.login', 'users.id']
  231. # User.fields_for_order_statement('authors') => ['authors.login', 'authors.id']
  232. def self.fields_for_order_statement(table=nil)
  233. table ||= table_name
  234. name_formatter[:order].map {|field| "#{table}.#{field}"}
  235. end
  236. # Return user's full name for display
  237. def name(formatter = nil)
  238. f = self.class.name_formatter(formatter)
  239. if formatter
  240. eval('"' + f[:string] + '"')
  241. else
  242. @name ||= eval('"' + f[:string] + '"')
  243. end
  244. end
  245. def active?
  246. self.status == STATUS_ACTIVE
  247. end
  248. def registered?
  249. self.status == STATUS_REGISTERED
  250. end
  251. def locked?
  252. self.status == STATUS_LOCKED
  253. end
  254. def activate
  255. self.status = STATUS_ACTIVE
  256. end
  257. def register
  258. self.status = STATUS_REGISTERED
  259. end
  260. def lock
  261. self.status = STATUS_LOCKED
  262. end
  263. def activate!
  264. update_attribute(:status, STATUS_ACTIVE)
  265. end
  266. def register!
  267. update_attribute(:status, STATUS_REGISTERED)
  268. end
  269. def lock!
  270. update_attribute(:status, STATUS_LOCKED)
  271. end
  272. def update_last_login_on!
  273. return if last_login_on.present? && last_login_on >= 1.minute.ago
  274. update_column(:last_login_on, Time.now)
  275. end
  276. # Returns true if +clear_password+ is the correct user's password, otherwise false
  277. def check_password?(clear_password)
  278. if auth_source_id.present?
  279. auth_source.authenticate(self.login, clear_password)
  280. else
  281. User.hash_password("#{salt}#{User.hash_password clear_password}") == hashed_password
  282. end
  283. end
  284. # Generates a random salt and computes hashed_password for +clear_password+
  285. # The hashed password is stored in the following form: SHA1(salt + SHA1(password))
  286. def salt_password(clear_password)
  287. self.salt = User.generate_salt
  288. self.hashed_password = User.hash_password("#{salt}#{User.hash_password clear_password}")
  289. self.passwd_changed_on = Time.now.change(:usec => 0)
  290. end
  291. # Does the backend storage allow this user to change their password?
  292. def change_password_allowed?
  293. auth_source.nil? ? true : auth_source.allow_password_changes?
  294. end
  295. # Returns true if the user password has expired
  296. def password_expired?
  297. period = Setting.password_max_age.to_i
  298. if period.zero?
  299. false
  300. else
  301. changed_on = self.passwd_changed_on || Time.at(0)
  302. changed_on < period.days.ago
  303. end
  304. end
  305. def must_change_password?
  306. (must_change_passwd? || password_expired?) && change_password_allowed?
  307. end
  308. def generate_password?
  309. ActiveRecord::Type::Boolean.new.deserialize(generate_password)
  310. end
  311. # Generate and set a random password on given length
  312. def random_password(length=40)
  313. chars_list = [('A'..'Z').to_a, ('a'..'z').to_a, ('0'..'9').to_a]
  314. # auto-generated passwords contain special characters only when admins
  315. # require users to use passwords which contains special characters
  316. if Setting.password_required_char_classes.include?('special_chars')
  317. chars_list << ("\x20".."\x7e").to_a.select {|c| c =~ Setting::PASSWORD_CHAR_CLASSES['special_chars']}
  318. end
  319. chars_list.each {|v| v.reject! {|c| %(0O1l|'"`*).include?(c)}}
  320. password = +''
  321. chars_list.each do |chars|
  322. password << chars[SecureRandom.random_number(chars.size)]
  323. length -= 1
  324. end
  325. chars = chars_list.flatten
  326. length.times {password << chars[SecureRandom.random_number(chars.size)]}
  327. password = password.split('').shuffle(random: SecureRandom).join
  328. self.password = password
  329. self.password_confirmation = password
  330. self
  331. end
  332. def twofa_active?
  333. twofa_scheme.present?
  334. end
  335. def must_activate_twofa?
  336. return false if twofa_active?
  337. return true if Setting.twofa_required?
  338. return true if Setting.twofa_required_for_administrators? && admin?
  339. return true if Setting.twofa_optional? && groups.any?(&:twofa_required?)
  340. end
  341. def pref
  342. self.preference ||= UserPreference.new(:user => self)
  343. end
  344. def time_zone
  345. @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
  346. end
  347. def force_default_language?
  348. Setting.force_default_language_for_loggedin?
  349. end
  350. def language
  351. if force_default_language?
  352. Setting.default_language
  353. else
  354. super
  355. end
  356. end
  357. def wants_comments_in_reverse_order?
  358. self.pref[:comments_sorting] == 'desc'
  359. end
  360. # Return user's ATOM key (a 40 chars long string), used to access feeds
  361. def atom_key
  362. if atom_token.nil?
  363. create_atom_token(:action => 'feeds')
  364. end
  365. atom_token.value
  366. end
  367. # Return user's API key (a 40 chars long string), used to access the API
  368. def api_key
  369. if api_token.nil?
  370. create_api_token(:action => 'api')
  371. end
  372. api_token.value
  373. end
  374. # Generates a new session token and returns its value
  375. def generate_session_token
  376. token = Token.create!(:user_id => id, :action => 'session')
  377. token.value
  378. end
  379. def delete_session_token(value)
  380. Token.where(:user_id => id, :action => 'session', :value => value).delete_all
  381. end
  382. # Generates a new autologin token and returns its value
  383. def generate_autologin_token
  384. token = Token.create!(:user_id => id, :action => 'autologin')
  385. token.value
  386. end
  387. def delete_autologin_token(value)
  388. Token.where(:user_id => id, :action => 'autologin', :value => value).delete_all
  389. end
  390. def twofa_totp_key
  391. read_ciphered_attribute(:twofa_totp_key)
  392. end
  393. def twofa_totp_key=(key)
  394. write_ciphered_attribute(:twofa_totp_key, key)
  395. end
  396. # Returns true if token is a valid session token for the user whose id is user_id
  397. def self.verify_session_token(user_id, token)
  398. return false if user_id.blank? || token.blank?
  399. scope = Token.where(:user_id => user_id, :value => token.to_s, :action => 'session')
  400. if Setting.session_lifetime?
  401. scope = scope.where("created_on > ?", Setting.session_lifetime.to_i.minutes.ago)
  402. end
  403. if Setting.session_timeout?
  404. scope = scope.where("updated_on > ?", Setting.session_timeout.to_i.minutes.ago)
  405. end
  406. last_updated = scope.maximum(:updated_on)
  407. if last_updated.nil?
  408. false
  409. elsif last_updated <= 1.minute.ago
  410. scope.update_all(:updated_on => Time.now) == 1
  411. else
  412. true
  413. end
  414. end
  415. # Return an array of project ids for which the user has explicitly turned mail notifications on
  416. def notified_projects_ids
  417. @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
  418. end
  419. def notified_project_ids=(ids)
  420. @notified_projects_ids_changed = true
  421. @notified_projects_ids = ids.map(&:to_i).uniq.select {|n| n > 0}
  422. end
  423. # Updates per project notifications (after_save callback)
  424. def update_notified_project_ids
  425. if @notified_projects_ids_changed
  426. ids = (mail_notification == 'selected' ? Array.wrap(notified_projects_ids).reject(&:blank?) : [])
  427. members.update_all(:mail_notification => false)
  428. members.where(:project_id => ids).update_all(:mail_notification => true) if ids.any?
  429. end
  430. end
  431. private :update_notified_project_ids
  432. def valid_notification_options
  433. self.class.valid_notification_options(self)
  434. end
  435. # Only users that belong to more than 1 project can select projects for which they are notified
  436. def self.valid_notification_options(user=nil)
  437. # Note that @user.membership.size would fail since AR ignores
  438. # :include association option when doing a count
  439. if user.nil? || user.memberships.length < 1
  440. MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
  441. else
  442. MAIL_NOTIFICATION_OPTIONS
  443. end
  444. end
  445. # Find a user account by matching the exact login and then a case-insensitive
  446. # version. Exact matches will be given priority.
  447. def self.find_by_login(login)
  448. login = Redmine::CodesetUtil.replace_invalid_utf8(login.to_s)
  449. if login.present?
  450. # First look for an exact match
  451. user = where(:login => login).detect {|u| u.login == login}
  452. unless user
  453. # Fail over to case-insensitive if none was found
  454. user = find_by("LOWER(login) = ?", login.downcase)
  455. end
  456. user
  457. end
  458. end
  459. def self.find_by_atom_key(key)
  460. Token.find_active_user('feeds', key)
  461. end
  462. def self.find_by_api_key(key)
  463. Token.find_active_user('api', key)
  464. end
  465. # Makes find_by_mail case-insensitive
  466. def self.find_by_mail(mail)
  467. having_mail(mail).first
  468. end
  469. # Returns true if the default admin account can no longer be used
  470. def self.default_admin_account_changed?
  471. !User.active.find_by_login("admin").try(:check_password?, "admin")
  472. end
  473. def to_s
  474. name
  475. end
  476. LABEL_BY_STATUS = {
  477. STATUS_ANONYMOUS => 'anon',
  478. STATUS_ACTIVE => 'active',
  479. STATUS_REGISTERED => 'registered',
  480. STATUS_LOCKED => 'locked'
  481. }
  482. def css_classes
  483. "user #{LABEL_BY_STATUS[status]}"
  484. end
  485. # Returns the current day according to user's time zone
  486. def today
  487. if time_zone.nil?
  488. Date.today
  489. else
  490. time_zone.today
  491. end
  492. end
  493. # Returns the day of +time+ according to user's time zone
  494. def time_to_date(time)
  495. self.convert_time_to_user_timezone(time).to_date
  496. end
  497. def convert_time_to_user_timezone(time)
  498. if self.time_zone
  499. time.in_time_zone(self.time_zone)
  500. else
  501. time.utc? ? time.localtime : time
  502. end
  503. end
  504. def logged?
  505. true
  506. end
  507. def anonymous?
  508. !logged?
  509. end
  510. # Returns user's membership for the given project
  511. # or nil if the user is not a member of project
  512. def membership(project)
  513. project_id = project.is_a?(Project) ? project.id : project
  514. @membership_by_project_id ||=
  515. Hash.new do |h, project_id|
  516. h[project_id] = memberships.where(:project_id => project_id).first
  517. end
  518. @membership_by_project_id[project_id]
  519. end
  520. def roles
  521. @roles ||=
  522. Role.joins(members: :project).
  523. where(["#{Project.table_name}.status <> ?", Project::STATUS_ARCHIVED]).
  524. where(Member.arel_table[:user_id].eq(id)).distinct
  525. if @roles.blank?
  526. group_class = anonymous? ? GroupAnonymous : GroupNonMember
  527. @roles = Role.joins(members: :project).
  528. where(["#{Project.table_name}.status <> ? AND #{Project.table_name}.is_public = ?", Project::STATUS_ARCHIVED, true]).
  529. where(Member.arel_table[:user_id].eq(group_class.first.id)).distinct
  530. end
  531. @roles
  532. end
  533. # Returns the user's bult-in role
  534. def builtin_role
  535. @builtin_role ||= Role.non_member
  536. end
  537. # Return user's roles for project
  538. def roles_for_project(project)
  539. # No role on archived projects
  540. return [] if project.nil? || project.archived?
  541. if membership = membership(project)
  542. membership.roles.to_a
  543. elsif project.is_public?
  544. project.override_roles(builtin_role)
  545. else
  546. []
  547. end
  548. end
  549. # Returns a hash of user's projects grouped by roles
  550. # TODO: No longer used, should be deprecated
  551. def projects_by_role
  552. return @projects_by_role if @projects_by_role
  553. result = Hash.new([])
  554. project_ids_by_role.each do |role, ids|
  555. result[role] = Project.where(:id => ids).to_a
  556. end
  557. @projects_by_role = result
  558. end
  559. # Returns a hash of project ids grouped by roles.
  560. # Includes the projects that the user is a member of and the projects
  561. # that grant custom permissions to the builtin groups.
  562. def project_ids_by_role
  563. # Clear project condition for when called from chained scopes
  564. # eg. project.children.visible(user)
  565. Project.unscoped do
  566. return @project_ids_by_role if @project_ids_by_role
  567. group_class = anonymous? ? GroupAnonymous.unscoped : GroupNonMember.unscoped
  568. group_id = group_class.pick(:id)
  569. members = Member.joins(:project, :member_roles).
  570. where("#{Project.table_name}.status <> 9").
  571. where("#{Member.table_name}.user_id = ? OR (#{Project.table_name}.is_public = ? AND #{Member.table_name}.user_id = ?)", self.id, true, group_id).
  572. pluck(:user_id, :role_id, :project_id)
  573. hash = {}
  574. members.each do |user_id, role_id, project_id|
  575. # Ignore the roles of the builtin group if the user is a member of the project
  576. next if user_id != id && project_ids.include?(project_id)
  577. hash[role_id] ||= []
  578. hash[role_id] << project_id
  579. end
  580. result = Hash.new([])
  581. if hash.present?
  582. roles = Role.where(:id => hash.keys).to_a
  583. hash.each do |role_id, proj_ids|
  584. role = roles.detect {|r| r.id == role_id}
  585. if role
  586. result[role] = proj_ids.uniq
  587. end
  588. end
  589. end
  590. @project_ids_by_role = result
  591. end
  592. end
  593. # Returns the ids of visible projects
  594. def visible_project_ids
  595. @visible_project_ids ||= Project.visible(self).pluck(:id)
  596. end
  597. # Returns the roles that the user is allowed to manage for the given project
  598. def managed_roles(project)
  599. if admin?
  600. @managed_roles ||= Role.givable.to_a
  601. else
  602. membership(project).try(:managed_roles) || []
  603. end
  604. end
  605. # Returns true if user is arg or belongs to arg
  606. def is_or_belongs_to?(arg)
  607. if arg.is_a?(User)
  608. self == arg
  609. elsif arg.is_a?(Group)
  610. arg.users.include?(self)
  611. else
  612. false
  613. end
  614. end
  615. # Return true if the user is allowed to do the specified action on a specific context
  616. # Action can be:
  617. # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
  618. # * a permission Symbol (eg. :edit_project)
  619. # Context can be:
  620. # * a project : returns true if user is allowed to do the specified action on this project
  621. # * an array of projects : returns true if user is allowed on every project
  622. # * nil with options[:global] set : check if user has at least one role allowed for this action,
  623. # or falls back to Non Member / Anonymous permissions depending if the user is logged
  624. def allowed_to?(action, context, options={}, &block)
  625. if context && context.is_a?(Project)
  626. return false unless context.allows_to?(action)
  627. # Admin users are authorized for anything else
  628. return true if admin?
  629. roles = roles_for_project(context)
  630. return false unless roles
  631. roles.any? do |role|
  632. (context.is_public? || role.member?) &&
  633. role.allowed_to?(action) &&
  634. (block ? yield(role, self) : true)
  635. end
  636. elsif context && context.is_a?(Array)
  637. if context.empty?
  638. false
  639. else
  640. # Authorize if user is authorized on every element of the array
  641. context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&)
  642. end
  643. elsif context
  644. raise ArgumentError.new("#allowed_to? context argument must be a Project, an Array of projects or nil")
  645. elsif options[:global]
  646. # Admin users are always authorized
  647. return true if admin?
  648. # authorize if user has at least one role that has this permission
  649. roles = self.roles.to_a | [builtin_role]
  650. roles.any? do |role|
  651. role.allowed_to?(action) &&
  652. (block ? yield(role, self) : true)
  653. end
  654. else
  655. false
  656. end
  657. end
  658. # Is the user allowed to do the specified action on any project?
  659. # See allowed_to? for the actions and valid options.
  660. #
  661. # NB: this method is not used anywhere in the core codebase as of
  662. # 2.5.2, but it's used by many plugins so if we ever want to remove
  663. # it it has to be carefully deprecated for a version or two.
  664. def allowed_to_globally?(action, options={}, &block)
  665. allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
  666. end
  667. def allowed_to_view_all_time_entries?(context)
  668. allowed_to?(:view_time_entries, context) do |role, user|
  669. role.time_entries_visibility == 'all'
  670. end
  671. end
  672. # Returns true if the user is allowed to delete the user's own account
  673. def own_account_deletable?
  674. Setting.unsubscribe? &&
  675. (!admin? || User.active.admin.where("id <> ?", id).exists?)
  676. end
  677. safe_attributes(
  678. 'firstname',
  679. 'lastname',
  680. 'mail',
  681. 'mail_notification',
  682. 'notified_project_ids',
  683. 'language',
  684. 'custom_field_values',
  685. 'custom_fields')
  686. safe_attributes(
  687. 'login',
  688. :if => lambda {|user, current_user| user.new_record?})
  689. safe_attributes(
  690. 'status',
  691. 'auth_source_id',
  692. 'generate_password',
  693. 'must_change_passwd',
  694. 'login',
  695. 'admin',
  696. :if => lambda {|user, current_user| current_user.admin?})
  697. safe_attributes(
  698. 'group_ids',
  699. :if => lambda {|user, current_user| current_user.admin? && !user.new_record?})
  700. # Utility method to help check if a user should be notified about an
  701. # event.
  702. #
  703. # TODO: only supports Issue events currently
  704. def notify_about?(object)
  705. if mail_notification == 'all'
  706. true
  707. elsif mail_notification.blank? || mail_notification == 'none'
  708. false
  709. else
  710. case object
  711. when Issue
  712. case mail_notification
  713. when 'selected', 'only_my_events'
  714. # user receives notifications for created/assigned issues on unselected projects
  715. object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.previous_assignee)
  716. when 'only_assigned'
  717. is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.previous_assignee)
  718. when 'only_owner'
  719. object.author == self
  720. end
  721. when News
  722. # always send to project members except when mail_notification is set to 'none'
  723. true
  724. end
  725. end
  726. end
  727. def notify_about_high_priority_issues?
  728. self.pref.notify_about_high_priority_issues
  729. end
  730. class CurrentUser < ActiveSupport::CurrentAttributes
  731. attribute :user
  732. end
  733. def self.current=(user)
  734. CurrentUser.user = user
  735. end
  736. def self.current
  737. CurrentUser.user ||= User.anonymous
  738. end
  739. # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only
  740. # one anonymous user per database.
  741. def self.anonymous
  742. anonymous_user = AnonymousUser.unscoped.find_by(:lastname => 'Anonymous')
  743. if anonymous_user.nil?
  744. anonymous_user = AnonymousUser.unscoped.create(:lastname => 'Anonymous', :firstname => '', :login => '', :status => 0)
  745. raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
  746. end
  747. anonymous_user
  748. end
  749. # Salts all existing unsalted passwords
  750. # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
  751. # This method is used in the SaltPasswords migration and is to be kept as is
  752. def self.salt_unsalted_passwords!
  753. transaction do
  754. User.where("salt IS NULL OR salt = ''").find_each do |user|
  755. next if user.hashed_password.blank?
  756. salt = User.generate_salt
  757. hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
  758. User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password)
  759. end
  760. end
  761. end
  762. def bookmarked_project_ids
  763. project_ids = []
  764. bookmarked_project_ids = self.pref[:bookmarked_project_ids]
  765. project_ids = bookmarked_project_ids.split(',') unless bookmarked_project_ids.nil?
  766. project_ids.map(&:to_i)
  767. end
  768. def self.prune(age)
  769. User.where("created_on < ? AND status = ?", Time.now - age, STATUS_REGISTERED).destroy_all
  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?) || (saved_change_to_twofa_scheme? && twofa_scheme.present?)
  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. WikiContentVersion.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  825. user_custom_field_ids = CustomField.where(field_format: 'user').ids
  826. if user_custom_field_ids.any?
  827. CustomValue.where(custom_field_id: user_custom_field_ids, value: self.id.to_s).delete_all
  828. end
  829. end
  830. # Singleton class method is public
  831. class << self
  832. # Return password digest
  833. def hash_password(clear_password)
  834. Digest::SHA1.hexdigest(clear_password || "")
  835. end
  836. # Returns a 128bits random salt as a hex string (32 chars long)
  837. def generate_salt
  838. Redmine::Utils.random_hex(16)
  839. end
  840. end
  841. # Send a security notification to all admins if the user has gained/lost admin privileges
  842. def deliver_security_notification
  843. options = {
  844. field: :field_admin,
  845. value: login,
  846. title: :label_user_plural,
  847. url: {controller: 'users', action: 'index'}
  848. }
  849. deliver = false
  850. if (admin? && saved_change_to_id? && active?) || # newly created admin
  851. (admin? && saved_change_to_admin? && active?) || # regular user became admin
  852. (admin? && saved_change_to_status? && active?) # locked admin became active again
  853. deliver = true
  854. options[:message] = :mail_body_security_notification_add
  855. elsif (admin? && destroyed? && active?) || # active admin user was deleted
  856. (!admin? && saved_change_to_admin? && active?) || # admin is no longer admin
  857. (admin? && saved_change_to_status? && !active?) # admin was locked
  858. deliver = true
  859. options[:message] = :mail_body_security_notification_remove
  860. end
  861. if deliver
  862. users = User.active.where(admin: true).to_a
  863. Mailer.deliver_security_notification(users, User.current, options)
  864. end
  865. end
  866. end