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

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