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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052
  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. (
  359. Setting.twofa_required? ||
  360. (Setting.twofa_optional? && groups.any?(&:twofa_required?))
  361. ) && !twofa_active?
  362. end
  363. def pref
  364. self.preference ||= UserPreference.new(:user => self)
  365. end
  366. def time_zone
  367. @time_zone ||= (self.pref.time_zone.blank? ? nil : ActiveSupport::TimeZone[self.pref.time_zone])
  368. end
  369. def force_default_language?
  370. Setting.force_default_language_for_loggedin?
  371. end
  372. def language
  373. if force_default_language?
  374. Setting.default_language
  375. else
  376. super
  377. end
  378. end
  379. def wants_comments_in_reverse_order?
  380. self.pref[:comments_sorting] == 'desc'
  381. end
  382. # Return user's RSS key (a 40 chars long string), used to access feeds
  383. def rss_key
  384. if rss_token.nil?
  385. create_rss_token(:action => 'feeds')
  386. end
  387. rss_token.value
  388. end
  389. # Return user's API key (a 40 chars long string), used to access the API
  390. def api_key
  391. if api_token.nil?
  392. create_api_token(:action => 'api')
  393. end
  394. api_token.value
  395. end
  396. # Generates a new session token and returns its value
  397. def generate_session_token
  398. token = Token.create!(:user_id => id, :action => 'session')
  399. token.value
  400. end
  401. def delete_session_token(value)
  402. Token.where(:user_id => id, :action => 'session', :value => value).delete_all
  403. end
  404. # Generates a new autologin token and returns its value
  405. def generate_autologin_token
  406. token = Token.create!(:user_id => id, :action => 'autologin')
  407. token.value
  408. end
  409. def delete_autologin_token(value)
  410. Token.where(:user_id => id, :action => 'autologin', :value => value).delete_all
  411. end
  412. def twofa_totp_key
  413. read_ciphered_attribute(:twofa_totp_key)
  414. end
  415. def twofa_totp_key=(key)
  416. write_ciphered_attribute(:twofa_totp_key, key)
  417. end
  418. # Returns true if token is a valid session token for the user whose id is user_id
  419. def self.verify_session_token(user_id, token)
  420. return false if user_id.blank? || token.blank?
  421. scope = Token.where(:user_id => user_id, :value => token.to_s, :action => 'session')
  422. if Setting.session_lifetime?
  423. scope = scope.where("created_on > ?", Setting.session_lifetime.to_i.minutes.ago)
  424. end
  425. if Setting.session_timeout?
  426. scope = scope.where("updated_on > ?", Setting.session_timeout.to_i.minutes.ago)
  427. end
  428. scope.update_all(:updated_on => Time.now) == 1
  429. end
  430. # Return an array of project ids for which the user has explicitly turned mail notifications on
  431. def notified_projects_ids
  432. @notified_projects_ids ||= memberships.select {|m| m.mail_notification?}.collect(&:project_id)
  433. end
  434. def notified_project_ids=(ids)
  435. @notified_projects_ids_changed = true
  436. @notified_projects_ids = ids.map(&:to_i).uniq.select {|n| n > 0}
  437. end
  438. # Updates per project notifications (after_save callback)
  439. def update_notified_project_ids
  440. if @notified_projects_ids_changed
  441. ids = (mail_notification == 'selected' ? Array.wrap(notified_projects_ids).reject(&:blank?) : [])
  442. members.update_all(:mail_notification => false)
  443. members.where(:project_id => ids).update_all(:mail_notification => true) if ids.any?
  444. end
  445. end
  446. private :update_notified_project_ids
  447. def valid_notification_options
  448. self.class.valid_notification_options(self)
  449. end
  450. # Only users that belong to more than 1 project can select projects for which they are notified
  451. def self.valid_notification_options(user=nil)
  452. # Note that @user.membership.size would fail since AR ignores
  453. # :include association option when doing a count
  454. if user.nil? || user.memberships.length < 1
  455. MAIL_NOTIFICATION_OPTIONS.reject {|option| option.first == 'selected'}
  456. else
  457. MAIL_NOTIFICATION_OPTIONS
  458. end
  459. end
  460. # Find a user account by matching the exact login and then a case-insensitive
  461. # version. Exact matches will be given priority.
  462. def self.find_by_login(login)
  463. login = Redmine::CodesetUtil.replace_invalid_utf8(login.to_s)
  464. if login.present?
  465. # First look for an exact match
  466. user = where(:login => login).detect {|u| u.login == login}
  467. unless user
  468. # Fail over to case-insensitive if none was found
  469. user = find_by("LOWER(login) = ?", login.downcase)
  470. end
  471. user
  472. end
  473. end
  474. def self.find_by_rss_key(key)
  475. Token.find_active_user('feeds', key)
  476. end
  477. def self.find_by_api_key(key)
  478. Token.find_active_user('api', key)
  479. end
  480. # Makes find_by_mail case-insensitive
  481. def self.find_by_mail(mail)
  482. having_mail(mail).first
  483. end
  484. # Returns true if the default admin account can no longer be used
  485. def self.default_admin_account_changed?
  486. !User.active.find_by_login("admin").try(:check_password?, "admin")
  487. end
  488. def to_s
  489. name
  490. end
  491. LABEL_BY_STATUS = {
  492. STATUS_ANONYMOUS => 'anon',
  493. STATUS_ACTIVE => 'active',
  494. STATUS_REGISTERED => 'registered',
  495. STATUS_LOCKED => 'locked'
  496. }
  497. def css_classes
  498. "user #{LABEL_BY_STATUS[status]}"
  499. end
  500. # Returns the current day according to user's time zone
  501. def today
  502. if time_zone.nil?
  503. Date.today
  504. else
  505. time_zone.today
  506. end
  507. end
  508. # Returns the day of +time+ according to user's time zone
  509. def time_to_date(time)
  510. self.convert_time_to_user_timezone(time).to_date
  511. end
  512. def convert_time_to_user_timezone(time)
  513. if self.time_zone
  514. time.in_time_zone(self.time_zone)
  515. else
  516. time.utc? ? time.localtime : time
  517. end
  518. end
  519. def logged?
  520. true
  521. end
  522. def anonymous?
  523. !logged?
  524. end
  525. # Returns user's membership for the given project
  526. # or nil if the user is not a member of project
  527. def membership(project)
  528. project_id = project.is_a?(Project) ? project.id : project
  529. @membership_by_project_id ||=
  530. Hash.new do |h, project_id|
  531. h[project_id] = memberships.where(:project_id => project_id).first
  532. end
  533. @membership_by_project_id[project_id]
  534. end
  535. def roles
  536. @roles ||=
  537. Role.joins(members: :project).
  538. where(["#{Project.table_name}.status <> ?", Project::STATUS_ARCHIVED]).
  539. where(Member.arel_table[:user_id].eq(id)).distinct
  540. end
  541. # Returns the user's bult-in role
  542. def builtin_role
  543. @builtin_role ||= Role.non_member
  544. end
  545. # Return user's roles for project
  546. def roles_for_project(project)
  547. # No role on archived projects
  548. return [] if project.nil? || project.archived?
  549. if membership = membership(project)
  550. membership.roles.to_a
  551. elsif project.is_public?
  552. project.override_roles(builtin_role)
  553. else
  554. []
  555. end
  556. end
  557. # Returns a hash of user's projects grouped by roles
  558. # TODO: No longer used, should be deprecated
  559. def projects_by_role
  560. return @projects_by_role if @projects_by_role
  561. result = Hash.new([])
  562. project_ids_by_role.each do |role, ids|
  563. result[role] = Project.where(:id => ids).to_a
  564. end
  565. @projects_by_role = result
  566. end
  567. # Returns a hash of project ids grouped by roles.
  568. # Includes the projects that the user is a member of and the projects
  569. # that grant custom permissions to the builtin groups.
  570. def project_ids_by_role
  571. # Clear project condition for when called from chained scopes
  572. # eg. project.children.visible(user)
  573. Project.unscoped do
  574. return @project_ids_by_role if @project_ids_by_role
  575. group_class = anonymous? ? GroupAnonymous.unscoped : GroupNonMember.unscoped
  576. group_id = group_class.pick(:id)
  577. members = Member.joins(:project, :member_roles).
  578. where("#{Project.table_name}.status <> 9").
  579. where("#{Member.table_name}.user_id = ? OR (#{Project.table_name}.is_public = ? AND #{Member.table_name}.user_id = ?)", self.id, true, group_id).
  580. pluck(:user_id, :role_id, :project_id)
  581. hash = {}
  582. members.each do |user_id, role_id, project_id|
  583. # Ignore the roles of the builtin group if the user is a member of the project
  584. next if user_id != id && project_ids.include?(project_id)
  585. hash[role_id] ||= []
  586. hash[role_id] << project_id
  587. end
  588. result = Hash.new([])
  589. if hash.present?
  590. roles = Role.where(:id => hash.keys).to_a
  591. hash.each do |role_id, proj_ids|
  592. role = roles.detect {|r| r.id == role_id}
  593. if role
  594. result[role] = proj_ids.uniq
  595. end
  596. end
  597. end
  598. @project_ids_by_role = result
  599. end
  600. end
  601. # Returns the ids of visible projects
  602. def visible_project_ids
  603. @visible_project_ids ||= Project.visible(self).pluck(:id)
  604. end
  605. # Returns the roles that the user is allowed to manage for the given project
  606. def managed_roles(project)
  607. if admin?
  608. @managed_roles ||= Role.givable.to_a
  609. else
  610. membership(project).try(:managed_roles) || []
  611. end
  612. end
  613. # Returns true if user is arg or belongs to arg
  614. def is_or_belongs_to?(arg)
  615. if arg.is_a?(User)
  616. self == arg
  617. elsif arg.is_a?(Group)
  618. arg.users.include?(self)
  619. else
  620. false
  621. end
  622. end
  623. # Return true if the user is allowed to do the specified action on a specific context
  624. # Action can be:
  625. # * a parameter-like Hash (eg. :controller => 'projects', :action => 'edit')
  626. # * a permission Symbol (eg. :edit_project)
  627. # Context can be:
  628. # * a project : returns true if user is allowed to do the specified action on this project
  629. # * an array of projects : returns true if user is allowed on every project
  630. # * nil with options[:global] set : check if user has at least one role allowed for this action,
  631. # or falls back to Non Member / Anonymous permissions depending if the user is logged
  632. def allowed_to?(action, context, options={}, &block)
  633. if context && context.is_a?(Project)
  634. return false unless context.allows_to?(action)
  635. # Admin users are authorized for anything else
  636. return true if admin?
  637. roles = roles_for_project(context)
  638. return false unless roles
  639. roles.any? do |role|
  640. (context.is_public? || role.member?) &&
  641. role.allowed_to?(action) &&
  642. (block_given? ? yield(role, self) : true)
  643. end
  644. elsif context && context.is_a?(Array)
  645. if context.empty?
  646. false
  647. else
  648. # Authorize if user is authorized on every element of the array
  649. context.map {|project| allowed_to?(action, project, options, &block)}.reduce(:&)
  650. end
  651. elsif context
  652. raise ArgumentError.new("#allowed_to? context argument must be a Project, an Array of projects or nil")
  653. elsif options[:global]
  654. # Admin users are always authorized
  655. return true if admin?
  656. # authorize if user has at least one role that has this permission
  657. roles = self.roles.to_a | [builtin_role]
  658. roles.any? do |role|
  659. role.allowed_to?(action) &&
  660. (block_given? ? yield(role, self) : true)
  661. end
  662. else
  663. false
  664. end
  665. end
  666. # Is the user allowed to do the specified action on any project?
  667. # See allowed_to? for the actions and valid options.
  668. #
  669. # NB: this method is not used anywhere in the core codebase as of
  670. # 2.5.2, but it's used by many plugins so if we ever want to remove
  671. # it it has to be carefully deprecated for a version or two.
  672. def allowed_to_globally?(action, options={}, &block)
  673. allowed_to?(action, nil, options.reverse_merge(:global => true), &block)
  674. end
  675. def allowed_to_view_all_time_entries?(context)
  676. allowed_to?(:view_time_entries, context) do |role, user|
  677. role.time_entries_visibility == 'all'
  678. end
  679. end
  680. # Returns true if the user is allowed to delete the user's own account
  681. def own_account_deletable?
  682. Setting.unsubscribe? &&
  683. (!admin? || User.active.admin.where("id <> ?", id).exists?)
  684. end
  685. safe_attributes(
  686. 'firstname',
  687. 'lastname',
  688. 'mail',
  689. 'mail_notification',
  690. 'notified_project_ids',
  691. 'language',
  692. 'custom_field_values',
  693. 'custom_fields',
  694. 'identity_url')
  695. safe_attributes(
  696. 'login',
  697. :if => lambda {|user, current_user| user.new_record?})
  698. safe_attributes(
  699. 'status',
  700. 'auth_source_id',
  701. 'generate_password',
  702. 'must_change_passwd',
  703. 'login',
  704. 'admin',
  705. :if => lambda {|user, current_user| current_user.admin?})
  706. safe_attributes(
  707. 'group_ids',
  708. :if => lambda {|user, current_user| current_user.admin? && !user.new_record?})
  709. # Utility method to help check if a user should be notified about an
  710. # event.
  711. #
  712. # TODO: only supports Issue events currently
  713. def notify_about?(object)
  714. if mail_notification == 'all'
  715. true
  716. elsif mail_notification.blank? || mail_notification == 'none'
  717. false
  718. else
  719. case object
  720. when Issue
  721. case mail_notification
  722. when 'selected', 'only_my_events'
  723. # user receives notifications for created/assigned issues on unselected projects
  724. object.author == self || is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.previous_assignee)
  725. when 'only_assigned'
  726. is_or_belongs_to?(object.assigned_to) || is_or_belongs_to?(object.previous_assignee)
  727. when 'only_owner'
  728. object.author == self
  729. end
  730. when News
  731. # always send to project members except when mail_notification is set to 'none'
  732. true
  733. end
  734. end
  735. end
  736. def notify_about_high_priority_issues?
  737. self.pref.notify_about_high_priority_issues
  738. end
  739. def self.current=(user)
  740. RequestStore.store[:current_user] = user
  741. end
  742. def self.current
  743. RequestStore.store[:current_user] ||= User.anonymous
  744. end
  745. # Returns the anonymous user. If the anonymous user does not exist, it is created. There can be only
  746. # one anonymous user per database.
  747. def self.anonymous
  748. anonymous_user = AnonymousUser.unscoped.find_by(:lastname => 'Anonymous')
  749. if anonymous_user.nil?
  750. anonymous_user = AnonymousUser.unscoped.create(:lastname => 'Anonymous', :firstname => '', :login => '', :status => 0)
  751. raise 'Unable to create the anonymous user.' if anonymous_user.new_record?
  752. end
  753. anonymous_user
  754. end
  755. # Salts all existing unsalted passwords
  756. # It changes password storage scheme from SHA1(password) to SHA1(salt + SHA1(password))
  757. # This method is used in the SaltPasswords migration and is to be kept as is
  758. def self.salt_unsalted_passwords!
  759. transaction do
  760. User.where("salt IS NULL OR salt = ''").find_each do |user|
  761. next if user.hashed_password.blank?
  762. salt = User.generate_salt
  763. hashed_password = User.hash_password("#{salt}#{user.hashed_password}")
  764. User.where(:id => user.id).update_all(:salt => salt, :hashed_password => hashed_password)
  765. end
  766. end
  767. end
  768. def bookmarked_project_ids
  769. project_ids = []
  770. bookmarked_project_ids = self.pref[:bookmarked_project_ids]
  771. project_ids = bookmarked_project_ids.split(',') unless bookmarked_project_ids.nil?
  772. project_ids.map(&:to_i)
  773. end
  774. protected
  775. def validate_password_length
  776. return if password.blank? && generate_password?
  777. # Password length validation based on setting
  778. if !password.nil? && password.size < Setting.password_min_length.to_i
  779. errors.add(:password, :too_short, :count => Setting.password_min_length.to_i)
  780. end
  781. end
  782. def instantiate_email_address
  783. email_address || build_email_address
  784. end
  785. private
  786. def generate_password_if_needed
  787. if generate_password? && auth_source.nil?
  788. length = [Setting.password_min_length.to_i + 2, 10].max
  789. random_password(length)
  790. end
  791. end
  792. # Delete all outstanding password reset tokens on password change.
  793. # Delete the autologin tokens on password change to prohibit session leakage.
  794. # This helps to keep the account secure in case the associated email account
  795. # was compromised.
  796. def destroy_tokens
  797. if saved_change_to_hashed_password? || (saved_change_to_status? && !active?) || (saved_change_to_twofa_scheme? && twofa_scheme.present?)
  798. tokens = ['recovery', 'autologin', 'session']
  799. Token.where(:user_id => id, :action => tokens).delete_all
  800. end
  801. end
  802. # Removes references that are not handled by associations
  803. # Things that are not deleted are reassociated with the anonymous user
  804. def remove_references_before_destroy
  805. return if self.id.nil?
  806. substitute = User.anonymous
  807. Attachment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  808. Comment.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  809. Issue.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  810. Issue.where(['assigned_to_id = ?', id]).update_all('assigned_to_id = NULL')
  811. Journal.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  812. JournalDetail.
  813. where(["property = 'attr' AND prop_key = 'assigned_to_id' AND old_value = ?", id.to_s]).
  814. update_all(['old_value = ?', substitute.id.to_s])
  815. JournalDetail.
  816. where(["property = 'attr' AND prop_key = 'assigned_to_id' AND value = ?", id.to_s]).
  817. update_all(['value = ?', substitute.id.to_s])
  818. Message.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  819. News.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  820. # Remove private queries and keep public ones
  821. ::Query.where('user_id = ? AND visibility = ?', id, ::Query::VISIBILITY_PRIVATE).delete_all
  822. ::Query.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  823. TimeEntry.where(['user_id = ?', id]).update_all(['user_id = ?', substitute.id])
  824. Token.where('user_id = ?', id).delete_all
  825. Watcher.where('user_id = ?', id).delete_all
  826. WikiContent.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  827. WikiContentVersion.where(['author_id = ?', id]).update_all(['author_id = ?', substitute.id])
  828. user_custom_field_ids = CustomField.where(field_format: 'user').ids
  829. if user_custom_field_ids.any?
  830. CustomValue.where(custom_field_id: user_custom_field_ids, value: self.id.to_s).delete_all
  831. end
  832. end
  833. # Singleton class method is public
  834. class << self
  835. # Return password digest
  836. def hash_password(clear_password)
  837. Digest::SHA1.hexdigest(clear_password || "")
  838. end
  839. # Returns a 128bits random salt as a hex string (32 chars long)
  840. def generate_salt
  841. Redmine::Utils.random_hex(16)
  842. end
  843. end
  844. # Send a security notification to all admins if the user has gained/lost admin privileges
  845. def deliver_security_notification
  846. options = {
  847. field: :field_admin,
  848. value: login,
  849. title: :label_user_plural,
  850. url: {controller: 'users', action: 'index'}
  851. }
  852. deliver = false
  853. if (admin? && saved_change_to_id? && active?) || # newly created admin
  854. (admin? && saved_change_to_admin? && active?) || # regular user became admin
  855. (admin? && saved_change_to_status? && active?) # locked admin became active again
  856. deliver = true
  857. options[:message] = :mail_body_security_notification_add
  858. elsif (admin? && destroyed? && active?) || # active admin user was deleted
  859. (!admin? && saved_change_to_admin? && active?) || # admin is no longer admin
  860. (admin? && saved_change_to_status? && !active?) # admin was locked
  861. deliver = true
  862. options[:message] = :mail_body_security_notification_remove
  863. end
  864. if deliver
  865. users = User.active.where(admin: true).to_a
  866. Mailer.deliver_security_notification(users, User.current, options)
  867. end
  868. end
  869. end
  870. class AnonymousUser < User
  871. validate :validate_anonymous_uniqueness, :on => :create
  872. self.valid_statuses = [STATUS_ANONYMOUS]
  873. def validate_anonymous_uniqueness
  874. # There should be only one AnonymousUser in the database
  875. errors.add :base, 'An anonymous user already exists.' if AnonymousUser.unscoped.exists?
  876. end
  877. def available_custom_fields
  878. []
  879. end
  880. # Overrides a few properties
  881. def logged?; false end
  882. def admin; false end
  883. def name(*args); I18n.t(:label_user_anonymous) end
  884. def mail=(*args); nil end
  885. def mail; nil end
  886. def time_zone; nil end
  887. def rss_key; nil end
  888. def pref
  889. UserPreference.new(:user => self)
  890. end
  891. # Returns the user's bult-in role
  892. def builtin_role
  893. @builtin_role ||= Role.anonymous
  894. end
  895. def membership(*args)
  896. nil
  897. end
  898. def member_of?(*args)
  899. false
  900. end
  901. # Anonymous user can not be destroyed
  902. def destroy
  903. false
  904. end
  905. protected
  906. def instantiate_email_address
  907. end
  908. end