OpenProject is the leading open source project management software for product, project and portfolio management. A powerful Jira alternative with agile planning, issue tracking, roadmaps, Gantt charts, time tracking, collaboration features, and more. Available on premises or in the cloud. ⭐ Star us on GitHub
Ruby agile-developmentangularbcfboardsbug-trackerganttgantt-chartifcissue-trackerjira-alternativekanbanopenprojectproduct-managementproject-managementproject-planningroadmaprubyscrumtimelineworkflows
[35507] Allow global permission to add and edit users (#8937)
Oliver Günther3c9be3bdbe7d
diff --git a/app/cells/users/row_cell.rb b/app/cells/users/row_cell.rbindex c6174357823..ad24d477540 100644--- a/app/cells/users/row_cell.rb+++ b/app/cells/users/row_cell.rb@@ -42,7 +42,13 @@ module Usersenddef status_link- change_user_status_links user unless user.id == table.current_user.id+ # Don't show for current user+ return if user.id == table.current_user.id++ # Don't show if non-admin+ return unless table.current_user.admin?++ change_user_status_links userenddef column_css_class(column)diff --git a/app/contracts/users/base_contract.rb b/app/contracts/users/base_contract.rbindex 75442a6fa92..5ca26378ee4 100644--- a/app/contracts/users/base_contract.rb+++ b/app/contracts/users/base_contract.rb@@ -38,21 +38,39 @@ module Usersattribute :lastnameattribute :nameattribute :mail- attribute :admin+ attribute :admin,+ writeable: ->(*) { user.admin? && model.id != user.id }attribute :language- attribute :auth_source_id- attribute :identity_url- attribute :password+ attribute :auth_source_id,+ writeable: ->(*) { user.admin? }++ attribute :identity_url,+ writeable: ->(*) { user.admin? }++ attribute :force_password_change,+ writeable: ->(*) { user.admin? }def self.modelUserend+ validate :password_writablevalidate :existing_auth_sourceprivate+ ##+ # User#password is not an ActiveModel property,+ # but just an accessor, so we need to identify it being written there.+ # It is only present when freshly written+ def password_writable+ # Only admins or the user themselves can set the password+ return if user.admin? || user.id == model.id++ errors.add :password, :error_readonly if model.password.present?+ end+def existing_auth_sourceif auth_source_id && AuthSource.find_by_unique(auth_source_id).nil?errors.add :auth_source, :error_not_founddiff --git a/app/contracts/users/create_contract.rb b/app/contracts/users/create_contract.rbindex bac846e7850..1297c40abde 100644--- a/app/contracts/users/create_contract.rb+++ b/app/contracts/users/create_contract.rb@@ -55,7 +55,7 @@ module Users### Users can only be created by Adminsdef user_allowed_to_add- unless user.admin?+ unless user.admin? || user.allowed_to_globally?(:add_user)errors.add :base, :error_unauthorizedendenddiff --git a/lib/api/v3/users/create_user.rb b/app/contracts/users/delete_contract.rbsimilarity index 51%rename from lib/api/v3/users/create_user.rbrename to app/contracts/users/delete_contract.rbindex eb8becbb29a..ffd9759721f 100644--- a/lib/api/v3/users/create_user.rb+++ b/app/contracts/users/delete_contract.rb@@ -1,3 +1,5 @@+#-- encoding: UTF-8+#-- copyright# OpenProject is an open source project management software.# Copyright (C) 2012-2021 the OpenProject GmbH@@ -26,40 +28,24 @@# See docs/COPYRIGHT.rdoc for more details.#++-require 'api/v3/users/user_representer'-require 'users/create_user_service'--module API- module V3- module Users- module CreateUser- extend Grape::API::Helpers- ##- # Call the user create service for the current request- # and return the service result API representation- def create_user(request_body, current_user)- payload = ::API::V3::Users::UserRepresenter.create(User.new, current_user: current_user)- new_user = payload.from_hash(request_body)-- result = call_service(new_user, current_user)- represent_service_result(result, current_user)- end-- private+require 'users/base_contract'- def represent_service_result(result, current_user)- if result.success?- status 201- ::API::V3::Users::UserRepresenter.create(result.result, current_user: current_user)- else- fail ::API::Errors::ErrorBase.create_and_merge_errors(result.errors)- end- end+module Users+ class DeleteContract < ::DeleteContract+ delete_permission -> {+ self.class.deletion_allowed?(model, user)+ }- def call_service(new_user, current_user)- create_service = ::Users::CreateUserService.new(current_user: current_user)- create_service.call(new_user)- end+ ##+ # Checks if a given user may be deleted by another one.+ #+ # @param user [User] User to be deleted.+ # @param actor [User] User who wants to delete the given user.+ def self.deletion_allowed?(user, actor)+ if actor == user+ Setting.users_deletable_by_self?+ else+ actor.admin? && actor.active? && Setting.users_deletable_by_admins?endendenddiff --git a/app/contracts/users/update_contract.rb b/app/contracts/users/update_contract.rbindex c4d98aaca2f..4133ab15ce7 100644--- a/app/contracts/users/update_contract.rb+++ b/app/contracts/users/update_contract.rb@@ -37,9 +37,12 @@ module Usersprivate##- # Users can only be updated by Admins+ # Users can only be updated when+ # - the user is editing herself+ # - the user has the global add_user CRU permission+ # - the user is an admindef user_allowed_to_update- unless user.admin?+ unless user == model || user.admin? || user.allowed_to_globally?(:add_user)errors.add :base, :error_unauthorizedendenddiff --git a/app/controllers/admin_controller.rb b/app/controllers/admin_controller.rbindex eb684868f42..ac1ea85d7b1 100644--- a/app/controllers/admin_controller.rb+++ b/app/controllers/admin_controller.rb@@ -31,7 +31,8 @@ require 'open3'class AdminController < ApplicationControllerlayout 'admin'- before_action :require_admin+ before_action :require_admin, except: %i[index]+ before_action :authorize_global, only: %i[index]menu_item :plugins, only: [:plugins]menu_item :info, only: [:info]@@ -41,6 +42,10 @@ class AdminController < ApplicationController@menu_nodes = Redmine::MenuManager.items(:admin_menu).children@menu_nodes.delete_if { |node| node.name === :admin_overview }@menu_nodes.delete_if { |node| node.condition && !node.condition.call }++ if @menu_nodes.count == 1+ redirect_to @menu_nodes.first.url+ endenddef projectsdiff --git a/app/controllers/my_controller.rb b/app/controllers/my_controller.rbindex ce16fd60224..c20e9c7f7ef 100644--- a/app/controllers/my_controller.rb+++ b/app/controllers/my_controller.rb@@ -50,7 +50,7 @@ class MyController < ApplicationControllerdef account; enddef update_account- write_settings @user, request, permitted_params, params+ write_settings# If mail changed, expire all other sessionsif @user.previous_changes['mail'] && ::Sessions::DropOtherSessionsService.call(@user, session)@@ -62,7 +62,7 @@ class MyController < ApplicationControllerdef settings; enddef update_settings- write_settings @user, request, permitted_params, params+ write_settingsend# Manage user's password@@ -151,10 +151,12 @@ class MyController < ApplicationControllerendend- def write_settings(current_user, request, permitted_params, params)+ def write_settings+ user_params = permitted_params.my_account_settings+result = Users::UpdateService- .new(current_user: current_user)- .call(permitted_params, params)+ .new(user: current_user, model: current_user)+ .call(user_params.to_h)if result&.successflash[:notice] = t(:notice_account_updated)diff --git a/app/controllers/onboarding_controller.rb b/app/controllers/onboarding_controller.rbindex 750a6e0a5d7..77cc85a30bc 100644--- a/app/controllers/onboarding_controller.rb+++ b/app/controllers/onboarding_controller.rb@@ -32,8 +32,8 @@ class OnboardingController < ApplicationController@user = User.currentresult = Users::UpdateService- .new(current_user: @user)- .call(permitted_params, params)+ .new(model: @user, user: @user)+ .call(permitted_params.user.to_h)if result.success?flash[:notice] = I18n.t(:notice_account_updated)diff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rbindex c15867520be..c3afd48e5cc 100644--- a/app/controllers/users_controller.rb+++ b/app/controllers/users_controller.rb@@ -32,20 +32,21 @@ class UsersController < ApplicationControllerhelper_method :gon- before_action :require_admin, except: [:show, :deletion_info, :destroy]- before_action :find_user, only: [:show,- :edit,- :update,- :change_status_info,- :change_status,- :destroy,- :deletion_info,- :resend_invitation]+ before_action :authorize_global, except: %i[show deletion_info destroy]++ before_action :find_user, only: %i[show+ edit+ update+ change_status_info+ change_status+ destroy+ deletion_info+ resend_invitation]# should also contain destroy but post data can not be redirectedbefore_action :require_login, only: [:deletion_info]before_action :authorize_for_user, only: [:destroy]- before_action :check_if_deletion_allowed, only: [:deletion_info,- :destroy]+ before_action :check_if_deletion_allowed, only: %i[deletion_info+ destroy]# Password confirmation helpers and actionsinclude PasswordConfirmation@@ -80,7 +81,7 @@ class UsersController < ApplicationControllerevents = Activities::Fetcher.new(User.current, author: @user).events(nil, nil, limit: 10)@events_by_day = events.group_by { |e| e.event_datetime.to_date }- if !User.current.admin? &&+ if !current_user.allowed_to_globally?(:add_user) &&(!(@user.active? ||@user.registered?) ||(@user != User.current && @memberships.empty? && events.empty?))@@ -127,33 +128,16 @@ class UsersController < ApplicationControllerenddef update- @user.attributes = permitted_params.user_create_as_admin(@user.uses_external_authentication?,- @user.change_password_allowed?)-- if @user.change_password_allowed?- if params[:user][:assign_random_password]- @user.random_password!- elsif set_password? params- @user.password = params[:user][:password]- @user.password_confirmation = params[:user][:password_confirmation]- end- end+ update_params = build_user_update_params+ mail_notification = update_params.delete(:mail_notification)+ call = ::Users::UpdateService.new(model: @user, user: current_user).call(update_params)- pref_params = if params[:pref].present?- permitted_params.pref- else- {}- end-- if @user.save+ if call.success?update_email_service = UpdateUserEmailSettingsService.new(@user)- update_email_service.call(mail_notification: pref_params.delete(:mail_notification),+ update_email_service.call(mail_notification: mail_notification,self_notified: params[:self_notified] == '1',notified_project_ids: params[:notified_project_ids])- @user.pref.attributes = pref_params- @user.pref.save-if [email protected]? && @user.change_password_allowed?send_information = params[:send_information]@@ -184,6 +168,8 @@ class UsersController < ApplicationController@auth_sources = AuthSource.all@membership ||= Member.new# Clear password input+ @user = call.result+ @errors = call.errors@user.password = @user.password_confirmation = nilrespond_to do |format|@@ -262,7 +248,7 @@ class UsersController < ApplicationController# true if the user deletes him/herselfself_delete = (@user == User.current)- Users::DeleteService.new(@user, User.current).call+ Users::DeleteService.new(model: @user, user: User.current).callflash[:notice] = I18n.t('account.deleted')@@ -307,7 +293,7 @@ class UsersController < ApplicationControllerenddef check_if_deletion_allowed- render_404 unless Users::DeleteService.deletion_allowed? @user, User.current+ render_404 unless Users::DeleteContract.deletion_allowed? @user, User.currentenddef my_or_admin_layout@@ -337,4 +323,30 @@ class UsersController < ApplicationControllerdef show_local_breadcrumbcurrent_user.admin?end++ def build_user_update_params+ pref_params = permitted_params.pref.to_h+ update_params = permitted_params+ .user_create_as_admin(@user.uses_external_authentication?, @user.change_password_allowed?)+ .to_h+ .merge(pref: pref_params)++ return update_params unless @user.change_password_allowed?++ if params[:user][:assign_random_password]+ password = OpenProject::Passwords::Generator.random_password+ update_params.merge!(+ password: password,+ password_confirmation: password,+ force_password_change: true+ )+ elsif set_password? params+ update_params.merge!(+ password: params[:user][:password],+ password_confirmation: params[:user][:password_confirmation]+ )+ end++ update_params+ endenddiff --git a/app/models/permitted_params.rb b/app/models/permitted_params.rbindex 8dfcba164c8..9af78cf8402 100644--- a/app/models/permitted_params.rb+++ b/app/models/permitted_params.rb@@ -93,8 +93,8 @@ class PermittedParamsdef custom_actionwhitelisted = params- .require(:custom_action)- .permit(*self.class.permitted_attributes[:custom_action])+ .require(:custom_action)+ .permit(*self.class.permitted_attributes[:custom_action])whitelisted.merge(params[:custom_action].slice(:actions, :conditions).permit!)end@@ -156,8 +156,8 @@ class PermittedParams# Here we try to circumvent thisp = params.require(:query).permit(*self.class.permitted_attributes[:query])p[:sort_criteria] = params- .require(:query)- .permit(sort_criteria: { '0' => [], '1' => [], '2' => [] })+ .require(:query)+ .permit(sort_criteria: { '0' => [], '1' => [], '2' => [] })p[:sort_criteria].delete :sort_criteriapend@@ -188,10 +188,14 @@ class PermittedParamspermitted_paramsend+ def my_account_settings+ user.merge(pref: pref)+ end+def user_register_via_omniauthpermitted_params = params- .require(:user)- .permit(:login, :firstname, :lastname, :mail, :language)+ .require(:user)+ .permit(:login, :firstname, :lastname, :mail, :language)permitted_params = permitted_params.merge(custom_field_values(:user))permitted_params@@ -213,7 +217,7 @@ class PermittedParamspermitted_paramselse- params.require(:user).permit+ userendend@@ -258,9 +262,9 @@ class PermittedParamsenddef pref- params.require(:pref).permit(:hide_mail, :time_zone, :theme,- :comments_sorting, :warn_on_leaving_unsaved,- :auto_hide_popups)+ params.fetch(:pref, {}).permit(:hide_mail, :time_zone, :theme,+ :comments_sorting, :warn_on_leaving_unsaved,+ :auto_hide_popups)enddef project@@ -518,8 +522,8 @@ class PermittedParamsProc.new do |args|# avoid costly allowed_to? if the param is not there at allif args[:params]['work_package'] &&- args[:params]['work_package'].has_key?('watcher_user_ids') &&- args[:current_user].allowed_to?(:add_work_package_watchers, args[:project])+ args[:params]['work_package'].has_key?('watcher_user_ids') &&+ args[:current_user].allowed_to?(:add_work_package_watchers, args[:project]){ watcher_user_ids: [] }enddiff --git a/app/services/authorization/user_allowed_service.rb b/app/services/authorization/user_allowed_service.rbindex f57abd37f35..8215e5f97e8 100644--- a/app/services/authorization/user_allowed_service.rb+++ b/app/services/authorization/user_allowed_service.rb@@ -90,6 +90,8 @@ class Authorization::UserAllowedServicereturn false unless project.active?# No action allowed on disabled modulesreturn false unless project.allows_to?(action)+ # Inactive users are never authorized+ return false unless authorizable_user?# Admin users are authorized for anything elsereturn true if user.admin?@@ -99,12 +101,21 @@ class Authorization::UserAllowedService# Is the user allowed to do the specified action on any project?# See allowed_to? for the actions and valid options.def allowed_to_globally?(action, _options = {})+ # Inactive users are never authorized+ return false unless authorizable_user?# Admin users are always authorizedreturn true if user.admin?has_authorized_role?(action)end+ ##+ # Only users that are not locked may be granted actions+ # with the exception of a temporary-granted system user+ def authorizable_user?+ user.active_or_registered? || user.is_a?(SystemUser)+ end+def has_authorized_role?(action, project = nil)project_role_cache.fetch(project)diff --git a/app/services/sessions/drop_other_sessions_service.rb b/app/services/sessions/drop_other_sessions_service.rbindex f0f15ef9dfc..89adb557de1 100644--- a/app/services/sessions/drop_other_sessions_service.rb+++ b/app/services/sessions/drop_other_sessions_service.rb@@ -40,7 +40,7 @@ module Sessions::UserSession.where(user_id: user.id)- .where.not(session_id: session.id)+ .where.not(session_id: session.id.to_s).delete_alltruediff --git a/app/services/users/create_user_service.rb b/app/services/users/create_service.rbsimilarity index 52%rename from app/services/users/create_user_service.rbrename to app/services/users/create_service.rbindex 41c376324cf..ba26e80c66f 100644--- a/app/services/users/create_user_service.rb+++ b/app/services/users/create_service.rb@@ -31,70 +31,35 @@ require 'work_packages/create_contract'require 'concerns/user_invitation'module Users- class CreateUserService- include Contracted-- attr_reader :current_user-- def initialize(current_user:)- @current_user = current_user- self.contract_class = Users::CreateContract- end-- def call(new_user)- User.execute_as current_user do- create(new_user)- end- end+ class CreateService < ::BaseServices::Createprivate- def create(new_user)- return create_regular(new_user) unless new_user.invited?+ def persist(call)+ new_user = call.result++ return super(call) unless new_user.invited?# As we're basing on the user's mail, this parameter is required# before we're able to validate the contract or user- if new_user.mail.blank?- contract = instantiate_contract(new_user, current_user)- contract.errors.add :mail, :blank- build_result(new_user, contract.errors)- else- create_invited(new_user)- end- end-- def build_result(result, errors)- success = result.is_a?(User) && errors.empty?- ServiceResult.new(success: success, errors: errors, result: result)- end+ return fail_with_missing_email(new_user) if new_user.mail.blank?- ##- # Create regular user- def create_regular(new_user)- result, errors = validate_and_save(new_user, current_user)- ServiceResult.new(success: result, errors: errors, result: new_user)+ invite_user!(new_user)end- ##- # User creation flow for users that are invited.- # Re-uses UserInvitation and thus avoids +validate_and_save+- def create_invited(new_user)- # Assign values other than mail to new_user- ::UserInvitation.assign_user_attributes new_user-- # Check contract validity before moving to UserInvitation- if !validate(new_user, current_user)- build_result(new_user, contract.errors)+ def fail_with_missing_email(new_user)+ ServiceResult.new(success: false, result: new_user).tap do |result|+ result.errors.add :mail, :blankend-- invite_user! new_userenddef invite_user!(new_user)++invited = ::UserInvitation.invite_user! new_usernew_user.errors.add :base, I18n.t(:error_can_not_invite_user) unless invited.is_a? User- build_result(invited, new_user.errors)+ ServiceResult.new(success: new_user.errors.empty?, result: invited)endendenddiff --git a/app/services/users/delete_service.rb b/app/services/users/delete_service.rbindex 32a6b7b6d30..3bf0df3cb48 100644--- a/app/services/users/delete_service.rb+++ b/app/services/users/delete_service.rb@@ -31,54 +31,27 @@### Implements the deletion of a user.module Users- class DeleteService- attr_reader :user, :actor-- def initialize(user, actor)- @user = user- @actor = actor- end+ class DeleteService < ::BaseServices::Delete### Deletes the given user if allowed.## @return True if the user deletion has been initiated, false otherwise.- def call- if deletion_allowed?- # as destroying users is a lengthy process we handle it in the background- # and lock the account now so that no action can be performed with it- user.lock!- DeleteUserJob.perform_later(user)+ def destroy(user_object)+ # as destroying users is a lengthy process we handle it in the background+ # and lock the account now so that no action can be performed with it+ user_object.lock!+ DeleteUserJob.perform_later(user_object)- logout! if self_delete?-- true- else- false- end- end+ logout! if self_delete?- ##- # Checks if a given user may be deleted by another one.- #- # @param user [User] User to be deleted.- # @param actor [User] User who wants to delete the given user.- def self.deletion_allowed?(user, actor)- if actor == user- Setting.users_deletable_by_self?- else- actor.admin? && actor.active? && Setting.users_deletable_by_admins?- end+ trueendprivate- def deletion_allowed?- self.class.deletion_allowed? user, actor- end-def self_delete?- user == actor+ user == modelenddef logout!diff --git a/app/services/users/update_user_service.rb b/app/services/users/set_attributes_service.rbsimilarity index 70%rename from app/services/users/update_user_service.rbrename to app/services/users/set_attributes_service.rbindex fe271a92b65..335ba5707b2 100644--- a/app/services/users/update_user_service.rb+++ b/app/services/users/set_attributes_service.rb@@ -28,30 +28,26 @@#++module Users- class UpdateUserService- include Contracted+ class SetAttributesService < ::BaseServices::SetAttributes+ include ::HookHelper- attr_accessor :current_user, :user+ private- def initialize(current_user:, user:)- self.current_user = current_user- self.user = user- self.contract_class = Users::UpdateContract- end+ def set_attributes(params)+ set_preferences params.delete(:pref)- def call(attributes: {})- User.execute_as current_user do- set_attributes(attributes)+ super(params)+ end- success, errors = validate_and_save(user, current_user)- ServiceResult.new(success: success, errors: errors, result: user)+ def set_default_attributes(_params)+ # Assign values other than mail to new_user when invited+ if model.invited? && model.mail.present?+ ::UserInvitation.assign_user_attributes modelendend- private-- def set_attributes(attributes)- user.attributes = attributes+ def set_preferences(user_preferences)+ model.pref.attributes = user_preferences if user_preferencesendendenddiff --git a/app/services/users/update_service.rb b/app/services/users/update_service.rbindex ff4a38d41bf..89ed5763edc 100644--- a/app/services/users/update_service.rb+++ b/app/services/users/update_service.rb@@ -28,42 +28,27 @@#++module Users- class UpdateService+ class UpdateService < ::BaseServices::Updateinclude ::HookHelper- attr_accessor :current_user+ protected- def initialize(current_user:)- @current_user = current_user- end+ def before_perform(params)+ call_hook :service_update_user_before_save,+ params: params,+ user: model- def call(permitted_params, params)- User.execute_as current_user do- set_attributes(permitted_params, params)- end+ super(params)end- private-- def set_attributes(permitted_params, params)- current_user.attributes = permitted_params.user- current_user.pref.attributes = if params[:pref].present?- permitted_params.pref- else- {}- end+ def persist(service_result)+ service_result = super(service_result)- call_hook :service_update_user_before_save,- params: params,- permitted_params: permitted_params,- user: current_user-- if current_user.save- success = current_user.pref.save- ServiceResult.new(success: success, errors: current_user.errors, result: current_user)- else- ServiceResult.new(success: false, errors: current_user.errors, result: current_user)+ if service_result.success?+ service_result.success = model.pref.saveend++ service_resultendendenddiff --git a/app/views/roles/_permissions.html.erb b/app/views/roles/_permissions.html.erbindex 07ebf453283..a40727bbc24 100644--- a/app/views/roles/_permissions.html.erb+++ b/app/views/roles/_permissions.html.erb@@ -32,7 +32,11 @@ See docs/COPYRIGHT.rdoc for more details.<% module_name = mod.blank? ? 'fieldset--global--' + Project.model_name.human.downcase.gsub(' ', '_') : global_prefix + l_or_humanize(mod, prefix: 'project_module_').downcase.gsub(' ', '_') %><fieldset class="form--fieldset -collapsible" id="<%= module_name %>"><legend class="form--fieldset-legend">- <%= mod.blank? ? Project.model_name.human : l_or_humanize(mod, prefix: 'project_module_') %>+ <% if mod.blank? %>+ <%= showGlobalRole ? t(:label_global) : Project.model_name.human %>+ <% else %>+ <%= l_or_humanize(mod, prefix: 'project_module_') %>+ <% end %></legend><div class="form--toolbar"><span class="form--toolbar-item">diff --git a/app/views/users/_form.html.erb b/app/views/users/_form.html.erbindex 064643afa99..22692354b1e 100644--- a/app/views/users/_form.html.erb+++ b/app/views/users/_form.html.erb@@ -27,131 +27,29 @@ See docs/COPYRIGHT.rdoc for more details.++#%>-<%= error_messages_for 'user' %>+<%= error_messages_for_contract @user, @errors %><% content_for :header_tags do %><meta name="required_script" content="admin_users" /><% end %>-<!--[form:user]--><section class="form--section">- <div class="form--field -required"><%= f.text_field :login, required: true, size: 25, container_class: '-middle' %></div>- <div class="form--field -required"><%= f.text_field :firstname, required: true, container_class: '-middle' %></div>- <div class="form--field -required"><%= f.text_field :lastname, required: true, container_class: '-middle' %></div>- <div class="form--field -required"><%= f.text_field :mail, required: true, container_class: '-middle' %></div>- <div class="form--field"><%= f.select :language, lang_options_for_select, prompt: "--- #{t(:actionview_instancetag_blank_option)} ---", container_class: '-slim' %></div>- <div class="form--field"><%= f.check_box :admin, disabled: (@user == User.current) %></div>+ <%= render partial: 'users/form/basic_attributes', locals: { f: f } %>- <h3 class="form--section-title"><%= t(:label_custom_field_plural) %></h3>- <%= render partial: 'customizable/field',- collection: @user.custom_field_values,- as: :value,- locals: { form: f } %>+ <% if current_user.admin? %>+ <%= render partial: 'users/form/admin_flag', locals: { f: f } %>+ <% end %>+ <%= render partial: 'users/form/custom_fields', locals: { f: f } %><%= call_hook(:view_users_form, user: @user, form: f) %></section>-<% if Setting.consent_required? %>- <%= render partial: "users/consent" %>-<% end %>--<section class="form--section">- <h3 class="form--section-title"><%=t(:label_authentication)%></h3>- <% if @user.uses_external_authentication? %>- <div class="form--field">- <%= styled_label_tag nil, I18n.t('user.authentication_provider') %>- <div class="form--field-container">- <%= @user.authentication_provider %>- </div>- </div>- <div class="form--field-instructions">- <%= I18n.t('user.authentication_settings_disabled_due_to_external_authentication') %>- </div>- <% else %>- <% unless @auth_sources.empty? || OpenProject::Configuration.disable_password_login? %>- <div class="form--field">- <%= f.select :auth_source_id,- ([[t(:label_internal), ""]] + @auth_sources.collect { |a| [a.name, a.id] }),- label: :'activerecord.attributes.user.auth_source',- container_class: '-middle' %>- </div>- <% end %>- <% if !OpenProject::Configuration.disable_password_login? %>- <%- pw_style =- if @user.change_password_allowed?- ''- else- ' style="display: none;"'- end- %>- <div id="password_fields"<%= pw_style.html_safe %>>- <% assign_random_password_enabled = params[:user] &&- params[:user][:assign_random_password] %>- <div class="form--field">- <%= styled_label_tag 'user_assign_random_password',- I18n.t(:assign_random_password, scope: :user) %>- <div class="form--field-container">- <%= styled_check_box_tag("user[assign_random_password]",- "1",- assign_random_password_enabled) %>- </div>- </div>-- <% unless OpenProject::Configuration.disable_password_choice? %>- <div class="form--field">- <%= f.password_field :password,- required: @user.new_record?,- disabled: assign_random_password_enabled,- container_class: '-middle' %>- <div class="form--field-instructions">- <%= password_complexity_requirements %>- </div>- </div>- <div class="form--field">- <%= f.password_field :password_confirmation,- required: @user.new_record?,- disabled: assign_random_password_enabled,- container_class: '-middle' %>- </div>- <% end %>-- <% if @user.active? -%>- <div class="form--field send-information -hidden">- <%= styled_label_tag 'send_information', t(:label_send_information) %>- <div class="form--field-container">- <%= styled_check_box_tag("send_information",- "1",- true) %>- </div>- </div>- <% end -%>-- <div class="form--field">- <%= f.check_box :force_password_change,- disabled: assign_random_password_enabled %>- </div>- </div>- <% else %>- <div id="no_password_info">- <div class="form--field">- <%= styled_label_tag nil, I18n.t(:warning) %>- <div class="form--field-container">- <%= I18n.t 'user.no_login' %>- </div>- </div>- </div>- <% end %>+<% if current_user.admin? %>+ <% if Setting.consent_required? %>+ <%= render partial: "users/consent" %><% end %>-</section>--<section class="form--section">- <h3 class="form--section-title"><%= User.human_attribute_name(:mail_notification) %></h3>- <%= render partial: 'users/mail_notifications' %>-</section>-<section class="form--section">- <h3 class="form--section-title"><%=t(:label_preferences)%></h3>- <%= render partial: 'users/preferences', locals: {input_size: :middle } %>-</section>-<!--[eoform:user]-->+ <%= render partial: 'users/form/authentication', locals: { f: f } %>+ <%= render partial: 'users/form/mail_notifications', locals: { f: f } %>+ <%= render partial: 'users/form/preferences', locals: { f: f } %>+<% end %>diff --git a/app/views/users/_simple_form.html.erb b/app/views/users/_simple_form.html.erbindex ff65fe93126..4c7b5bec3b6 100644--- a/app/views/users/_simple_form.html.erb+++ b/app/views/users/_simple_form.html.erb@@ -33,30 +33,14 @@ See docs/COPYRIGHT.rdoc for more details.<meta name="required_script" content="two_factor_authentication" /><% end %>-<!--[form:user]--><section class="form--section">- <div class="form--field -required"><%= f.text_field :mail, required: true, autofocus: true, container_class: '-middle' %></div>- <div class="form--field -required"><%= f.text_field :firstname, required: true, container_class: '-middle' %></div>- <div class="form--field -required"><%= f.text_field :lastname, required: true, container_class: '-middle' %></div>-- <%= render partial: 'customizable/field',- collection: @user.custom_field_values,- as: :value,- locals: { form: f, input_size: "middle" } %>-- <% unless @auth_sources.empty? || OpenProject::Configuration.disable_password_login? %>- <div class="form--field">- <% sources = ([[t(:label_internal), ""]] + @auth_sources.collect { |a| [a.name, a.id] }) %>- <%= f.select :auth_source_id, sources, label: :'activerecord.attributes.user.auth_source' %>- </div>-- <div class="form--field" id="new_user_login" style="display: none;">- <%= f.text_field :login, required: true, size: 25, disabled: true %>- </div>+ <%= render partial: 'users/form/basic_attributes', locals: { f: f } %>++ <% if current_user.admin? %>+ <%= render partial: 'users/form/auth_source', locals: { f: f } %>+ <%= render partial: 'users/form/admin_flag', locals: { f: f } %><% end %>- <div class="form--field"><%= f.check_box :admin, disabled: (@user == User.current) %></div>+ <%= render partial: 'users/form/custom_fields', locals: { f: f } %><%= call_hook(:view_users_form, user: @user, form: f) %></section>--<!--[eoform:user]-->diff --git a/app/views/users/_toolbar.html.erb b/app/views/users/_toolbar.html.erbindex e7aedf1225b..d1ca9de59eb 100644--- a/app/views/users/_toolbar.html.erb+++ b/app/views/users/_toolbar.html.erb@@ -26,29 +26,30 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.See docs/COPYRIGHT.rdoc for more details.++#%>-<%= breadcrumb_toolbar(@user.new_record? ? t(:label_user_new) : @user.name) do %>- <% unless @user.new_record? %>- <% if current_user.admin? || current_user.id == @user.id %>- <li class="toolbar-item hidden-for-mobile">- <%= form_for(@user, html: { class: 'toolbar-item'},- url: { action: :resend_invitation },- method: :post) do |_form| %>- <button class="button" title="<%= t(:tooltip_resend_invitation) %>">- <%= op_icon('button--icon icon-mail1') %>- <span class="button--text"><%= t(:label_send_invitation) %></span>- </button>- <% end %>- </li>+<%= breadcrumb_toolbar(@user.name) do %>+ <li class="toolbar-item">+ <%= link_to user_path(@user), class: 'button' do %>+ <%= op_icon('button--icon icon-user') %>+ <span class="button--text"><%= t(:label_profile) %></span><% end %>- <li class="toolbar-item">- <%= link_to user_path(@user), class: 'button' do %>- <%= op_icon('button--icon icon-user') %>- <span class="button--text"><%= t(:label_profile) %></span>- <% end %>- </li>+ </li>+ <% if current_user.allowed_to_globally?(:add_user) %>+ <li class="toolbar-item hidden-for-mobile">+ <%= form_for(@user, html: { class: 'toolbar-item' },+ url: { action: :resend_invitation },+ method: :post) do |_form| %>+ <button class="button" title="<%= t(:tooltip_resend_invitation) %>">+ <%= op_icon('button--icon icon-mail1') %>+ <span class="button--text"><%= t(:label_send_invitation) %></span>+ </button>+ <% end %>+ </li>+ <% end %>++ <% if current_user.admin? %><% unless current_user.id == @user.id %>- <%= form_for @user, html: { class: 'toolbar-item hidden-for-mobile' }, :url => {:action => :change_status},- :method => :post do %>+ <%= form_for @user, html: { class: 'toolbar-item hidden-for-mobile' }, :url => { :action => :change_status },+ :method => :post do %><li><%= change_user_status_buttons(@user) %></li>diff --git a/app/views/users/form/_admin_flag.html.erb b/app/views/users/form/_admin_flag.html.erbnew file mode 100644index 00000000000..a77037e4366--- /dev/null+++ b/app/views/users/form/_admin_flag.html.erb@@ -0,0 +1,4 @@+<div class="form--field">+ <%= f.check_box :admin,+ disabled: (@user == User.current) %>+</div>diff --git a/app/views/users/form/_auth_source.html.erb b/app/views/users/form/_auth_source.html.erbnew file mode 100644index 00000000000..8953c83c04e--- /dev/null+++ b/app/views/users/form/_auth_source.html.erb@@ -0,0 +1,10 @@+<% unless @auth_sources.empty? || OpenProject::Configuration.disable_password_login? %>+ <div class="form--field">+ <% sources = ([[t(:label_internal), ""]] + @auth_sources.collect { |a| [a.name, a.id] }) %>+ <%= f.select :auth_source_id, sources, label: :'activerecord.attributes.user.auth_source' %>+ </div>++ <div class="form--field" id="new_user_login" style="display: none;">+ <%= f.text_field :login, required: true, size: 25, disabled: true %>+ </div>+<% end %>\ No newline at end of filediff --git a/app/views/users/form/_authentication.html.erb b/app/views/users/form/_authentication.html.erbnew file mode 100644index 00000000000..28b11dc738a--- /dev/null+++ b/app/views/users/form/_authentication.html.erb@@ -0,0 +1,82 @@+<section class="form--section">+ <h3 class="form--section-title"><%=t(:label_authentication)%></h3>+ <% if @user.uses_external_authentication? %>+ <div class="form--field">+ <%= styled_label_tag nil, I18n.t('user.authentication_provider') %>+ <div class="form--field-container">+ <%= @user.authentication_provider %>+ </div>+ </div>+ <div class="form--field-instructions">+ <%= I18n.t('user.authentication_settings_disabled_due_to_external_authentication') %>+ </div>+ <% else %>+ <%= render partial: 'users/form/auth_source', locals: { f: f } %>+ <% if !OpenProject::Configuration.disable_password_login? %>+ <%+ pw_style =+ if @user.change_password_allowed?+ ''+ else+ ' style="display: none;"'+ end+ %>+ <div id="password_fields"<%= pw_style.html_safe %>>+ <% assign_random_password_enabled = params[:user] &&+ params[:user][:assign_random_password] %>+ <div class="form--field">+ <%= styled_label_tag 'user_assign_random_password',+ I18n.t(:assign_random_password, scope: :user) %>+ <div class="form--field-container">+ <%= styled_check_box_tag("user[assign_random_password]",+ "1",+ assign_random_password_enabled) %>+ </div>+ </div>++ <% unless OpenProject::Configuration.disable_password_choice? %>+ <div class="form--field">+ <%= f.password_field :password,+ required: @user.new_record?,+ disabled: assign_random_password_enabled,+ container_class: '-middle' %>+ <div class="form--field-instructions">+ <%= password_complexity_requirements %>+ </div>+ </div>+ <div class="form--field">+ <%= f.password_field :password_confirmation,+ required: @user.new_record?,+ disabled: assign_random_password_enabled,+ container_class: '-middle' %>+ </div>+ <% end %>++ <% if @user.active? -%>+ <div class="form--field send-information -hidden">+ <%= styled_label_tag 'send_information', t(:label_send_information) %>+ <div class="form--field-container">+ <%= styled_check_box_tag("send_information",+ "1",+ true) %>+ </div>+ </div>+ <% end -%>++ <div class="form--field">+ <%= f.check_box :force_password_change,+ disabled: assign_random_password_enabled %>+ </div>+ </div>+ <% else %>+ <div id="no_password_info">+ <div class="form--field">+ <%= styled_label_tag nil, I18n.t(:warning) %>+ <div class="form--field-container">+ <%= I18n.t 'user.no_login' %>+ </div>+ </div>+ </div>+ <% end %>+ <% end %>+</section>\ No newline at end of filediff --git a/app/views/users/form/_basic_attributes.html.erb b/app/views/users/form/_basic_attributes.html.erbnew file mode 100644index 00000000000..ee79e244de9--- /dev/null+++ b/app/views/users/form/_basic_attributes.html.erb@@ -0,0 +1,33 @@+<% unless @user.new_record? %>+<div class="form--field -required">+ <%= f.text_field :login,+ required: true,+ size: 25,+ container_class: '-middle' %>+</div>+<% end %>++<div class="form--field -required">+ <%= f.text_field :firstname,+ required: true,+ container_class: '-middle' %>+</div>++<div class="form--field -required">+ <%= f.text_field :lastname,+ required: true,+ container_class: '-middle' %>+</div>++<div class="form--field -required">+ <%= f.text_field :mail,+ required: true,+ container_class: '-middle' %>+</div>++<div class="form--field">+ <%= f.select :language,+ lang_options_for_select,+ prompt: "--- #{t(:actionview_instancetag_blank_option)} ---",+ container_class: '-slim' %>+</div>\ No newline at end of filediff --git a/app/views/users/form/_custom_fields.html.erb b/app/views/users/form/_custom_fields.html.erbnew file mode 100644index 00000000000..0a7746c2fb8--- /dev/null+++ b/app/views/users/form/_custom_fields.html.erb@@ -0,0 +1,4 @@+<%= render partial: 'customizable/field',+ collection: @user.custom_field_values,+ as: :value,+ locals: { form: f, input_size: 'middle' } %>\ No newline at end of filediff --git a/app/views/users/form/_mail_notifications.html.erb b/app/views/users/form/_mail_notifications.html.erbnew file mode 100644index 00000000000..4a34cf09aa2--- /dev/null+++ b/app/views/users/form/_mail_notifications.html.erb@@ -0,0 +1,4 @@+<section class="form--section">+ <h3 class="form--section-title"><%= User.human_attribute_name(:mail_notification) %></h3>+ <%= render partial: 'users/mail_notifications' %>+</section>\ No newline at end of filediff --git a/app/views/users/form/_preferences.html.erb b/app/views/users/form/_preferences.html.erbnew file mode 100644index 00000000000..9d791f5d89c--- /dev/null+++ b/app/views/users/form/_preferences.html.erb@@ -0,0 +1,4 @@+<section class="form--section">+ <h3 class="form--section-title"><%=t(:label_preferences)%></h3>+ <%= render partial: 'users/preferences', locals: {input_size: :middle } %>+</section>\ No newline at end of filediff --git a/app/views/users/new.html.erb b/app/views/users/new.html.erbindex 7fee9309edc..4c83e148c8b 100644--- a/app/views/users/new.html.erb+++ b/app/views/users/new.html.erb@@ -33,7 +33,6 @@ See docs/COPYRIGHT.rdoc for more details.<% html_title t(:label_administration), t("label_user_new") %><% local_assigns[:additional_breadcrumb] = t(:label_user_new) %>-<%= render partial: 'toolbar', locals: { new_user: true } %><%= labelled_tabular_form_for @user,url: { action: "create" },html: { class: nil, autocomplete: 'off' },diff --git a/config/initializers/menus.rb b/config/initializers/menus.rbindex d9122b71e97..832329d35f1 100644--- a/config/initializers/menus.rb+++ b/config/initializers/menus.rb@@ -76,7 +76,7 @@ Redmine::MenuManager.map :account_menu do |menu|if: Proc.new { User.current.logged? }menu.push :administration,{ controller: '/admin', action: 'index' },- if: Proc.new { User.current.admin? }+ if: Proc.new { User.current.admin? || User.current.allowed_to_globally?(:add_user) }menu.push :logout,:signout_path,if: Proc.new { User.current.logged? }@@ -124,75 +124,95 @@ endRedmine::MenuManager.map :admin_menu do |menu|menu.push :admin_overview,- { controller: '/admin' },+ { controller: '/admin', action: :index },+ if: Proc.new { User.current.admin? },caption: :label_overview,icon: 'icon2 icon-home',first: true+ menu.push :users,+ { controller: '/users' },+ if: Proc.new { !User.current.admin? && User.current.allowed_to?(:add_user, nil, global: true) },+ caption: :label_user_plural,+ icon: 'icon2 icon-group'+menu.push :users_and_permissions,{ controller: '/users' },+ if: Proc.new { User.current.admin? },caption: :label_user_and_permission,icon: 'icon2 icon-group'menu.push :user_settings,{ controller: '/users_settings' },+ if: Proc.new { User.current.admin? },caption: :label_setting_plural,parent: :users_and_permissionsmenu.push :users,{ controller: '/users' },+ if: Proc.new { User.current.admin? },caption: :label_user_plural,parent: :users_and_permissionsmenu.push :groups,{ controller: '/groups' },+ if: Proc.new { User.current.admin? },caption: :label_group_plural,parent: :users_and_permissionsmenu.push :roles,{ controller: '/roles' },+ if: Proc.new { User.current.admin? },caption: :label_role_and_permissions,parent: :users_and_permissionsmenu.push :user_avatars,{ controller: '/settings', action: 'plugin', id: :openproject_avatars },+ if: Proc.new { User.current.admin? },caption: :label_avatar_plural,parent: :users_and_permissionsmenu.push :admin_work_packages,{ controller: '/work_packages/settings' },+ if: Proc.new { User.current.admin? },caption: :label_work_package_plural,icon: 'icon2 icon-view-timeline'menu.push :work_packages_setting,{ controller: '/work_packages/settings' },+ if: Proc.new { User.current.admin? },caption: :label_setting_plural,parent: :admin_work_packagesmenu.push :types,{ controller: '/types' },+ if: Proc.new { User.current.admin? },caption: :label_type_plural,parent: :admin_work_packagesmenu.push :statuses,{ controller: '/statuses' },+ if: Proc.new { User.current.admin? },caption: :label_status,parent: :admin_work_packages,html: { class: 'statuses' }menu.push :workflows,{ controller: '/workflows', action: 'edit' },+ if: Proc.new { User.current.admin? },caption: Proc.new { Workflow.model_name.human },parent: :admin_work_packagesmenu.push :custom_fields,{ controller: '/custom_fields' },+ if: Proc.new { User.current.admin? },caption: :label_custom_field_plural,icon: 'icon2 icon-custom-fields',html: { class: 'custom_fields' }menu.push :custom_actions,{ controller: '/custom_actions' },+ if: Proc.new { User.current.admin? },caption: :'custom_actions.plural',parent: :admin_work_packages@@ -201,15 +221,17 @@ Redmine::MenuManager.map :admin_menu do |menu|caption: :'attribute_help_texts.label_plural',icon: 'icon2 icon-help2',if: Proc.new {- EnterpriseToken.allows_to?(:attribute_help_texts)+ User.current.admin? && EnterpriseToken.allows_to?(:attribute_help_texts)}menu.push :enumerations,{ controller: '/enumerations' },+ if: Proc.new { User.current.admin? },icon: 'icon2 icon-enumerations'menu.push :settings,{ controller: '/settings/general', action: 'show' },+ if: Proc.new { User.current.admin? },caption: :label_system_settings,icon: 'icon2 icon-settings2'@@ -217,36 +239,43 @@ Redmine::MenuManager.map :admin_menu do |menu|menu.push :"settings_#{node[:name]}",node[:action],caption: node[:label],+ if: Proc.new { User.current.admin? },parent: :settingsendmenu.push :email,{ controller: '/admin/mail_notifications', action: 'show' },+ if: Proc.new { User.current.admin? },caption: :'attributes.mail',icon: 'icon2 icon-mail1'menu.push :mail_notifications,{ controller: '/admin/mail_notifications', action: 'show' },+ if: Proc.new { User.current.admin? },caption: :'activerecord.attributes.user.mail_notification',parent: :emailmenu.push :incoming_mails,{ controller: '/admin/incoming_mails', action: 'show' },+ if: Proc.new { User.current.admin? },caption: :label_incoming_emails,parent: :emailmenu.push :authentication,{ controller: '/authentication', action: 'authentication_settings' },+ if: Proc.new { User.current.admin? },caption: :label_authentication,icon: 'icon2 icon-two-factor-authentication'menu.push :authentication_settings,{ controller: '/authentication', action: 'authentication_settings' },+ if: Proc.new { User.current.admin? },caption: :label_setting_plural,parent: :authenticationmenu.push :ldap_authentication,{ controller: '/ldap_auth_sources', action: 'index' },+ if: Proc.new { User.current.admin? },parent: :authentication,html: { class: 'server_authentication' },last: true,@@ -254,33 +283,39 @@ Redmine::MenuManager.map :admin_menu do |menu|menu.push :oauth_applications,{ controller: '/oauth/applications', action: 'index' },+ if: Proc.new { User.current.admin? },parent: :authentication,caption: :'oauth.application.plural',html: { class: 'oauth_applications' }menu.push :announcements,{ controller: '/announcements', action: 'edit' },+ if: Proc.new { User.current.admin? },caption: :label_announcement,icon: 'icon2 icon-news'menu.push :plugins,{ controller: '/admin', action: 'plugins' },+ if: Proc.new { User.current.admin? },last: true,icon: 'icon2 icon-plugins'menu.push :info,{ controller: '/admin', action: 'info' },+ if: Proc.new { User.current.admin? },caption: :label_information_plural,last: true,icon: 'icon2 icon-info1'menu.push :custom_style,{ controller: '/custom_styles', action: 'show' },+ if: Proc.new { User.current.admin? },caption: :label_custom_style,icon: 'icon2 icon-design'menu.push :colors,{ controller: '/colors', action: 'index' },+ if: Proc.new { User.current.admin? },caption: :'timelines.admin_menu.colors',icon: 'icon2 icon-status'@@ -288,25 +323,29 @@ Redmine::MenuManager.map :admin_menu do |menu|{ controller: '/enterprises', action: 'show' },caption: :label_enterprise_edition,icon: 'icon2 icon-headset',- if: proc { OpenProject::Configuration.ee_manager_visible? }+ if: proc { User.current.admin? && OpenProject::Configuration.ee_manager_visible? }menu.push :admin_costs,{ controller: '/settings', action: 'plugin', id: :costs },+ if: Proc.new { User.current.admin? },caption: :project_module_costs,icon: 'icon2 icon-budget'menu.push :costs_setting,{ controller: '/settings', action: 'plugin', id: :costs },+ if: Proc.new { User.current.admin? },caption: :label_setting_plural,parent: :admin_costsmenu.push :admin_backlogs,{ controller: '/settings', action: 'plugin', id: :openproject_backlogs },+ if: Proc.new { User.current.admin? },caption: :label_backlogs,icon: 'icon2 icon-backlogs'menu.push :backlogs_settings,{ controller: '/settings', action: 'plugin', id: :openproject_backlogs },+ if: Proc.new { User.current.admin? },caption: :label_setting_plural,parent: :admin_backlogsenddiff --git a/config/initializers/permissions.rb b/config/initializers/permissions.rbindex 9425fa34a4c..0367213f80f 100644--- a/config/initializers/permissions.rb+++ b/config/initializers/permissions.rb@@ -43,6 +43,19 @@ endOpenProject::AccessControl.map do |map|map.project_module nil, order: 100 do+ map.permission :add_project,+ { projects: %i[new create] },+ require: :loggedin,+ global: true++ map.permission :add_user,+ {+ users: %i[index show new create edit update resend_invitation],+ admin: %i[index]+ },+ require: :loggedin,+ global: true+map.permission :view_project,{ projects: [:show],activities: [:index] },@@ -52,11 +65,6 @@ OpenProject::AccessControl.map do |map|{ search: :index },public: true- map.permission :add_project,- { projects: %i[new create] },- require: :loggedin,- global: true-map.permission :edit_project,edit_project_hash,require: :memberdiff --git a/config/locales/en.yml b/config/locales/en.ymlindex 29c87b023df..a9eecd775e4 100644--- a/config/locales/en.yml+++ b/config/locales/en.yml@@ -587,6 +587,7 @@ en:invalid_url: 'is not a valid URL.'invalid_url_scheme: 'is not a supported protocol (allowed: %{allowed_schemes}).'less_than_or_equal_to: "must be less than or equal to %{count}."+ not_deletable: "cannot be deleted."not_current_user: "is not the current user."not_a_date: "is not a valid date."not_a_datetime: "is not a valid date time."diff --git a/docs/api/apiv3/endpoints/users.apib b/docs/api/apiv3/endpoints/users.apibindex c72663ea3ff..6cd182a01ef 100644--- a/docs/api/apiv3/endpoints/users.apib+++ b/docs/api/apiv3/endpoints/users.apib@@ -6,7 +6,7 @@| lock | Restrict the user from logging in and performing any actions | not locked; **Permission**: Administrator || show | Link to the OpenProject user page (HTML) | || unlock | Allow a locked user to login and act again | locked; **Permission**: Administrator |-| updateImmediately | Updates the user's attributes. | **Permission**: Administrator |+| updateImmediately | Updates the user's attributes. | **Permission**: Administrator, add_users global permission || delete | Permanently remove a user from the instance | **Permission**: Administrator, self-delete |## Linked Properties@@ -17,22 +17,22 @@| members | Link to collection of all the user's memberships. The list will only include the memberships in projects in which the requesting user has the necessary permissions. | MemberCollection | | READ | **Permission**: view members or manage members in any project |## Local Properties-| Property | Description | Type | Constraints | Supported operations | Condition |-| :----------: | --------------------------------------------------------- | -------- | ---------------------------------------------------- | -------------------- | ----------------------------------------------------------- |-| id | User's id | Integer | x > 0 | READ | |-| login | User's login name | String | unique, 256 max length | READ / WRITE | **Permission**: Administrator |-| firstName | User's first name | String | 30 max length | READ / WRITE | **Permission**: Administrator |-| lastName | User's last name | String | 30 max length | READ / WRITE | **Permission**: Administrator |-| name | User's full name, formatting depends on instance settings | String | | READ | |-| email | User's email address | String | unique, 60 max length | READ / WRITE | E-Mail address not hidden, **Permission**: Administrator |-| admin | Flag indicating whether or not the user is an admin | Boolean | in: [true, false] | READ / WRITE | **Permission**: Administrator |-| avatar | URL to user's avatar | Url | | READ | |-| status | The current activation status of the user (see below) | String | in: ["active", "registered", "locked", "invited"] | READ | |-| language | User's language | String | ISO 639-1 | READ / WRITE | **Permission**: Administrator |-| password | User's password for the default password authentication | String | | WRITE | **Permission**: Administrator |-| identity_url | User's identity_url for OmniAuth authentication | String | | READ / WRITE | **Permission**: Administrator |-| createdAt | Time of creation | DateTime | | READ | |-| updatedAt | Time of the most recent change to the user | DateTime | | READ | |+| Property | Description | Type | Constraints | Supported operations | Condition |+| :----------: | --------------------------------------------------------- | -------- | ---------------------------------------------------- | -------------------- | ----------------------------------------------------------- |+| id | User's id | Integer | x > 0 | READ | |+| login | User's login name | String | unique, 256 max length | READ / WRITE | **Permission**: Administrator, add_users global permission |+| firstName | User's first name | String | 30 max length | READ / WRITE | **Permission**: Administrator, add_users global permission |+| lastName | User's last name | String | 30 max length | READ / WRITE | **Permission**: Administrator, add_users global permission |+| name | User's full name, formatting depends on instance settings | String | | READ | |+| email | User's email address | String | unique, 60 max length | READ / WRITE | E-Mail address not hidden, **Permission**: Administrator, add_users global permission |+| admin | Flag indicating whether or not the user is an admin | Boolean | in: [true, false] | READ / WRITE | **Permission**: Administrator |+| avatar | URL to user's avatar | Url | | READ | |+| status | The current activation status of the user (see below) | String | in: ["active", "registered", "locked", "invited"] | READ | |+| language | User's language | String | ISO 639-1 | READ / WRITE | **Permission**: Administrator, add_users global permission |+| password | User's password for the default password authentication | String | | WRITE | **Permission**: Administrator |+| identity_url | User's identity_url for OmniAuth authentication | String | | READ / WRITE | **Permission**: Administrator |+| createdAt | Time of creation | DateTime | | READ | |+| updatedAt | Time of the most recent change to the user | DateTime | | READ | |The `status` of a user can be one of:@@ -162,7 +162,7 @@ When calling this endpoint the client provides a single object, containing at leReturned if the client does not have sufficient permissions.- **Required permission:** Administrators only+ **Required permission:** Administrators, add_users global permission+ Body@@ -409,7 +409,7 @@ Permanently deletes the specified user account.## List Users [GET]-Lists users. Only administrators have permission to do this.+Lists users. Only administrators or users with add_users global permission have permission to do this.+ Parameters+ offset = `1` (optional, integer, `25`) ... Page number inside the requested collection.@@ -459,7 +459,7 @@ Lists users. Only administrators have permission to do this.## Create User [POST]-Creates a new user. Only administrators have permission to do so.+Creates a new user. Only administrators and users with add_users global permission are allowed to do so.When calling this endpoint the client provides a single object, containing at least the properties and links that are required, in the body.Valid values for `status`:diff --git a/lib/api/utilities/endpoints/delete.rb b/lib/api/utilities/endpoints/delete.rbindex 6fd729f4989..93ad2760bda 100644--- a/lib/api/utilities/endpoints/delete.rb+++ b/lib/api/utilities/endpoints/delete.rb@@ -39,11 +39,13 @@ module APIdef initialize(model:,instance_generator: default_instance_generator(model),process_service: nil,+ success_status: 204,api_name: model.name.demodulize)self.model = modelself.instance_generator = instance_generatorself.process_service = process_service || deduce_process_serviceself.api_name = api_name+ self.success_status = success_statusenddef mount@@ -75,14 +77,11 @@ module APIendend- def success_status- 204- end-attr_accessor :model,:instance_generator,:process_service,- :api_name+ :api_name,+ :success_statusprivatediff --git a/lib/api/v3/principals/principal_representer.rb b/lib/api/v3/principals/principal_representer.rbindex 95c409679af..d3589f191bb 100644--- a/lib/api/v3/principals/principal_representer.rb+++ b/lib/api/v3/principals/principal_representer.rb@@ -39,14 +39,6 @@ module APIinclude API::Decorators::DatePropertyinclude ::API::Caching::CachedRepresenter- def self.create(user, current_user:)- new(user, current_user: current_user)- end-- def initialize(user, current_user:)- super(user, current_user: current_user)- end-self_linklink :memberships,diff --git a/lib/api/v3/users/update_user.rb b/lib/api/v3/users/user_payload_representer.rbsimilarity index 53%rename from lib/api/v3/users/update_user.rbrename to lib/api/v3/users/user_payload_representer.rbindex 6bd44e8b6da..b1c8abfe8b1 100644--- a/lib/api/v3/users/update_user.rb+++ b/lib/api/v3/users/user_payload_representer.rb@@ -1,3 +1,5 @@+#-- encoding: UTF-8+#-- copyright# OpenProject is an open source project management software.# Copyright (C) 2012-2021 the OpenProject GmbH@@ -26,41 +28,11 @@# See docs/COPYRIGHT.rdoc for more details.#++-require 'api/v3/users/user_representer'-require 'users/update_user_service'-module APImodule V3module Users- module UpdateUser- ##- # Call the user create service for the current request- # and return the service result API representation- def update_user(request_body, current_user)- payload = ::API::V3::Users::UserRepresenter.create(@user, current_user: current_user)- updated_user = payload.from_hash(request_body)-- result = call_service(updated_user, current_user)- represent_service_result(result, current_user)- end-- private-- def represent_service_result(result, current_user)- if result.success?- ::API::V3::Users::UserRepresenter.create(result.result, current_user: current_user)- else- fail ::API::Errors::ErrorBase.create_and_merge_errors(result.errors)- end- end-- def call_service(updated_user, current_user)- create_service = ::Users::UpdateUserService.new(- current_user: current_user,- user: updated_user- )- create_service.call- end+ class UserPayloadRepresenter < UserRepresenter+ include ::API::Utilities::PayloadRepresenterendendenddiff --git a/lib/api/v3/users/user_representer.rb b/lib/api/v3/users/user_representer.rbindex 724bdeeca8b..fe9bf6e7e95 100644--- a/lib/api/v3/users/user_representer.rb+++ b/lib/api/v3/users/user_representer.rb@@ -37,14 +37,6 @@ module APIcached_representer key_parts: %i(auth_source),dependencies: ->(*) { avatar_cache_dependencies }- def self.create(user, current_user:)- new(user, current_user: current_user)- end-- def initialize(user, current_user:)- super(user, current_user: current_user)- end-self_linklink :showUser do@@ -218,7 +210,7 @@ module APIenddef current_user_can_delete_represented?- current_user && ::Users::DeleteService.deletion_allowed?(represented, current_user)+ current_user && ::Users::DeleteContract.deletion_allowed?(represented, current_user)endprivatediff --git a/lib/api/v3/users/users_api.rb b/lib/api/v3/users/users_api.rbindex 91d8d64447a..cffe0aec27a 100644--- a/lib/api/v3/users/users_api.rb+++ b/lib/api/v3/users/users_api.rb@@ -47,18 +47,17 @@ module APIfail ::API::Errors::InvalidUserStatusTransitionendend++ def authorize_user_cru_allowed+ authorize_by_with_raise(current_user.allowed_to_globally?(:add_user))+ endendresources :users do- helpers ::API::V3::Users::CreateUser-- post do- authorize_admin- create_user(request_body, current_user)- end+ post &::API::V3::Utilities::Endpoints::Create.new(model: User).mountget do- authorize_admin+ authorize_user_cru_allowedquery = ParamsToQueryService.new(User, current_user).call(params)@@ -78,8 +77,6 @@ module APIrequires :id, desc: 'User\'s id'endroute_param :id do- helpers ::API::V3::Users::UpdateUser-after_validation do@user =if params[:id] == 'me'@@ -89,22 +86,9 @@ module APIendend- get do- UserRepresenter.new(@user, current_user: current_user)- end-- patch do- authorize_admin- update_user(request_body, current_user)- end-- delete do- if ::Users::DeleteService.new(@user, current_user).call- status 202- else- fail ::API::Errors::Unauthorized- end- end+ get &::API::V3::Utilities::Endpoints::Show.new(model: User).mount+ patch &::API::V3::Utilities::Endpoints::Update.new(model: User).mount+ delete &::API::V3::Utilities::Endpoints::Delete.new(model: User, success_status: 202).mountnamespace :lock do# Authenticate lock transitionsdiff --git a/lib/open_project/ui/extensible_tabs.rb b/lib/open_project/ui/extensible_tabs.rbindex e98e8422570..425cdbcd0e2 100644--- a/lib/open_project/ui/extensible_tabs.rb+++ b/lib/open_project/ui/extensible_tabs.rb@@ -65,20 +65,22 @@ module OpenProjectname: 'memberships',partial: 'users/memberships',path: ->(params) { tab_edit_user_path(params[:user], tab: :memberships) },- label: :label_project_plural+ label: :label_project_plural,+ only_if: ->(*) { User.current.admin? }},{name: 'groups',partial: 'users/groups',path: ->(params) { tab_edit_user_path(params[:user], tab: :groups) },label: :label_group_plural,- if: ->(*) { Group.all.any? }+ only_if: ->(*) { User.current.admin? && Group.any? }},{name: 'global_roles',partial: 'users/global_roles',path: ->(params) { tab_edit_user_path(params[:user], tab: :global_roles) },- label: :label_global_roles+ label: :label_global_roles,+ only_if: ->(*) { User.current.admin? }}]enddiff --git a/modules/avatars/lib/open_project/avatars/engine.rb b/modules/avatars/lib/open_project/avatars/engine.rbindex 90bd503c7e2..1c0dc40b7cb 100644--- a/modules/avatars/lib/open_project/avatars/engine.rb+++ b/modules/avatars/lib/open_project/avatars/engine.rb@@ -54,7 +54,7 @@ module OpenProject::Avatarspartial: 'avatars/users/avatar_tab',path: ->(params) { tab_edit_user_path(params[:user], tab: :avatar) },label: :label_avatar,- only_if: ->(*) { ::OpenProject::Avatars::AvatarManager.avatars_enabled? }+ only_if: ->(*) { User.current.admin? && ::OpenProject::Avatars::AvatarManager.avatars_enabled? }initializer 'patch avatar helper' do# This is required to be an initializer,diff --git a/modules/backlogs/lib/open_project/backlogs/hooks/user_settings_hook.rb b/modules/backlogs/lib/open_project/backlogs/hooks/user_settings_hook.rbindex 8b8074eae93..f5ba699f318 100644--- a/modules/backlogs/lib/open_project/backlogs/hooks/user_settings_hook.rb+++ b/modules/backlogs/lib/open_project/backlogs/hooks/user_settings_hook.rb@@ -37,12 +37,14 @@ class OpenProject::Backlogs::Hooks::UserSettingsHook < Redmine::Hook::ViewListendef service_update_user_before_save(context = {})params = context[:params]user = context[:user]- return unless params[:backlogs]- versions_default_fold_state = params.dig(:backlogs, :versions_default_fold_state) || 'open'+ backlogs_params = params.delete(:backlogs)+ return unless backlogs_params++ versions_default_fold_state = backlogs_params[:versions_default_fold_state] || 'open'user.backlogs_preference(:versions_default_fold_state, versions_default_fold_state)- color = params.dig(:backlogs, :task_color) || ''+ color = backlogs_params[:task_color] || ''if color == '' || color.match(/^#[A-Fa-f0-9]{6}$/)user.backlogs_preference(:task_color, color)enddiff --git a/modules/backlogs/lib/open_project/backlogs/patches/permitted_params_patch.rb b/modules/backlogs/lib/open_project/backlogs/patches/permitted_params_patch.rbindex f28c5a9543f..b715718aade 100644--- a/modules/backlogs/lib/open_project/backlogs/patches/permitted_params_patch.rb+++ b/modules/backlogs/lib/open_project/backlogs/patches/permitted_params_patch.rb@@ -42,6 +42,11 @@ module OpenProject::Backlogs::Patches::PermittedParamsPatchpermitted_paramsend++ def my_account_settings+ backlogs_params = params.fetch(:backlogs, {}).permit(:task_color, :versions_default_fold_state)+ super.merge(backlogs: backlogs_params)+ endendendPermittedParams.send(:include, OpenProject::Backlogs::Patches::PermittedParamsPatch)diff --git a/modules/costs/lib/costs/engine.rb b/modules/costs/lib/costs/engine.rbindex bd330fa6f5d..b8720543785 100644--- a/modules/costs/lib/costs/engine.rb+++ b/modules/costs/lib/costs/engine.rb@@ -89,6 +89,7 @@ module Costsmenu :admin_menu,:cost_types,{ controller: '/cost_types', action: 'index' },+ if: ->(*) { User.current.admin? },parent: :admin_costs,caption: :label_cost_type_pluralend@@ -104,6 +105,7 @@ module Costsname: 'rates',partial: 'users/rates',path: ->(params) { tab_edit_user_path(params[:user], tab: :rates) },+ only_if: ->(*) { User.current.admin? },label: :caption_rate_historyadd_api_path :cost_entry do |id|diff --git a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rb b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rbindex 674f9b8402e..d6823ba0f33 100644--- a/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rb+++ b/modules/two_factor_authentication/lib/open_project/two_factor_authentication/engine.rb@@ -43,7 +43,7 @@ module OpenProject::TwoFactorAuthenticationpartial: 'users/two_factor_authentication',path: ->(params) { tab_edit_user_path(params[:user], tab: :two_factor_authentication) },label: 'two_factor_authentication.label_two_factor_authentication',- only_if: ->(*) { OpenProject::TwoFactorAuthentication::TokenStrategyManager.enabled? }+ only_if: ->(*) { User.current.admin? && OpenProject::TwoFactorAuthentication::TokenStrategyManager.enabled? }config.to_prepare do# Verify the validity of the configurationdiff --git a/modules/webhooks/lib/open_project/webhooks/engine.rb b/modules/webhooks/lib/open_project/webhooks/engine.rbindex 7b6088d5110..bf08d9b83a7 100644--- a/modules/webhooks/lib/open_project/webhooks/engine.rb+++ b/modules/webhooks/lib/open_project/webhooks/engine.rb@@ -40,6 +40,7 @@ module OpenProject::Webhooksmenu :admin_menu,:plugin_webhooks,{ controller: 'webhooks/outgoing/admin', action: :index },+ if: Proc.new { User.current.admin? },after: :plugins,caption: ->(*) { I18n.t('webhooks.plural') },icon: 'icon2 icon-relations'diff --git a/spec/contracts/users/create_contract_spec.rb b/spec/contracts/users/create_contract_spec.rbindex 96c94eb98d7..5189e59c65f 100644--- a/spec/contracts/users/create_contract_spec.rb+++ b/spec/contracts/users/create_contract_spec.rb@@ -73,7 +73,62 @@ describe Users::CreateContract doendend- context 'when not admin' do+ context 'when global user' do+ let!(:global_add_user_role) { FactoryBot.create :global_role, name: 'Add user', permissions: %i[add_user] }+ let(:current_user) do+ user = FactoryBot.create(:user)++ FactoryBot.create(:global_member,+ principal: user,+ roles: [global_add_user_role])++ user+ end++ describe 'can invite user' do+ before do+ user.password = user.password_confirmation = nil+ user.mail = '[email protected]'+ user.invite+ end++ it_behaves_like 'is valid'+ end++ describe 'cannot set the password' do+ before do+ user.password = user.password_confirmation = 'password!password!'+ end++ it 'is invalid' do+ expect_valid(false, password: %i(error_readonly))+ end+ end++ describe 'cannot set the auth_source' do+ let!(:auth_source) { FactoryBot.create :auth_source }++ before do+ user.auth_source = auth_source+ end++ it 'is invalid' do+ expect_valid(false, auth_source_id: %i(error_readonly))+ end+ end++ describe 'cannot set the identity url' do+ before do+ user.identity_url = 'saml:123412foo'+ end++ it 'is invalid' do+ expect_valid(false, identity_url: %i(error_readonly))+ end+ end+ end++ context 'when unauthorized user' dolet(:current_user) { FactoryBot.build_stubbed(:user) }it 'is invalid' dodiff --git a/spec/controllers/my_controller_spec.rb b/spec/controllers/my_controller_spec.rbindex 569ff20c4d4..adb9dee8add 100644--- a/spec/controllers/my_controller_spec.rb+++ b/spec/controllers/my_controller_spec.rb@@ -70,8 +70,8 @@ describe MyController, type: :controller doit 'should show an error message' doassert_response :successassert_template 'password'- expect(user.errors.keys).to eq([:password_confirmation])- expect(user.errors.values.flatten.join('')).to include("doesn't match")+ expect(user.errors.attribute_names).to eq([:password_confirmation])+ expect(user.errors.map(&:message).flatten.join('')).to include("doesn't match")endend@@ -156,21 +156,20 @@ describe MyController, type: :controller dobefore doas_logged_in_user user douser.pref.self_notified = false+ user.pref.auto_hide_popups = true- patch :update_settings, params: { user: { language: 'en' } }+ patch :update_settings, params: { user: { language: 'en' }, pref: { auto_hide_popups: 0 } }endend- it 'does not alter the email preferences' do+ it 'updates the settings appropriately', :aggregate_failures do+ expect(assigns(:user).language).to eq 'en'expect(assigns(:user).pref.self_notified?).to be_falsey- end+ expect(assigns(:user).pref.auto_hide_popups?).to be_falsey- it 'redirects to settings' doexpect(request.path).to eq(my_settings_path)- end-- it 'has a successful flash' doexpect(flash[:notice]).to eql I18n.t(:notice_account_updated)+endcontext 'when user is invalid' dodiff --git a/spec/features/users/create_spec.rb b/spec/features/users/create_spec.rbindex 969d562627b..c6252718df8 100644--- a/spec/features/users/create_spec.rb+++ b/spec/features/users/create_spec.rb@@ -40,7 +40,7 @@ describe 'create users', type: :feature, selenium: true dolet(:token) { mail_body.scan(/token=(.*)$/).first.first.strip }before do- allow(User).to receive(:current).and_return admin+ allow(User).to receive(:current).and_return current_userendshared_examples_for 'successful user creation' do@@ -143,4 +143,48 @@ describe 'create users', type: :feature, selenium: true doendendend++ context 'as global user' do+ using_shared_fixtures :global_add_user+ let(:current_user) { global_add_user }++ context 'with internal authentication' do+ before do+ visit new_user_path++ new_user_page.fill_in! first_name: 'bobfirst',+ last_name: 'boblast',+ email: '[email protected]'++ perform_enqueued_jobs do+ new_user_page.submit!+ end+ end++ it_behaves_like 'successful user creation' do+ describe 'activation' do+ before do+ allow(User).to receive(:current).and_call_original++ visit "/account/activate?token=#{token}"+ end++ it 'shows the registration form' do+ expect(page).to have_text 'Create a new account'+ end++ it 'registers the user upon submission' do+ fill_in 'user_password', with: 'foobarbaz1'+ fill_in 'user_password_confirmation', with: 'foobarbaz1'++ click_button 'Create'++ # landed on the 'my page'+ expect(page).to have_text 'Welcome, your account has been activated. You are logged in now.'+ expect(page).to have_link 'bobfirst boblast'+ end+ end+ end+ end+ endenddiff --git a/spec/features/users/delete_spec.rb b/spec/features/users/delete_spec.rbindex 686d46d7e62..957883a42fe 100644--- a/spec/features/users/delete_spec.rb+++ b/spec/features/users/delete_spec.rb@@ -66,6 +66,31 @@ describe 'user deletion: ', type: :feature, js: true doendend+ context 'user with global add role' do+ let!(:user) { FactoryBot.create :user }+ let!(:global_add_user_role) { FactoryBot.create :global_role, name: 'Add user', permissions: %i[add_user] }+ let(:current_user) do+ user = FactoryBot.create(:user)++ FactoryBot.create(:global_member,+ principal: user,+ roles: [global_add_user_role])++ user+ end++ it 'can not delete even if settings allow it', js: true do+ Setting.users_deletable_by_admins = 1+ visit edit_user_path(user)++ expect(page).to have_content "#{user.firstname} #{user.lastname}"+ expect(page).to_not have_content 'Delete account'++ visit deletion_info_user_path(user)+ expect(page).to have_text 'Error 404'+ end+ end+context 'admin user' dolet!(:user) { FactoryBot.create :user }let(:user_password) { 'admin! * 4' }diff --git a/spec/features/users/edit_users_spec.rb b/spec/features/users/edit_users_spec.rbindex 83cc48bdd95..bf18add3efd 100644--- a/spec/features/users/edit_users_spec.rb+++ b/spec/features/users/edit_users_spec.rb@@ -31,7 +31,7 @@ require 'spec_helper'describe 'edit users', type: :feature, js: true dousing_shared_fixtures :adminlet(:current_user) { admin }- let(:user) { FactoryBot.create :user }+ let(:user) { FactoryBot.create :user, mail: '[email protected]' }let!(:auth_source) { FactoryBot.create :auth_source }@@ -83,4 +83,43 @@ describe 'edit users', type: :feature, js: true doexpect(user_password).to be_visibleendend++ context 'as global user' do+ using_shared_fixtures :global_add_user+ let(:current_user) { global_add_user }++ it 'can too edit the user' do+ visit edit_user_path(user)++ expect(page).to have_no_selector('.admin-overview-menu-item', text: 'Overview')+ expect(page).to have_no_selector('.users-and-permissions-menu-item', text: 'Users & Permissions')+ expect(page).to have_selector('.users-menu-item.selected', text: 'Users')++ expect(page).to have_no_selector 'select#user_auth_source_id'+ expect(page).to have_no_selector 'input#user_password'++ expect(page).to have_selector '#user_login'+ expect(page).to have_selector '#user_firstname'+ expect(page).to have_selector '#user_lastname'+ expect(page).to have_selector '#user_mail'++ fill_in 'user[firstname]', with: 'NewName', fill_options: { clear: :backspace }++ click_on 'Save'++ expect(page).to have_selector('.flash.notice', text: 'Successful update.')++ user.reload++ expect(user.firstname).to eq 'NewName'+ end++ it 'can reinvite the user' do+ visit edit_user_path(user)++ click_on 'Send invitation'++ expect(page).to have_selector('.flash.notice', text: 'An invitation has been sent to [email protected]')+ end+ endenddiff --git a/spec/features/users/index_spec.rb b/spec/features/users/index_spec.rbindex 61215f22fdb..26e92a4cd0a 100644--- a/spec/features/users/index_spec.rb+++ b/spec/features/users/index_spec.rb@@ -29,7 +29,7 @@require 'spec_helper'describe 'index users', type: :feature do- let!(:admin) { FactoryBot.create :admin, created_at: 1.hour.ago }+ let!(:current_user) { FactoryBot.create :admin, created_at: 1.hour.ago }let!(:anonymous) { FactoryBot.create :anonymous }let!(:active_user) { FactoryBot.create :user, created_at: 1.minute.ago }let!(:registered_user) { FactoryBot.create :user, status: User::STATUSES[:registered] }@@ -37,7 +37,7 @@ describe 'index users', type: :feature dolet(:index_page) { Pages::Admin::Users::Index.new }before do- login_as(admin)+ login_as(current_user)endit 'shows the users by status and allows status manipulations',@@ -47,16 +47,16 @@ describe 'index users', type: :feature do# Order is by id, asc# so first ones created are on top.- index_page.expect_listed(admin, active_user, registered_user, invited_user)+ index_page.expect_listed(current_user, active_user, registered_user, invited_user)index_page.order_by('Created on')- index_page.expect_listed(invited_user, registered_user, active_user, admin)+ index_page.expect_listed(invited_user, registered_user, active_user, current_user)index_page.order_by('Created on')- index_page.expect_listed(admin, active_user, registered_user, invited_user)+ index_page.expect_listed(current_user, active_user, registered_user, invited_user)index_page.lock_user(active_user)- index_page.expect_listed(admin, active_user, registered_user, invited_user)+ index_page.expect_listed(current_user, active_user, registered_user, invited_user)index_page.expect_user_locked(active_user)expect(active_user.reload)@@ -66,14 +66,14 @@ describe 'index users', type: :feature doindex_page.expect_listed(active_user)index_page.filter_by_status('active')- index_page.expect_listed(admin)+ index_page.expect_listed(current_user)index_page.filter_by_status('locked permanently')index_page.unlock_user(active_user)index_page.expect_non_listedindex_page.filter_by_status('active')- index_page.expect_listed(admin, active_user)+ index_page.expect_listed(current_user, active_user)index_page.filter_by_name(active_user.lastname[0..-3])index_page.expect_listed(active_user)@@ -82,7 +82,7 @@ describe 'index users', type: :feature doactive_user.update(failed_login_count: 6,last_failed_login_on: 9.minutes.ago)index_page.clear_filters- index_page.expect_listed(admin, active_user, registered_user, invited_user)+ index_page.expect_listed(current_user, active_user, registered_user, invited_user)index_page.filter_by_status('locked temporarily')index_page.expect_listed(active_user)@@ -109,7 +109,7 @@ describe 'index users', type: :feature doindex_page.expect_non_listedindex_page.filter_by_status('active')- index_page.expect_listed(admin, active_user)+ index_page.expect_listed(current_user, active_user)# activate registered userindex_page.filter_by_status('registered')@@ -118,6 +118,16 @@ describe 'index users', type: :feature doindex_page.activate_user(registered_user)index_page.filter_by_status('active')- index_page.expect_listed(admin, active_user, registered_user)+ index_page.expect_listed(current_user, active_user, registered_user)+ end++ context 'as global user' do+ using_shared_fixtures :global_add_user+ let(:current_user) { global_add_user }++ it 'can too visit the page' do+ index_page.visit!+ index_page.expect_listed(current_user, active_user, registered_user, invited_user)+ endendenddiff --git a/spec/features/users/invitation_spec.rb b/spec/features/users/invitation_spec.rbindex 5039c8c4ee2..eda8ce73344 100644--- a/spec/features/users/invitation_spec.rb+++ b/spec/features/users/invitation_spec.rb@@ -29,17 +29,14 @@require 'spec_helper'feature 'invitation spec', type: :feature, js: true do- using_shared_fixtures :admin- let(:current_user) { admin }let(:user) { FactoryBot.create :invited_user, mail: '[email protected]' }before doallow(User).to receive(:current).and_return current_user-- visit edit_user_path(user)end- scenario 'admin resends the invitation' do+ shared_examples 'resends the invitation' do+ visit edit_user_path(user)click_on I18n.t(:label_send_invitation)expect(page).to have_text 'An invitation has been sent to [email protected].'@@ -55,4 +52,14 @@ feature 'invitation spec', type: :feature, js: true doexpect(page).to have_selector('.op-modal--modal-header', text: 'Welcome to OpenProject')end++ context 'as admin' do+ using_shared_fixtures :admin+ let(:current_user) { admin }+ end++ context 'as global user' do+ using_shared_fixtures :global_add_user+ let(:current_user) { global_add_user }+ endenddiff --git a/spec/lib/api/v3/users/user_representer_spec.rb b/spec/lib/api/v3/users/user_representer_spec.rbindex 7ce03efbc92..7b09205fff2 100644--- a/spec/lib/api/v3/users/user_representer_spec.rb+++ b/spec/lib/api/v3/users/user_representer_spec.rb@@ -191,11 +191,23 @@ describe ::API::V3::Users::UserRepresenter doexpect(subject).to have_json_path('_links/unlock/href')endend++ context 'when deletion is allowed' do+ before do+ allow(Users::DeleteContract).to receive(:deletion_allowed?)+ .with(user, current_user)+ .and_return(true)+ end++ it 'should link to delete' do+ expect(subject).to have_json_path('_links/delete/href')+ end+ endendcontext 'when deletion is allowed' dobefore do- allow(Users::DeleteService).to receive(:deletion_allowed?)+ allow(Users::DeleteContract).to receive(:deletion_allowed?).with(user, current_user).and_return(true)end@@ -207,7 +219,7 @@ describe ::API::V3::Users::UserRepresenter docontext 'when deletion is not allowed' dobefore do- allow(Users::DeleteService).to receive(:deletion_allowed?)+ allow(Users::DeleteContract).to receive(:deletion_allowed?).with(user, current_user).and_return(false)enddiff --git a/spec/models/permitted_params_spec.rb b/spec/models/permitted_params_spec.rbindex 65e6124110b..b3d5f7aea4c 100644--- a/spec/models/permitted_params_spec.rb+++ b/spec/models/permitted_params_spec.rb@@ -523,8 +523,10 @@ describe PermittedParams, type: :model docontext 'non-admin' dolet(:hash) { Hash[admin_permissions.zip(admin_permissions)] }- it 'permits nothing' do- expect(subject).to eq({})+ it 'permits default permissions' do+ expect(subject.keys).to match_array(+ %w[custom_fields firstname lastname language mail mail_notification]+ )endenddiff --git a/spec/requests/api/v3/user/create_user_common_examples.rb b/spec/requests/api/v3/user/create_user_common_examples.rbnew file mode 100644index 00000000000..87b7ff9125b--- /dev/null+++ b/spec/requests/api/v3/user/create_user_common_examples.rb@@ -0,0 +1,155 @@+#-- encoding: UTF-8+#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2020 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.++shared_context 'represents the created user' do |expected_attributes|+ it 'returns the represented user' do+ send_request++ expect(last_response.status).to eq(201)+ expect(last_response.body).to have_json_type(Object).at_path('_links')+ expect(last_response.body)+ .to be_json_eql('User'.to_json)+ .at_path('_type')++ parameters.merge!(expected_attributes) if expected_attributes++ user = User.find_by!(login: parameters.fetch(:login, parameters[:email]))+ expect(user.firstname).to eq(parameters[:firstName])+ expect(user.lastname).to eq(parameters[:lastName])+ expect(user.mail).to eq(parameters[:email])+ end+end++shared_examples 'property is not writable' do |attributeName|+ it 'returns an error for the unwritable property' do+ send_request++ attr = JSON.parse(last_response.body).dig "_embedded", "details", "attribute"++ expect(last_response.status).to eq 422+ expect(attr).to eq attributeName+ end+end++shared_examples 'create user request flow' do+ let(:errors) { parse_json(last_response.body)['_embedded']['errors'] }++ describe 'empty request body' do+ let(:parameters) { {} }++ it 'returns an erroneous response' do+ send_request++ expect(last_response.status).to eq(422)++ expect(errors.count).to eq(5)+ expect(errors.collect { |el| el['_embedded']['details']['attribute'] })+ .to contain_exactly('password', 'login', 'firstname', 'lastname', 'email')++ expect(last_response.body)+ .to be_json_eql('urn:openproject-org:api:v3:errors:MultipleErrors'.to_json)+ .at_path('errorIdentifier')+ end+ end++ describe 'invited status' do+ let(:status) { 'invited' }+ let(:invitation_request) {+ {+ status: status,+ email: '[email protected]'+ }+ }++ describe 'invitation successful' do+ before do+ expect(OpenProject::Notifications).to receive(:send) do |event, _|+ expect(event).to eq 'user_invited'+ end+ end++ context 'only mail set' do+ let(:parameters) { invitation_request }++ it_behaves_like 'represents the created user',+ firstName: 'foo',+ lastName: '@example.org'++ it 'sets the other attributes' do+ send_request++ user = User.find_by!(login: '[email protected]')+ expect(user.firstname).to eq('foo')+ expect(user.lastname).to eq('@example.org')+ expect(user.mail).to eq('[email protected]')+ end+ end++ context 'mail and name set' do+ let(:parameters) { invitation_request.merge(firstName: 'First', lastName: 'Last') }++ it_behaves_like 'represents the created user'+ end+ end++ context 'missing email' do+ let(:parameters) { { status: status } }++ it 'marks the mail as missing' do+ send_request++ expect(last_response.body)+ .to be_json_eql('urn:openproject-org:api:v3:errors:MultipleErrors'.to_json)+ .at_path('errorIdentifier')++ expect(errors.count).to eq 4++ attributes = errors.map { |error| error.dig('_embedded', 'details', 'attribute') }+ expect(attributes).to contain_exactly('login', 'firstname', 'lastname', 'email')+ end+ end+ end++ describe 'invalid status' do+ let(:parameters) { { status: 'blablu' } }++ it 'returns an erroneous response' do+ send_request++ expect(last_response.status).to eq(422)++ expect(errors).not_to be_empty+ expect(last_response.body)+ .to be_json_eql('urn:openproject-org:api:v3:errors:MultipleErrors'.to_json)+ .at_path('errorIdentifier')++ expect(errors.collect { |el| el['message'] })+ .to include 'Status is not a valid status for new users.'+ end+ end+end\ No newline at end of filediff --git a/spec/requests/api/v3/user/create_user_resource_spec.rb b/spec/requests/api/v3/user/create_user_resource_spec.rbindex b179c7002f5..f54a9236915 100644--- a/spec/requests/api/v3/user/create_user_resource_spec.rb+++ b/spec/requests/api/v3/user/create_user_resource_spec.rb@@ -28,16 +28,25 @@require 'spec_helper'require 'rack/test'+require_relative './create_user_common_examples'describe ::API::V3::Users::UsersAPI, type: :request doinclude API::V3::Utilities::PathHelperlet(:path) { api_v3_paths.users }- let(:user) { FactoryBot.build(:admin) }- let(:parameters) { {} }+ let(:parameters) {+ {+ status: 'active',+ login: 'myusername',+ firstName: 'Foo',+ lastName: 'Bar',+ email: '[email protected]',+ language: 'de'+ }+ }before do- login_as(user)+ login_as(current_user)enddef send_request@@ -45,56 +54,10 @@ describe ::API::V3::Users::UsersAPI, type: :request dopost path, parameters.to_jsonend- let(:errors) { parse_json(last_response.body)['_embedded']['errors'] }-- shared_context 'represents the created user' do |expected_attributes|- it 'returns the represented user' do- send_request-- expect(last_response.status).to eq(201)- expect(last_response.body).to have_json_type(Object).at_path('_links')- expect(last_response.body)- .to be_json_eql('User'.to_json)- .at_path('_type')-- parameters.merge!(expected_attributes) if expected_attributes+ describe 'admin user' do+ let(:current_user) { FactoryBot.build(:admin) }- user = User.find_by!(login: parameters.fetch(:login, parameters[:email]))- expect(user.firstname).to eq(parameters[:firstName])- expect(user.lastname).to eq(parameters[:lastName])- expect(user.mail).to eq(parameters[:email])- end- end-- describe 'empty request body' do- it 'returns an erroneous response' do- send_request-- expect(last_response.status).to eq(422)-- expect(errors.count).to eq(5)- expect(errors.collect { |el| el['_embedded']['details']['attribute'] })- .to contain_exactly('password', 'login', 'firstname', 'lastname', 'email')-- expect(last_response.body)- .to be_json_eql('urn:openproject-org:api:v3:errors:MultipleErrors'.to_json)- .at_path('errorIdentifier')- end- end-- describe 'active status' do- let(:status) { 'active' }-- let(:parameters) {- {- status: status,- login: 'myusername',- firstName: 'Foo',- lastName: 'Bar',- email: '[email protected]',- language: 'de'- }- }+ it_behaves_like 'create user request flow'context 'with auth_source' dolet(:auth_source_id) { 'some_ldap' }@@ -149,144 +112,141 @@ describe ::API::V3::Users::UsersAPI, type: :request do}end- it 'returns an error for the auth_source attribute' do+ it 'returns an error on that attribute' dosend_request-- attr = JSON.parse(last_response.body).dig "_embedded", "details", "attribute"- expect(last_response.status).to eq 422- expect(attr).to eq "authSource"+ expect(last_response.status).to eq(422)++ expect(last_response.body)+ .to be_json_eql('authSource'.to_json)+ .at_path('_embedded/details/attribute')++ expect(last_response.body)+ .to be_json_eql('urn:openproject-org:api:v3:errors:PropertyConstraintViolation'.to_json)+ .at_path('errorIdentifier')endendend- context 'with identity_url' do- let(:identity_url) { 'google:3289272389298' }-- before do- parameters[:identityUrl] = identity_url- end+ describe 'active status' do+ let(:parameters) {+ {+ status: 'active',+ login: 'myusername',+ firstName: 'Foo',+ lastName: 'Bar',+ email: '[email protected]',+ language: 'de'+ }+ }- it 'creates the user with the given identity_url' do- send_request+ context 'with identity_url' do+ let(:identity_url) { 'google:3289272389298' }- user = User.find_by(login: parameters[:login])+ before do+ parameters[:identityUrl] = identity_url+ end- expect(user.identity_url).to eq identity_url- end+ it 'creates the user with the given identity_url' do+ send_request- it_behaves_like 'represents the created user'- end+ user = User.find_by(login: parameters[:login])- context 'with password' do- let(:password) { 'admin!admin!' }+ expect(user.identity_url).to eq identity_url+ end- before do- parameters[:password] = password+ it_behaves_like 'represents the created user'end- it 'returns the represented user' do- send_request+ context 'with password' do+ let(:password) { 'admin!admin!' }- expect(last_response.body).not_to have_json_path("_embedded/errors")- expect(last_response.body).to have_json_type(Object).at_path('_links')- expect(last_response.body)- .to be_json_eql('User'.to_json)- .at_path('_type')- end+ before do+ parameters[:password] = password+ end- it_behaves_like 'represents the created user'+ it 'returns the represented user' do+ send_request- context 'empty password' do- let(:password) { '' }+ expect(last_response.body).not_to have_json_path("_embedded/errors")+ expect(last_response.body).to have_json_type(Object).at_path('_links')+ expect(last_response.body)+ .to be_json_eql('User'.to_json)+ .at_path('_type')+ end- it 'marks the password missing and too short' do- send_request+ it_behaves_like 'represents the created user'++ context 'empty password' do+ let(:password) { '' }- expect(errors.count).to eq(2)- expect(errors.collect { |el| el['_embedded']['details']['attribute'] })- .to match_array %w(password password)+ it 'marks the password missing and too short' do+ send_request++ errors = parse_json(last_response.body)['_embedded']['errors']+ expect(errors.count).to eq(2)+ expect(errors.collect { |el| el['_embedded']['details']['attribute'] })+ .to match_array %w(password password)+ endendendendend- describe 'invited status' do- let(:status) { 'invited' }- let(:invitation_request) {- {- status: status,- email: '[email protected]'- }- }+ describe 'user with global user CRU permission' do+ let!(:global_add_user_role) { FactoryBot.create :global_role, name: 'Add user', permissions: %i[add_user] }+ let(:current_user) do+ user = FactoryBot.create(:user)- describe 'invitation successful' do- before do- expect(OpenProject::Notifications).to receive(:send) do |event, _|- expect(event).to eq 'user_invited'- end- end+ FactoryBot.create(:global_member,+ principal: user,+ roles: [global_add_user_role])- context 'only mail set' do- let(:parameters) { invitation_request }+ user+ end- it_behaves_like 'represents the created user',- firstName: 'foo',- lastName: '@example.org'+ it_behaves_like 'create user request flow'- it 'sets the other attributes' do- send_request+ describe 'active status' do+ context 'with identity_url' do+ let(:identity_url) { 'google:3289272389298' }- user = User.find_by!(login: '[email protected]')- expect(user.firstname).to eq('foo')- expect(user.lastname).to eq('@example.org')- expect(user.mail).to eq('[email protected]')+ before do+ parameters[:identityUrl] = identity_urlend- end- context 'mail and name set' do- let(:parameters) { invitation_request.merge(firstName: 'First', lastName: 'Last') }-- it_behaves_like 'represents the created user'+ it_behaves_like 'property is not writable', 'identityUrl'end- end- context 'missing email' do- let(:parameters) { { status: status } }+ context 'with password' do+ let(:password) { 'admin!admin!' }- it 'marks the mail as missing' do- send_request+ before do+ parameters[:password] = password+ end- expect(last_response.body)- .to be_json_eql('urn:openproject-org:api:v3:errors:PropertyConstraintViolation'.to_json)- .at_path('errorIdentifier')- expect(last_response.body)- .to be_json_eql('email'.to_json)- .at_path('_embedded/details/attribute')+ it_behaves_like 'property is not writable', 'password'endend- end-- describe 'invalid status' do- let(:parameters) { { status: 'blablu' } }-- it 'returns an erroneous response' do- send_request- expect(last_response.status).to eq(422)+ context 'with auth_source' do+ let(:auth_source_id) { 'some_ldap' }+ let(:auth_source) { FactoryBot.create :auth_source, name: auth_source_id }- expect(errors).not_to be_empty- expect(last_response.body)- .to be_json_eql('urn:openproject-org:api:v3:errors:MultipleErrors'.to_json)- .at_path('errorIdentifier')+ before do+ parameters[:_links] = {+ auth_source: {+ href: "/api/v3/auth_sources/#{auth_source.id}"+ }+ }+ end- expect(errors.collect { |el| el['message'] })- .to include 'Status is not a valid status for new users.'+ it_behaves_like 'property is not writable', 'authSource'endenddescribe 'unauthorized user' do- let(:user) { FactoryBot.build(:user) }+ let(:current_user) { FactoryBot.build(:user) }let(:parameters) { { status: 'invited', email: '[email protected]' } }it 'returns an erroneous response' dodiff --git a/spec/requests/api/v3/user/update_user_resource_spec.rb b/spec/requests/api/v3/user/update_user_resource_spec.rbindex 326b46b1e79..195c840d2c8 100644--- a/spec/requests/api/v3/user/update_user_resource_spec.rb+++ b/spec/requests/api/v3/user/update_user_resource_spec.rb@@ -33,7 +33,6 @@ describe ::API::V3::Users::UsersAPI, type: :request doinclude API::V3::Utilities::PathHelperlet(:path) { api_v3_paths.user(user.id) }- let(:current_user) { FactoryBot.build(:admin) }let(:user) { FactoryBot.create(:user) }let(:parameters) { {} }@@ -64,58 +63,92 @@ describe ::API::V3::Users::UsersAPI, type: :request doendend- describe 'empty request body' do- it_behaves_like 'successful update'- end+ shared_examples 'update flow' do+ describe 'empty request body' do+ it_behaves_like 'successful update'+ end- describe 'attribute change' do- let(:parameters) { { email: '[email protected]', language: 'de' } }- it_behaves_like 'successful update', mail: '[email protected]', language: 'de'- end+ describe 'attribute change' do+ let(:parameters) { { email: '[email protected]', language: 'de' } }+ it_behaves_like 'successful update', mail: '[email protected]', language: 'de'+ end- describe 'password update' do- let(:password) { 'my!new!password123' }- let(:parameters) { { password: password } }+ describe 'attribute collision' do+ let(:parameters) { { email: '[email protected]' } }+ let(:collision) { FactoryBot.create(:user, mail: '[email protected]') }+ before do+ collision+ end- it 'updates the users password correctly' do- send_request- expect(last_response.status).to eq(200)+ it 'returns an erroneous response' do+ send_request- updated_user = User.find(user.id)- matches = updated_user.check_password?(password)- expect(matches).to eq(true)+ expect(last_response.status).to eq(422)++ expect(last_response.body)+ .to be_json_eql('email'.to_json)+ .at_path('_embedded/details/attribute')++ expect(last_response.body)+ .to be_json_eql('urn:openproject-org:api:v3:errors:PropertyConstraintViolation'.to_json)+ .at_path('errorIdentifier')+ endendend- describe 'attribute collision' do- let(:parameters) { { email: '[email protected]' } }- let(:collision) { FactoryBot.create(:user, mail: '[email protected]') }- before do- collision- end+ describe 'admin user' do+ let(:current_user) { FactoryBot.build(:admin) }- it 'returns an erroneous response' do- send_request+ it_behaves_like 'update flow'- expect(last_response.status).to eq(422)+ describe 'password update' do+ let(:password) { 'my!new!password123' }+ let(:parameters) { { password: password } }- expect(last_response.body)- .to be_json_eql('email'.to_json)- .at_path('_embedded/details/attribute')+ it 'updates the users password correctly' do+ send_request+ expect(last_response.status).to eq(200)- expect(last_response.body)- .to be_json_eql('urn:openproject-org:api:v3:errors:PropertyConstraintViolation'.to_json)- .at_path('errorIdentifier')+ updated_user = User.find(user.id)+ matches = updated_user.check_password?(password)+ expect(matches).to eq(true)+ end+ end++ describe 'unknown user' do+ let(:parameters) { { email: '[email protected]' } }+ let(:path) { api_v3_paths.user(666) }++ it 'responds with 404' do+ send_request+ expect(last_response.status).to eql(404)+ endend+end- describe 'unknown user' do- let(:parameters) { { email: '[email protected]' } }- let(:path) { api_v3_paths.user(666) }+ describe 'user with global add_user permission' do+ using_shared_fixtures :global_add_user+ let(:current_user) { global_add_user }- it 'responds with 404' do- send_request- expect(last_response.status).to eql(404)+ it_behaves_like 'update flow'++ describe 'password update' do+ let(:password) { 'my!new!password123' }+ let(:parameters) { { password: password } }++ it 'rejects the users password update' do+ send_request+ expect(last_response.status).to eq(422)++ expect(last_response.body)+ .to be_json_eql('password'.to_json)+ .at_path('_embedded/details/attribute')++ expect(last_response.body)+ .to be_json_eql('urn:openproject-org:api:v3:errors:PropertyIsReadOnly'.to_json)+ .at_path('errorIdentifier')+ endendenddiff --git a/spec/requests/api/v3/user/user_resource_spec.rb b/spec/requests/api/v3/user/user_resource_spec.rbindex 0a83c98d0d5..932c0f77bc7 100644--- a/spec/requests/api/v3/user/user_resource_spec.rb+++ b/spec/requests/api/v3/user/user_resource_spec.rb@@ -40,6 +40,16 @@ describe 'API v3 User resource',let(:user) { FactoryBot.create(:user) }let(:admin) { FactoryBot.create(:admin) }let(:locked_admin) { FactoryBot.create :admin, status: Principal::STATUSES[:locked] }+ let(:user_with_global_add_user) do+ user = FactoryBot.create(:user, firstname: 'Global', lastname: 'User')+ global_role = FactoryBot.create :global_role, name: 'Add user', permissions: %i[add_user]++ FactoryBot.create(:global_member,+ principal: user,+ roles: [global_role])++ user+ endsubject(:response) { last_response }@@ -55,9 +65,7 @@ describe 'API v3 User resource',get get_pathend- context 'admin user' do- let(:current_user) { admin }-+ shared_examples 'flow with permitted user' doit 'should respond with 200' doexpect(subject.status).to eq(200)end@@ -155,6 +163,18 @@ describe 'API v3 User resource',endend+ context 'admin' do+ let(:current_user) { admin }++ it_behaves_like 'flow with permitted user'+ end++ context 'user with global add_user permission' do+ let(:current_user) { user_with_global_add_user }++ it_behaves_like 'flow with permitted user'+ end+context 'locked admin' dolet(:current_user) { locked_admin }@@ -292,6 +312,12 @@ describe 'API v3 User resource',it_behaves_like 'deletion is not allowed'end+ context 'as user with add_user permission' do+ let(:current_user) { user_with_global_add_user }++ it_behaves_like 'deletion is not allowed'+ end+context 'as self' dolet(:current_user) { user }diff --git a/spec/services/authorization/user_allowed_service_spec.rb b/spec/services/authorization/user_allowed_service_spec.rbindex de67b957136..3c4c9485c26 100644--- a/spec/services/authorization/user_allowed_service_spec.rb+++ b/spec/services/authorization/user_allowed_service_spec.rb@@ -100,6 +100,17 @@ describe Authorization::UserAllowedService doinstance.call(action, context)endend++ context 'but the user not being active' do+ before do+ user.lock+ end++ it 'returns false', :aggregate_failures do+ expect(instance.call(action, nil, global: true)).to be_success+ expect(instance.call(action, nil, global: true).result).not_to be_truthy+ end+ endendcontext 'with the user having a nongranting role' do@@ -287,11 +298,19 @@ describe Authorization::UserAllowedService do.and_return(true)end- it 'is true' do- expect(instance.call(action, nil, global: true).result).to be_truthy+ context 'but the user not being active' do+ before do+ user.lock+ end++ it 'is unsuccessful', :aggregate_failures do+ expect(instance.call(action, nil, global: true)).to be_success+ expect(instance.call(action, nil, global: true).result).not_to be_truthy+ endend- it 'is successful' do+ it 'is successful', :aggregate_failures do+ expect(instance.call(action, nil, global: true).result).to be_truthyexpect(instance.call(action, nil, global: true)).to be_successendenddiff --git a/spec/services/base_services/behaves_like_update_service.rb b/spec/services/base_services/behaves_like_update_service.rbnew file mode 100644index 00000000000..215d873762f--- /dev/null+++ b/spec/services/base_services/behaves_like_update_service.rb@@ -0,0 +1,135 @@+#-- encoding: UTF-8++#-- copyright+# OpenProject is an open source project management software.+# Copyright (C) 2012-2021 the OpenProject GmbH+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License version 3.+#+# OpenProject is a fork of ChiliProject, which is a fork of Redmine. The copyright follows:+# Copyright (C) 2006-2013 Jean-Philippe Lang+# Copyright (C) 2010-2013 the ChiliProject Team+#+# This program is free software; you can redistribute it and/or+# modify it under the terms of the GNU General Public License+# as published by the Free Software Foundation; either version 2+# of the License, or (at your option) any later version.+#+# This program is distributed in the hope that it will be useful,+# but WITHOUT ANY WARRANTY; without even the implied warranty of+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+# GNU General Public License for more details.+#+# You should have received a copy of the GNU General Public License+# along with this program; if not, write to the Free Software+# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.+#+# See docs/COPYRIGHT.rdoc for more details.+#++++require 'spec_helper'++shared_examples 'BaseServices update service' do+ let(:service_class) { described_class }+ let(:namespace) { service_class.to_s.deconstantize }+ let(:model_class) { namespace.singularize.constantize }+ let(:contract_class) { "#{namespace}::UpdateContract".constantize }+ let(:factory) { namespace.singularize.underscore }++ let(:set_attributes_class) { "#{namespace}::SetAttributesService".constantize }++ let(:user) { FactoryBot.build_stubbed(:user) }+ let(:contract_class) do+ double('contract_class', '<=': true)+ end+ let(:instance) do+ described_class.new(user: user,+ model: model_instance,+ contract_class: contract_class)+ end+ let(:call_attributes) { { name: 'Some name', identifier: 'Some identifier' } }+ let(:set_attributes_success) do+ true+ end+ let(:set_attributes_errors) do+ double('set_attributes_errors')+ end+ let(:set_attributes_result) do+ ServiceResult.new result: model_instance,+ success: set_attributes_success,+ errors: set_attributes_errors+ end+ let!(:model_instance) { FactoryBot.build_stubbed(factory) }+ let!(:set_attributes_service) do+ service = double('set_attributes_service_instance')++ allow(set_attributes_class)+ .to receive(:new)+ .with(user: user,+ model: model_instance,+ contract_class: contract_class,+ contract_options: {})+ .and_return(service)++ allow(service)+ .to receive(:call)+ .and_return(set_attributes_result)+ end++ before do+ allow(model_instance).to receive(:save).and_return(true)+ end++ subject { instance.call(call_attributes) }++ describe '#user' do+ it 'exposes a user which is available as a getter' do+ expect(instance.user).to eql user+ end+ end++ describe '#contract' do+ it 'uses the UpdateContract contract' do+ expect(instance.contract_class).to eql contract_class+ end+ end++ describe "#call" do+ context 'when the model instance is valid' do+ it 'is a successful call', :aggregate_failures do+ expect(subject.success?).to be_truthy+ expect(subject).to eql set_attributes_result+ expect(subject.result).to eql model_instance+ end+ end++ context 'if the SetAttributeService is unsuccessful' do+ let(:set_attributes_success) { false }++ it 'is unsuccessful', :aggregate_failures do+ expect(model_instance).not_to receive(:save)++ expect(subject.success?).to be_falsey+ expect(subject).to eql set_attributes_result++ expect(model_instance).to_not receive(:save)++ expect(subject.errors).to eql set_attributes_errors+ end+ end++ context 'when the model instance is invalid' do+ before do+ expect(model_instance)+ .to(receive(:save))+ .and_return(false)+ end++ it 'is unsuccessful and returns the errors', :aggregate_failures do+ expect(subject.success?).to be_falsey+ expect(subject.errors).to eql model_instance.errors+ end+ end+ end+enddiff --git a/spec/services/custom_fields/update_service_spec.rb b/spec/services/custom_fields/update_service_spec.rbindex 13ee0635589..8be4c11f214 100644--- a/spec/services/custom_fields/update_service_spec.rb+++ b/spec/services/custom_fields/update_service_spec.rb@@ -29,124 +29,8 @@#++require 'spec_helper'+require 'services/base_services/behaves_like_update_service'describe CustomFields::UpdateService, type: :model do- let(:user) { FactoryBot.build_stubbed(:user) }- let(:contract_class) do- double('contract_class', "<=": true)- end- let(:cf_valid) { true }- let(:instance) do- described_class.new(user: user,- model: cf,- contract_class: contract_class,- contract_options: {})- end- let(:call_attributes) { {} }- let(:set_attributes_success) do- true- end- let(:set_attributes_errors) do- double('set_attributes_errors')- end- let(:set_attributes_result) do- ServiceResult.new result: cf,- success: set_attributes_success,- errors: set_attributes_errors- end- let!(:cf) do- cf = FactoryBot.build_stubbed(:project_custom_field)-- allow(cf)- .to receive(:save)- .and_return(cf_valid)-- cf- end- let!(:set_attributes_service) do- service = double('set_attributes_service_instance')-- allow(CustomFields::SetAttributesService)- .to receive(:new)- .with(user: user,- model: cf,- contract_class: contract_class,- contract_options: {})- .and_return(service)-- allow(service)- .to receive(:call)- .and_return(set_attributes_result)-- service- end-- describe 'call' do- shared_examples_for 'service call' do- subject { instance.call(call_attributes) }-- it 'is successful' do- expect(subject.success?).to be_truthy- end-- it 'returns the result of the SetAttributesService' do- expect(subject)- .to eql set_attributes_result- end-- it 'persists the custom field' do- expect(cf)- .to receive(:save)- .and_return(cf_valid)-- subject- end-- context 'when the SetAttributeService is unsuccessful' do- let(:set_attributes_success) { false }-- it 'is unsuccessful' do- expect(subject.success?).to be_falsey- end-- it 'returns the result of the SetAttributesService' do- expect(subject)- .to eql set_attributes_result- end-- it 'does not persist the changes' do- expect(cf)- .to_not receive(:save)-- subject- end-- it "exposes the contract's errors" do- subject-- expect(subject.errors).to eql set_attributes_errors- end- end-- context 'when the custom field is invalid' do- let(:cf_valid) { false }-- it 'is unsuccessful' do- expect(subject.success?).to be_falsey- end-- it "exposes the custom field's errors" do- subject-- expect(subject.errors).to eql cf.errors- end- end- end-- context 'with parameters' do- let(:call_attributes) { { sticky: true } }-- it_behaves_like 'service call'- end- end+ it_behaves_like 'BaseServices update service'enddiff --git a/spec/services/messages/update_service_spec.rb b/spec/services/messages/update_service_spec.rbindex c7aeca06e13..a2f755e8454 100644--- a/spec/services/messages/update_service_spec.rb+++ b/spec/services/messages/update_service_spec.rb@@ -29,124 +29,8 @@#++require 'spec_helper'+require 'services/base_services/behaves_like_update_service'describe Messages::UpdateService, type: :model do- let(:user) { FactoryBot.build_stubbed(:user) }- let(:contract_class) do- double('contract_class', "<=": true)- end- let(:message_valid) { true }- let(:instance) do- described_class.new(user: user,- model: message,- contract_class: contract_class,- contract_options: {})- end- let(:call_attributes) { {} }- let(:set_attributes_success) do- true- end- let(:set_attributes_errors) do- double('set_attributes_errors')- end- let(:set_attributes_result) do- ServiceResult.new result: message,- success: set_attributes_success,- errors: set_attributes_errors- end- let!(:message) do- message = FactoryBot.build_stubbed(:message)-- allow(message)- .to receive(:save)- .and_return(message_valid)-- message- end- let!(:set_attributes_service) do- service = double('set_attributes_service_instance')-- allow(Messages::SetAttributesService)- .to receive(:new)- .with(user: user,- model: message,- contract_class: contract_class,- contract_options: {})- .and_return(service)-- allow(service)- .to receive(:call)- .and_return(set_attributes_result)-- service- end-- describe 'call' do- shared_examples_for 'service call' do- subject { instance.call(call_attributes) }-- it 'is successful' do- expect(subject.success?).to be_truthy- end-- it 'returns the result of the SetAttributesService' do- expect(subject)- .to eql set_attributes_result- end-- it 'persists the message' do- expect(message)- .to receive(:save)- .and_return(message_valid)-- subject- end-- context 'when the SetAttributeService is unsuccessful' do- let(:set_attributes_success) { false }-- it 'is unsuccessful' do- expect(subject.success?).to be_falsey- end-- it 'returns the result of the SetAttributesService' do- expect(subject)- .to eql set_attributes_result- end-- it 'does not persist the changes' do- expect(message)- .to_not receive(:save)-- subject- end-- it "exposes the contract's errors" do- subject-- expect(subject.errors).to eql set_attributes_errors- end- end-- context 'when the message is invalid' do- let(:message_valid) { false }-- it 'is unsuccessful' do- expect(subject.success?).to be_falsey- end-- it "exposes the message's errors" do- subject-- expect(subject.errors).to eql message.errors- end- end- end-- context 'with parameters' do- let(:call_attributes) { { sticky: true } }-- it_behaves_like 'service call'- end- end+ it_behaves_like 'BaseServices update service'enddiff --git a/spec/services/projects/update_service_intergration_spec.rb b/spec/services/projects/update_service_integration_spec.rbsimilarity index 100%rename from spec/services/projects/update_service_intergration_spec.rbrename to spec/services/projects/update_service_integration_spec.rbdiff --git a/spec/services/projects/update_service_spec.rb b/spec/services/projects/update_service_spec.rbindex 05fb51bfa80..14342e24c31 100644--- a/spec/services/projects/update_service_spec.rb+++ b/spec/services/projects/update_service_spec.rb@@ -29,87 +29,21 @@#++require 'spec_helper'+require 'services/base_services/behaves_like_update_service'describe Projects::UpdateService, type: :model do- let(:user) { FactoryBot.build_stubbed(:user) }- let(:contract_class) do- double('contract_class', '<=': true)- end- let(:project_valid) { true }- let(:instance) do- described_class.new(user: user,- model: project,- contract_class: contract_class)- end- let(:call_attributes) { { name: 'Some name', identifier: 'Some identifier' } }- let(:set_attributes_success) do- true- end- let(:set_attributes_errors) do- double('set_attributes_errors')- end- let(:set_attributes_result) do- ServiceResult.new result: project,- success: set_attributes_success,- errors: set_attributes_errors- end- let!(:project) do- FactoryBot.build_stubbed(:project, status: project_status).tap do |p|- allow(p)- .to receive(:save)- .and_return(project_valid)-- project_status.clear_changes_information- end- end- let(:project_status) do- FactoryBot.build_stubbed(:project_status)- end- let!(:set_attributes_service) do- service = double('set_attributes_service_instance')-- allow(Projects::SetAttributesService)- .to receive(:new)- .with(user: user,- model: project,- contract_class: contract_class,- contract_options: {})- .and_return(service)-- allow(service)- .to receive(:call)- .and_return(set_attributes_result)- end-- describe 'call' do- subject { instance.call(call_attributes) }-- it 'is successful' do- expect(subject.success?).to be_truthy- end-- it 'returns the result of the SetAttributesService' do- expect(subject)- .to eql set_attributes_result- end-- it 'persists the project' do- expect(project)- .to receive(:save)- .and_return(project_valid)-- subject- end-- it 'returns the project' do- expect(subject.result)- .to eql project+ it_behaves_like 'BaseServices update service' do+ let!(:model_instance) do+ FactoryBot.build_stubbed(:project, status: project_status).tap do |p|+ project_status.clear_changes_information+ endend+ let(:project_status) { FactoryBot.build_stubbed(:project_status) }it 'sends an update notification' doexpect(OpenProject::Notifications)- .to receive(:send)- .with('project_updated', project: project)+ .to(receive(:send))+ .with('project_updated', project: model_instance)subjectend@@ -118,18 +52,18 @@ describe Projects::UpdateService, type: :model dolet(:call_attributes) { { identifier: 'Some identifier' } }before do- allow(project)- .to receive(:changes)+ allow(model_instance)+ .to(receive(:changes)).and_return('identifier' => %w(lorem ipsum))endit 'sends the notification' doexpect(OpenProject::Notifications)- .to receive(:send)- .with('project_updated', project: project)+ .to(receive(:send))+ .with('project_updated', project: model_instance)expect(OpenProject::Notifications)- .to receive(:send)- .with('project_renamed', project: project)+ .to(receive(:send))+ .with('project_renamed', project: model_instance)subjectend@@ -137,15 +71,15 @@ describe Projects::UpdateService, type: :model docontext 'if the parent is altered' dobefore do- allow(project)- .to receive(:changes)+ allow(model_instance)+ .to(receive(:changes)).and_return('parent_id' => [nil, 5])endit 'updates the versions associated with the work packages' doexpect(WorkPackage)- .to receive(:update_versions_from_hierarchy_change)- .with(project)+ .to(receive(:update_versions_from_hierarchy_change))+ .with(model_instance)subjectend@@ -154,56 +88,15 @@ describe Projects::UpdateService, type: :model docontext 'if the project status is altered' dobefore doallow(project_status)- .to receive(:changed?)+ .to(receive(:changed?)).and_return(true)endit 'persists the changes' do- expect(project_status)- .to receive(:save)+ expect(project_status).to receive(:save)subjectendend-- context 'if the SetAttributeService is unsuccessful' do- let(:set_attributes_success) { false }-- it 'is unsuccessful' do- expect(subject.success?).to be_falsey- end-- it 'returns the result of the SetAttributesService' do- expect(subject)- .to eql set_attributes_result- end-- it 'does not persist the changes' do- expect(project)- .to_not receive(:save)-- subject- end-- it "exposes the contract's errors" do- subject-- expect(subject.errors).to eql set_attributes_errors- end- end-- context 'if the project is invalid' do- let(:project_valid) { false }-- it 'is unsuccessful' do- expect(subject.success?).to be_falsey- end-- it "exposes the project's errors" do- subject-- expect(subject.errors).to eql project.errors- end- endendenddiff --git a/spec/services/users/create_user_service_spec.rb b/spec/services/users/create_user_service_spec.rbindex bbb02c25d8e..0cfc6ed8fe4 100644--- a/spec/services/users/create_user_service_spec.rb+++ b/spec/services/users/create_user_service_spec.rb@@ -28,10 +28,18 @@require 'spec_helper'-describe Users::CreateUserService do+describe Users::CreateService dolet(:current_user) { FactoryBot.build_stubbed(:user) }let(:new_user) { FactoryBot.build_stubbed(:user) }- let(:instance) { described_class.new(current_user: current_user) }+ let(:instance) { described_class.new(user: current_user) }+ let(:params) do+ {+ firstname: 'Bob',+ lastname: 'Bobby',+ login: 'bob1',+ mail: '[email protected]'+ }+ enddescribe '.contract' doit 'uses the CreateContract contract' do@@ -41,16 +49,17 @@ describe Users::CreateUserService dodescribe '.new' doit 'takes a user which is available as a getter' do- expect(instance.current_user).to eql current_user+ expect(instance.user).to eql current_userendenddescribe '#call' do- subject { instance.call(new_user) }+ subject { instance.call(params) }let(:validates) { true }let(:saves) { true }before do+ allow(instance).to receive(:instance).and_return(new_user)allow(new_user).to receive(:save).and_return(saves)allow_any_instance_of(Users::CreateContract).to receive(:validate).and_return(validates)enddiff --git a/spec/services/users/delete_service_spec.rb b/spec/services/users/delete_service_spec.rbindex 941f89b7feb..5020d65cb76 100644--- a/spec/services/users/delete_service_spec.rb+++ b/spec/services/users/delete_service_spec.rb@@ -32,7 +32,7 @@ describe ::Users::DeleteService, type: :model dolet(:input_user) { FactoryBot.build_stubbed(:user) }let(:project) { FactoryBot.build_stubbed(:project) }- let(:instance) { described_class.new(input_user, actor) }+ let(:instance) { described_class.new(model: input_user, user: actor) }subject { instance.call }@@ -40,7 +40,7 @@ describe ::Users::DeleteService, type: :model doit doexpect(input_user).to receive(:lock!)expect(DeleteUserJob).to receive(:perform_later).with(input_user)- expect(subject).to eq true+ expect(subject).to be_successendend@@ -48,7 +48,7 @@ describe ::Users::DeleteService, type: :model doit doexpect(input_user).not_to receive(:lock!)expect(DeleteUserJob).not_to receive(:perform_later)- expect(subject).to eq false+ expect(subject).not_to be_successendend@@ -77,7 +77,7 @@ describe ::Users::DeleteService, type: :model doactor.run_given doexpect(input_user).to receive(:lock!)expect(DeleteUserJob).to receive(:perform_later).with(input_user)- expect(subject).to eq true+ expect(subject).to be_successendendenddiff --git a/spec/services/users/update_user_service_spec.rb b/spec/services/users/update_service_spec.rbsimilarity index 58%rename from spec/services/users/update_user_service_spec.rbrename to spec/services/users/update_service_spec.rbindex be10aa2f025..e38cb148e38 100644--- a/spec/services/users/update_user_service_spec.rb+++ b/spec/services/users/update_service_spec.rb@@ -27,25 +27,19 @@# See docs/COPYRIGHT.rdoc for more details.require 'spec_helper'+require 'services/base_services/behaves_like_update_service'-describe Users::UpdateUserService do- let(:current_user) { FactoryBot.build_stubbed(:admin) }- let(:update_user) { FactoryBot.build_stubbed(:user) }- let(:instance) { described_class.new(user: update_user, current_user: current_user) }-- describe '.contract' do- it 'uses the UpdateContract contract' do- expect(instance.contract_class).to eql Users::UpdateContract- end- end-- describe '.new' do- it 'takes a user which is available as a getter' do- expect(instance.current_user).to eql current_user+describe Users::UpdateService do+ it_behaves_like 'BaseServices update service' do+ # The user service also tries to save the preferences+ before do+ allow(model_instance.pref).to receive(:save).and_return(true)endenddescribe 'updating attributes' do+ let(:instance) { described_class.new(model: update_user, user: current_user) }+ let(:current_user) { FactoryBot.build_stubbed(:admin) }let(:update_user) { FactoryBot.create(:user, mail: '[email protected]') }subject { instance.call(attributes: attributes) }@@ -79,55 +73,45 @@ describe Users::UpdateUserService doendendend- end- describe '#call' do- subject { instance.call() }- let(:validates) { true }- let(:saves) { true }+ describe 'updating prefs' do+ let(:attributes) { {} }- before do- allow(update_user).to receive(:save).and_return(saves)- allow_any_instance_of(Users::UpdateContract).to receive(:validate).and_return(validates)- end-- context 'if contract validates and the user saves' do- it 'is successful' do- expect(subject).to be_success+ before do+ allow(update_user).to receive(:save).and_return(user_save_result)end- it 'has no errors' do- expect(subject.errors).to be_empty- end+ context 'if the user was updated calls the prefs' do+ let(:user_save_result) { true }- it 'returns the user as a result' do- result = subject.result- expect(result).to be_a User- end- end+ before do+ expect(update_user.pref).to receive(:save).and_return(pref_save_result)+ end- context 'if contract does not validate' do- let(:validates) { false }+ context 'and the prefs can be saved' do+ let(:pref_save_result) { true }- it 'is unsuccessful' do- expect(subject).to_not be_success- end- end+ it 'returns a successful call' do+ expect(subject).to be_success+ end+ end- context 'if user does not save' do- let(:saves) { false }- let(:errors) { double('errors') }+ context 'and the prefs can not be saved' do+ let(:pref_save_result) { false }- it 'is unsuccessful' do- expect(subject).to_not be_success+ it 'returns an erroneous call' do+ expect(subject).not_to be_success+ end+ endend- it "returns the user's errors" do- allow(update_user)- .to receive(:errors)- .and_return errors+ context 'if the user was not saved' do+ let(:user_save_result) { false }- expect(subject.errors).to eql errors+ it 'does not call #prefs.save' do+ expect(update_user.pref).not_to receive(:save)+ expect(subject).not_to be_success+ endendendenddiff --git a/spec/support/shared_fixtures/users/global_add_user.rb b/spec/support/shared_fixtures/users/global_add_user.rbnew file mode 100644index 00000000000..d3807384ab8--- /dev/null+++ b/spec/support/shared_fixtures/users/global_add_user.rb@@ -0,0 +1,12 @@+require_relative '../shared_fixture'++::SharedFixture.register! :global_add_user do+ global_add_user_role = FactoryBot.create :global_role, name: 'Global add user role', permissions: %i[add_user]+ FactoryBot.create(:user).tap do |user|++ FactoryBot.create(:global_member,+ principal: user,+ roles: [global_add_user_role])++ end+end