You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.rb 31KB

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