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
[36467] Add API users form and schema endpoints (#9090)
Oliver Günther065dfbddc466
diff --git a/app/contracts/users/base_contract.rb b/app/contracts/users/base_contract.rbindex bbabb54df7e..75cdd2801dd 100644--- a/app/contracts/users/base_contract.rb+++ b/app/contracts/users/base_contract.rb@@ -30,11 +30,12 @@module Usersclass BaseContract < ::ModelContract+ include AssignableCustomFieldValues+attribute :login,writeable: ->(*) { user.allowed_to_globally?(:manage_user) && model.id != user.id }attribute :firstnameattribute :lastname- attribute :nameattribute :mailattribute :admin,writeable: ->(*) { user.admin? && model.id != user.id }@@ -53,18 +54,33 @@ module UsersUserend- validate :password_writable+ validate :validate_password_writablevalidate :existing_auth_source+ delegate :available_custom_fields, to: :model++ def reduce_writable_attributes(attributes)+ super.tap do |writable|+ writable << 'password' if password_writable?+ end+ end+private+ ##+ # Password is not a regular attribute so it bypasses+ # attribute writable checks+ def password_writable?+ user.admin? || user.id == model.id+ end+### 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+ def validate_password_writable# Only admins or the user themselves can set the password- return if user.admin? || user.id == model.id+ return if password_writable?errors.add :password, :error_readonly if model.password.present?enddiff --git a/config/constants/ar_to_api_conversions.rb b/config/constants/ar_to_api_conversions.rbindex 63c89257ff2..ee8f0c265ce 100644--- a/config/constants/ar_to_api_conversions.rb+++ b/config/constants/ar_to_api_conversions.rb@@ -44,7 +44,9 @@ module Constantscolumn_names: 'columns',is_public: 'public',sort_criteria: 'sortBy',- message: 'post'+ message: 'post',+ firstname: 'firstName',+ lastname: 'lastName',}.freeze# Conversions that are unidirectional (from the API to AR)diff --git a/docs/api/apiv3/endpoints/users.apib b/docs/api/apiv3/endpoints/users.apibindex 32c31ff1fba..a6ba701ed87 100644--- a/docs/api/apiv3/endpoints/users.apib+++ b/docs/api/apiv3/endpoints/users.apib@@ -16,7 +16,12 @@| auth_source | Link to the user's auth source (endpoint not yet implemented) | AuthSource | | READ / WRITE | **Permission**: Administrator || 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 |+Depending on custom fields defined for users, additional links might exist.+++## Local Properties+| Property | Description | Type | Constraints | Supported operations | Condition || :----------: | --------------------------------------------------------- | -------- | ---------------------------------------------------- | -------------------- | ----------------------------------------------------------- || id | User's id | Integer | x > 0 | READ | |@@ -34,6 +39,10 @@| createdAt | Time of creation | DateTime | | READ | || updatedAt | Time of the most recent change to the user | DateTime | | READ | |+Depending on custom fields defined for users, additional properties might exist.+++The `status` of a user can be one of:* `active` - the user can log in with the account right away@@ -56,7 +65,7 @@ users except for admins or the user themselves.Please note that custom fields are not yet supported by the api although the backend supports them.-## User [/api/v3/users/{id}]+## View user [/api/v3/users/{id}]+ Model+ Body@@ -101,11 +110,12 @@ Please note that custom fields are not yet supported by the api although the bac## View user [GET]+ Parameters++ id (required, integer or `me`, `1`) ... User id. Use `me` to reference current user, if any.-++ Response 200 (application/hal+json)- [User][]+ [View user][]+ Response 404 (application/hal+json)@@ -121,14 +131,109 @@ Please note that custom fields are not yet supported by the api although the bac"message": "The specified user does not exist or you do not have permission to view them."}+## Create User [/api/v3/users]++## Create User [POST]++Creates a new user. Only administrators and users with manage_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`:++1) "active" - In this case a password has to be provided in addition to the other attributes.+2) "invited" - In this case nothing but the email address is required. The rest is optional. An invitation will be sent to the user.+++ Request Create User (application/json)++ + Body++ {+ "login": "h.wurst",+ "email": "[email protected]",+ "firstName": "Hans",+ "lastName": "Wurst",+ "admin": false,+ "language": "de",+ "status": "active",+ "password": "hunter5"+ }+++ Request Invite User (application/json)++ + Body++ {+ "email": "[email protected]",+ "firstName": "Hanz",+ "status": "invited"+ }+++ Response 201++ [View user][]+++ Response 400 (application/hal+json)++ Occurs when the client did not send a valid JSON object in the request body.++ + Body++ {+ "_type": "Error",+ "errorIdentifier": "urn:openproject-org:api:v3:errors:InvalidRequestBody",+ "message": "The request body was not a single JSON object."+ }+++ Response 403 (application/hal+json)++ Returned if the client does not have sufficient permissions.++ **Required permission:** Administrator++ + Body++ {+ "_type": "Error",+ "errorIdentifier": "urn:openproject-org:api:v3:errors:MissingPermission",+ "message": "You are not allowed to create new users."+ }+++ Response 422 (application/hal+json)++ Returned if:++ * a constraint for a property was violated (`PropertyConstraintViolation`)++ + Body++ {+ "_type": "Error",+ "errorIdentifier": "urn:openproject-org:api:v3:errors:PropertyConstraintViolation",+ "message": "The email address is already taken.",+ "_embedded": {+ "details": {+ "attribute": "email"+ }+ }+ }++##++++++## Update User [/api/v3/users/{id}]+## Update user [PATCH]Updates the user's writable attributes.When calling this endpoint the client provides a single object, containing at least the properties and links that are required, in the body.+ Parameters++ id (required, integer, `1`) ... User id-++ Request Update User (application/json)+ Body@@ -144,7 +249,7 @@ When calling this endpoint the client provides a single object, containing at le+ Response 200- [User][]+ [View user][]+ Response 400 (application/hal+json)@@ -207,13 +312,16 @@ When calling this endpoint the client provides a single object, containing at le}}+## Delete User [/api/v3/users/{id}]+## Delete user [DELETE]Permanently deletes the specified user account.+ Parameters++ id (required, integer, `1`) ... User id-++ Response 202Returned if the account was deleted successfully.@@ -249,17 +357,17 @@ Permanently deletes the specified user account."message": "The specified user does not exist."}+## Lock user [/api/v3/users/{id}/lock]-## User Account Locking [/api/v3/users/{id}/lock]--## Set Lock [POST]+## Lock user [POST]+ Parameters++ id (required, integer, `1`) ... User id-++ Response 200 (application/hal+json)- [User][]+ [View user][]+ Response 400 (application/hal+json)@@ -301,14 +409,17 @@ Permanently deletes the specified user account."message": "The specified user does not exist."}-## Remove Lock [DELETE]+## Unlock user [/api/v3/users/{id}/lock]++## Unlock user [DELETE]+ Parameters++ id (required, integer, `1`) ... User id-++ Response 200 (application/hal+json)- [User][]+ [View user][]+ Response 400 (application/hal+json)@@ -457,86 +568,682 @@ Lists users. Only administrators or users with manage_users global permission ha"message": "You are not allowed to list users."}-## Create User [POST]+## View user schema [/api/v3/users/schemas]-Creates a new user. Only administrators and users with manage_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.++ Model+ + Body-Valid values for `status`:+ {+ "_type": "Schema",+ "_dependencies": [],+ "id": {+ "type": "Integer",+ "name": "ID",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "login": {+ "type": "String",+ "name": "Username",+ "required": true,+ "hasDefault": false,+ "writable": true,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "admin": {+ "type": "Boolean",+ "name": "Administrator",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "mail": {+ "type": "String",+ "name": "Email",+ "required": true,+ "hasDefault": false,+ "writable": true,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "firstName": {+ "type": "String",+ "name": "First name",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "lastName": {+ "type": "String",+ "name": "Last name",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "avatar": {+ "type": "String",+ "name": "Avatar",+ "required": false,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "status": {+ "type": "String",+ "name": "Status",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "identityUrl": {+ "type": "String",+ "name": "Identity url",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "language": {+ "type": "String",+ "name": "Language",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "password": {+ "type": "Password",+ "name": "Password",+ "required": false,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "createdAt": {+ "type": "DateTime",+ "name": "Created on",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "updatedAt": {+ "type": "DateTime",+ "name": "Updated on",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "customField1": {+ "type": "String",+ "name": "User String CF",+ "required": false,+ "hasDefault": false,+ "writable": true+ },+ "customField2": {+ "type": "CustomOption",+ "name": "User List cf",+ "required": false,+ "hasDefault": false,+ "writable": true+ },+ "_links": {+ "self": {+ "href": "/api/v3/users/schema"+ }+ }+ }-1) "active" - In this case a password has to be provided in addition to the other attributes.-2) "invited" - In this case nothing but the email address is required. The rest is optional. An invitation will be sent to the user.+## View user schema [GET]-+ Request Create User (application/json)+The schema response use two exemplary custom fields that extend the schema response. Depending on your instance and custom field configuration, the response will look somewhat different.- + Body++ Response 200 (application/hal+json)- {- "login": "h.wurst",- "email": "[email protected]",- "firstName": "Hans",- "lastName": "Wurst",- "admin": false,- "language": "de",- "status": "active",- "password": "hunter5"- }+ [View user schema][]-+ Request Invite User (application/json)- + Body+## User create form [/api/v3/users/{id}/form]- {- "email": "[email protected]",- "firstName": "Hanz",- "status": "invited"+This endpoint returns a form allowing a guided creation of new users.++For more details and all possible responses see the general specification of [Forms](/api/forms).++## Users create form [POST]+++ Request Create user form++ + Body++ {+ "mail": "[email protected]",+ "status": "invited",+ "customField1": "Custom field text value",+ "_links" {+ "customField2" : {+ "href": "/api/v3/custom_options/123"+ }}+ }-+ Response 201++ Response 200 (application/hal+json)- [User][]+ + Body++ {+ "_type": "Form",+ "_embedded": {+ "payload": {+ "firstName": "bar",+ "lastname": " @example.com",+ "_links": {}+ },+ "schema": {+ "_type": "Schema",+ "_dependencies": [],+ "id": {+ "type": "Integer",+ "name": "ID",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "login": {+ "type": "String",+ "name": "Username",+ "required": true,+ "hasDefault": false,+ "writable": true,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "admin": {+ "type": "Boolean",+ "name": "Administrator",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "mail": {+ "type": "String",+ "name": "Email",+ "required": true,+ "hasDefault": false,+ "writable": true,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "firstName": {+ "type": "String",+ "name": "First name",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "lastName": {+ "type": "String",+ "name": "Last name",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "avatar": {+ "type": "String",+ "name": "Avatar",+ "required": false,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "status": {+ "type": "String",+ "name": "Status",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "identityUrl": {+ "type": "String",+ "name": "Identity url",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "language": {+ "type": "String",+ "name": "Language",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "password": {+ "type": "Password",+ "name": "Password",+ "required": false,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "createdAt": {+ "type": "DateTime",+ "name": "Created on",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "updatedAt": {+ "type": "DateTime",+ "name": "Updated on",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "customField1": {+ "type": "String",+ "name": "User String CF",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "visibility": "default"+ },+ "customField2": {+ "type": "CustomOption",+ "name": "User List cf",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "visibility": "default",+ "_embedded": {+ "allowedValues": [{+ "_type": "CustomOption",+ "id": 123,+ "value": "abc",+ "_links": {+ "self": {+ "href": "/api/v3/custom_options/123",+ "title": "abc"+ }+ }+ },+ {+ "_type": "CustomOption",+ "id": 124,+ "value": "foo",+ "_links": {+ "self": {+ "href": "/api/v3/custom_options/124",+ "title": "foo"+ }+ }+ }+ ]+ },+ "_links": {+ "allowedValues": [{+ "href": "/api/v3/custom_options/123",+ "title": "abc"+ },+ {+ "href": "/api/v3/custom_options/124",+ "title": "foo"+ }+ ]+ }+ },+ "_links": {}+ },+ "validationErrors": {}+ },+ "_links": {+ "self": {+ "href": "/api/v3/users/form",+ "method": "post"+ },+ "validate": {+ "href": "/api/v3/users/form",+ "method": "post"+ },+ "commit": {+ "href": "/api/v3/users",+ "method": "post"+ }+ }+ }+ Response 400 (application/hal+json)- Occurs when the client did not send a valid JSON object in the request body.+ Occurs when the client did not send a valid JSON object in the request body.- + Body+ + Body- {- "_type": "Error",- "errorIdentifier": "urn:openproject-org:api:v3:errors:InvalidRequestBody",- "message": "The request body was not a single JSON object."- }+ {+ "_type": "Error",+ "errorIdentifier": "urn:openproject-org:api:v3:errors:InvalidRequestBody",+ "message": "The request body was not a single JSON object."+ }+ Response 403 (application/hal+json)- Returned if the client does not have sufficient permissions.+ Returned if the client does not have sufficient permissions.- **Required permission:** Administrator+ **Required permission:** manage_user global permission- + Body+ + Body- {- "_type": "Error",- "errorIdentifier": "urn:openproject-org:api:v3:errors:MissingPermission",- "message": "You are not allowed to create new users."- }+ {+ "_type": "Error",+ "errorIdentifier": "urn:openproject-org:api:v3:errors:MissingPermission",+ "message": "You are not authorized to access this resource."+ }-+ Response 422 (application/hal+json)- Returned if:- * a constraint for a property was violated (`PropertyConstraintViolation`)- + Body- {- "_type": "Error",- "errorIdentifier": "urn:openproject-org:api:v3:errors:PropertyConstraintViolation",- "message": "The email address is already taken.",+## User update form [/api/v3/users/{id}/form]++This endpoint returns a form allowing a guided modification of existing users.+The returned payload part of the form will be contain a merge between the already existing properties' values (as long as they are writeable) and the provided values with the later having precedence.++For more details and all possible responses see the general specification of [Forms](/api/forms).++## User update form [POST]+++ Parameters++ + id (required, integer, `1`) ... User id+++ Request Update user form++ + Body++ {+ "firstName": "Matthew"+ "customField1": "An exemplary text custom field value",+ "_links" {+ "customField2" : {+ "href": "/api/v3/custom_options/123"+ }+ }+ }+++ Response 200 (application/hal+json)++ + Body++ {+ "_type": "Form",+ "_embedded": {+ "payload": {+ "firstName": "Matthew",+ "lastName": "Mercer",+ "login": "[email protected]",+ "admin": false,+ "email": "[email protected]",+ "identityUrl": null,+ "language": "en",+ "customField1": "An exemplary text custom field value",+ "_links" {+ "customField2" : {+ "href": "/api/v3/custom_options/123"+ }+ }+ },+ "schema": {+ "_type": "Schema",+ "_dependencies": [],+ "id": {+ "type": "Integer",+ "name": "ID",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "login": {+ "type": "String",+ "name": "Username",+ "required": true,+ "hasDefault": false,+ "writable": true,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "admin": {+ "type": "Boolean",+ "name": "Administrator",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "mail": {+ "type": "String",+ "name": "Email",+ "required": true,+ "hasDefault": false,+ "writable": true,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "firstName": {+ "type": "String",+ "name": "First name",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "lastName": {+ "type": "String",+ "name": "Last name",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "minLength": 1,+ "maxLength": 255,+ "options": {}+ },+ "avatar": {+ "type": "String",+ "name": "Avatar",+ "required": false,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "status": {+ "type": "String",+ "name": "Status",+ "required": false,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "identityUrl": {+ "type": "String",+ "name": "Identity url",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "language": {+ "type": "String",+ "name": "Language",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "options": {}+ },+ "password": {+ "type": "Password",+ "name": "Password",+ "required": false,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "createdAt": {+ "type": "DateTime",+ "name": "Created on",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "updatedAt": {+ "type": "DateTime",+ "name": "Updated on",+ "required": true,+ "hasDefault": false,+ "writable": false,+ "options": {}+ },+ "customField1": {+ "type": "String",+ "name": "User String CF",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "visibility": "default"+ },+ "customField2": {+ "type": "CustomOption",+ "name": "User List cf",+ "required": false,+ "hasDefault": false,+ "writable": true,+ "visibility": "default","_embedded": {- "details": {- "attribute": "email"+ "allowedValues": [{+ "_type": "CustomOption",+ "id": 123,+ "value": "abc",+ "_links": {+ "self": {+ "href": "/api/v3/custom_options/123",+ "title": "abc"+ }+ }+ },+ {+ "_type": "CustomOption",+ "id": 124,+ "value": "foo",+ "_links": {+ "self": {+ "href": "/api/v3/custom_options/124",+ "title": "foo"+ }+ }}+ ]+ },+ "_links": {+ "allowedValues": [{+ "href": "/api/v3/custom_options/123",+ "title": "abc"+ },+ {+ "href": "/api/v3/custom_options/124",+ "title": "foo"+ }+ ]}+ },+ "_links": {}+ },+ "validationErrors": {}+ },+ "_links": {+ "self": {+ "href": "/api/v3/users/70917/form",+ "method": "post"+ },+ "validate": {+ "href": "/api/v3/users/70917/form",+ "method": "post"+ },+ "commit": {+ "href": "/api/v3/users/70917",+ "method": "patch"}+ }+ }+++ Response 400 (application/hal+json)++ Occurs when the client did not send a valid JSON object in the request body.++ + Body++ {+ "_type": "Error",+ "errorIdentifier": "urn:openproject-org:api:v3:errors:InvalidRequestBody",+ "message": "The request body was not a single JSON object."+ }+++ Response 403 (application/hal+json)++ Returned if the client does not have sufficient permissions.++ **Required permission:** manage_user global permission++ + Body++ {+ "_type": "Error",+ "errorIdentifier": "urn:openproject-org:api:v3:errors:MissingPermission",+ "message": "You are not authorized to access this resource."+ }+++ Response 404 (application/hal+json)++ Returned if the request user can not be found.++ *Note: A client without sufficient permissions shall not be able to test for the existence of+ a membership. That's why a 404 is returned here, even if a 403 might be more appropriate.*++ + Body++ {+ "_type": "Error",+ "errorIdentifier": "urn:openproject-org:api:v3:errors:NotFound",+ "message": "The requested resource could not be found."+ }+diff --git a/lib/api/v3/principals/principal_representer.rb b/lib/api/v3/principals/principal_representer.rbindex 00d80798f0c..7801107fa99 100644--- a/lib/api/v3/principals/principal_representer.rb+++ b/lib/api/v3/principals/principal_representer.rb@@ -71,13 +71,17 @@ module APIcache_if: -> { current_user_is_admin_or_self }def current_user_is_admin_or_self- current_user_is_admin || represented.id == current_user.id+ current_user_is_admin? || current_user_is_self?end- def current_user_is_admin+ def current_user_is_admin?current_user.admin?end+ def current_user_is_self?+ represented.id == current_user.id+ end+def current_user_allowed_to_see_members?current_user.allowed_to_globally?(:view_members) ||current_user.allowed_to_globally?(:manage_members)diff --git a/lib/api/v3/users/create_form_api.rb b/lib/api/v3/users/create_form_api.rbnew file mode 100644index 00000000000..42b951fa672--- /dev/null+++ b/lib/api/v3/users/create_form_api.rb@@ -0,0 +1,44 @@+#-- 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.+#++++module API+ module V3+ module Users+ class CreateFormAPI < ::API::OpenProjectAPI+ resource :form do+ after_validation do+ authorize :manage_user, global: true+ end++ post &::API::V3::Utilities::Endpoints::CreateForm.new(model: User)+ .mount+ end+ end+ end+ end+enddiff --git a/lib/api/v3/users/create_form_representer.rb b/lib/api/v3/users/create_form_representer.rbnew file mode 100644index 00000000000..3c77809105b--- /dev/null+++ b/lib/api/v3/users/create_form_representer.rb@@ -0,0 +1,39 @@+#-- 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.+#++++module API+ module V3+ module Users+ class CreateFormRepresenter < FormRepresenter+ include API::Decorators::CreateForm+ end+ end+ end+enddiff --git a/lib/api/v3/users/form_representer.rb b/lib/api/v3/users/form_representer.rbnew file mode 100644index 00000000000..4af0ac7bf35--- /dev/null+++ b/lib/api/v3/users/form_representer.rb@@ -0,0 +1,41 @@+#-- 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.+#++++module API+ module V3+ module Users+ class FormRepresenter < ::API::Decorators::SimpleForm+ def model+ User+ end+ end+ end+ end+enddiff --git a/lib/api/v3/users/schemas/user_schema_api.rb b/lib/api/v3/users/schemas/user_schema_api.rbnew file mode 100644index 00000000000..3751922fdf4--- /dev/null+++ b/lib/api/v3/users/schemas/user_schema_api.rb@@ -0,0 +1,41 @@+#-- 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.+#++++module API+ module V3+ module Users+ module Schemas+ class UserSchemaAPI < ::API::OpenProjectAPI+ resources :schema do+ get &::API::V3::Utilities::Endpoints::Schema.new(model: User).mount+ end+ end+ end+ end+ end+enddiff --git a/lib/api/v3/users/schemas/user_schema_representer.rb b/lib/api/v3/users/schemas/user_schema_representer.rbnew file mode 100644index 00000000000..6523f5faeb9--- /dev/null+++ b/lib/api/v3/users/schemas/user_schema_representer.rb@@ -0,0 +1,107 @@+#-- 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.+#++++module API+ module V3+ module Users+ module Schemas+ class UserSchemaRepresenter < ::API::Decorators::SchemaRepresenter+ extend ::API::V3::Utilities::CustomFieldInjector::RepresenterClass+ custom_field_injector type: :schema_representer++ schema :id,+ type: 'Integer'++ schema :login,+ type: 'String',+ min_length: 1,+ max_length: 255++ schema :admin,+ type: 'Boolean',+ required: false++ schema :email,+ type: 'String',+ min_length: 1,+ max_length: 255++ schema :name,+ type: 'String',+ required: false,+ writable: false++ schema :firstname,+ as: :firstName,+ type: 'String',+ min_length: 1,+ max_length: 255++ schema :lastname,+ as: :lastName,+ type: 'String',+ min_length: 1,+ max_length: 255++ schema :avatar,+ type: 'String',+ writable: false,+ required: false++ schema :status,+ type: 'String',+ required: false++ schema :identity_url,+ type: 'String',+ required: false++ schema :language,+ type: 'String',+ required: false++ schema :password,+ type: 'Password',+ required: false++ schema :created_at,+ type: 'DateTime'++ schema :updated_at,+ type: 'DateTime'++ def self.represented_class+ ::User+ end+ end+ end+ end+ end+enddiff --git a/lib/api/v3/users/update_form_api.rb b/lib/api/v3/users/update_form_api.rbnew file mode 100644index 00000000000..5d3c6c958b8--- /dev/null+++ b/lib/api/v3/users/update_form_api.rb@@ -0,0 +1,44 @@+#-- 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.+#++++module API+ module V3+ module Users+ class UpdateFormAPI < ::API::OpenProjectAPI+ resource :form do+ after_validation do+ authorize :manage_user, global: true+ end++ post &::API::V3::Utilities::Endpoints::UpdateForm.new(model: User)+ .mount+ end+ end+ end+ end+enddiff --git a/lib/api/v3/users/update_form_representer.rb b/lib/api/v3/users/update_form_representer.rbnew file mode 100644index 00000000000..c52dc01b83b--- /dev/null+++ b/lib/api/v3/users/update_form_representer.rb@@ -0,0 +1,39 @@+#-- 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.+#++++module API+ module V3+ module Users+ class UpdateFormRepresenter < FormRepresenter+ include API::Decorators::UpdateForm+ end+ end+ end+enddiff --git a/lib/api/v3/users/user_payload_representer.rb b/lib/api/v3/users/user_payload_representer.rbindex b1c8abfe8b1..2b7d0e76a82 100644--- a/lib/api/v3/users/user_payload_representer.rb+++ b/lib/api/v3/users/user_payload_representer.rb@@ -33,6 +33,8 @@ module APImodule Usersclass UserPayloadRepresenter < UserRepresenterinclude ::API::Utilities::PayloadRepresenter++ cached_representer disabled: trueendendenddiff --git a/lib/api/v3/users/user_representer.rb b/lib/api/v3/users/user_representer.rbindex 9408de3a448..fd96edb9076 100644--- a/lib/api/v3/users/user_representer.rb+++ b/lib/api/v3/users/user_representer.rb@@ -33,6 +33,7 @@ module APImodule Usersclass UserRepresenter < ::API::V3::Principals::PrincipalRepresenterinclude AvatarHelper+ extend ::API::V3::Utilities::CustomFieldInjector::RepresenterClasscached_representer key_parts: %i(auth_source),dependencies: ->(*) { avatar_cache_dependencies }@@ -40,7 +41,7 @@ module APIself_linklink :showUser do- next if represented.locked?+ next if represented.new_record? || represented.locked?{href: api_v3_paths.show_user(represented.id),@@ -49,7 +50,7 @@ module APIendlink :updateImmediately,- cache_if: -> { current_user_is_admin } do+ cache_if: -> { current_user_is_admin? } do{href: api_v3_paths.user(represented.id),title: "Update #{represented.login}",@@ -58,7 +59,7 @@ module APIendlink :lock,- cache_if: -> { current_user_is_admin } do+ cache_if: -> { current_user_is_admin? } donext unless represented.lockable?{@@ -69,7 +70,7 @@ module APIendlink :unlock,- cache_if: -> { current_user_is_admin } do+ cache_if: -> { current_user_is_admin? } donext unless represented.activatable?{@@ -89,7 +90,7 @@ module APIendlink :auth_source,- cache_if: -> { current_user_is_admin } do+ cache_if: -> { current_user_is_admin? } donext unless represented.auth_source{@@ -103,7 +104,7 @@ module APIrender_nil: false,getter: ->(*) { represented.login },setter: ->(fragment:, represented:, **) { represented.login = fragment },- cache_if: -> { current_user_is_admin_or_self }+ cache_if: -> { current_user_can_manage? }property :admin,exec_context: :decorator,@@ -112,25 +113,31 @@ module APIrepresented.admin?},setter: ->(fragment:, represented:, **) { represented.admin = fragment },- cache_if: -> { current_user_is_admin }+ cache_if: -> { current_user_is_admin? }- property :firstName,+ property :firstname,+ as: :firstName,exec_context: :decorator,getter: ->(*) { represented.firstname },- setter: ->(fragment:, represented:, **) { represented.firstname = fragment },+ setter: ->(fragment:, represented:, **) do+ represented.firstname = fragment+ end,render_nil: false,- cache_if: -> { current_user_is_admin_or_self }+ cache_if: -> { current_user_can_manage? }- property :lastName,+ property :lastname,+ as: :lastName,exec_context: :decorator,getter: ->(*) { represented.lastname },setter: ->(fragment:, represented:, **) { represented.lastname = fragment },render_nil: false,- cache_if: -> { current_user_is_admin_or_self }+ cache_if: -> { current_user_can_manage? }- property :mail,- as: :email,- cache_if: -> { !represented.pref.hide_mail || current_user_is_admin_or_self }+ property :email,+ getter: ->(*) { represented.mail },+ setter: ->(fragment:, represented:, **) { represented.mail = fragment },+ exec_context: :decorator,+ cache_if: -> { !represented.pref.hide_mail || represented.new_record? || current_user_can_manage? }property :avatar,exec_context: :decorator,@@ -138,10 +145,11 @@ module APIrender_nil: trueproperty :status,- getter: ->(*) { status },+ getter: ->(*) { represented.status },setter: ->(fragment:, represented:, **) { represented.status = User.statuses[fragment.to_sym] },+ exec_context: :decorator,render_nil: true,- cache_if: -> { current_user_is_admin_or_self }+ cache_if: -> { current_user_can_manage? }property :identity_url,exec_context: :decorator,@@ -149,14 +157,14 @@ module APIgetter: ->(*) { represented.identity_url },setter: ->(fragment:, represented:, **) { represented.identity_url = fragment },render_nil: true,- cache_if: -> { current_user_is_admin_or_self }+ cache_if: -> { current_user_can_manage? }property :language,exec_context: :decorator,render_nil: false,getter: ->(*) { represented.language },setter: ->(fragment:, represented:, **) { represented.language = fragment },- cache_if: -> { current_user_is_admin_or_self }+ cache_if: -> { current_user_can_manage? }# Write-only properties@@ -213,6 +221,10 @@ module APIcurrent_user && ::Users::DeleteContract.deletion_allowed?(represented, current_user)end+ def current_user_can_manage?+ current_user && (current_user.allowed_to_globally?(:manage_user) || current_user_is_self?)+ end+private##diff --git a/lib/api/v3/users/users_api.rb b/lib/api/v3/users/users_api.rbindex 342789fffbb..0698002ff4d 100644--- a/lib/api/v3/users/users_api.rb+++ b/lib/api/v3/users/users_api.rb@@ -73,6 +73,9 @@ module APIendend+ mount ::API::V3::Users::Schemas::UserSchemaAPI+ mount ::API::V3::Users::CreateFormAPI+params dorequires :id, desc: 'User\'s id'end@@ -90,6 +93,8 @@ module APIpatch &::API::V3::Utilities::Endpoints::Update.new(model: User).mountdelete &::API::V3::Utilities::Endpoints::Delete.new(model: User, success_status: 202).mount+ mount ::API::V3::Users::UpdateFormAPI+namespace :lock do# Authenticate lock transitionsafter_validation dodiff --git a/lib/api/v3/utilities/path_helper.rb b/lib/api/v3/utilities/path_helper.rbindex fb3e9debdd8..4bf2e9754d9 100644--- a/lib/api/v3/utilities/path_helper.rb+++ b/lib/api/v3/utilities/path_helper.rb@@ -367,8 +367,7 @@ module API"#{project(project_id)}/types"end- index :user- show :user+ resources :userdef self.user_lock(id)"#{user(id)}/lock"diff --git a/lib/open_project/patches/representable.rb b/lib/open_project/patches/representable.rbindex f63d473a01c..41471791d71 100644--- a/lib/open_project/patches/representable.rb+++ b/lib/open_project/patches/representable.rb@@ -27,29 +27,55 @@#++require 'representable'+require 'open_project/patches'module OpenProject::Patches::Representable- def self.included(base)- base.class_eval do- def self.as_strategy=(strategy)- raise 'The :as_strategy option should respond to #call?' unless strategy.respond_to?(:call)+ module DecoratorPatch+ def self.included(base)+ base.class_eval do+ def self.as_strategy=(strategy)+ raise 'The :as_strategy option should respond to #call?' unless strategy.respond_to?(:call)- @as_strategy = strategy- end+ @as_strategy = strategy+ end++ def self.as_strategy+ @as_strategy+ end++ def self.property(name, options = {}, &block)+ options = { as: as_strategy.call(name.to_s) }.merge(options) if as_strategy- def self.as_strategy- @as_strategy+ super+ endend+ end+ end- def self.property(name, options = {}, &block)- options = { as: as_strategy.call(name.to_s) }.merge(options) if as_strategy+ module OverwriteOnNilPatch+ def self.included(base)+ base.class_eval do+ unless const_defined?(:OverwriteOnNil)+ raise "Missing OverwriteOnNil on Representable gem, check if this patch still applies"+ end- super+ remove_const :OverwriteOnNil++ ##+ # Redefine OverwriteOnNil to ensure we use the correct setter+ # https://github.com/trailblazer/representable/issues/234+ const_set(:OverwriteOnNil, ->(input, *) { input })endendendend-unless Representable::Decorator.included_modules.include?(OpenProject::Patches::Representable)- Representable::Decorator.include OpenProject::Patches::Representable+OpenProject::Patches.patch_gem_version 'representable', '3.0.4' do+ unless Representable::Decorator.included_modules.include?(OpenProject::Patches::Representable::DecoratorPatch)+ Representable::Decorator.include OpenProject::Patches::Representable::DecoratorPatch+ end++ unless Representable::Decorator.included_modules.include?(OpenProject::Patches::Representable::OverwriteOnNilPatch)+ Representable.include OpenProject::Patches::Representable::OverwriteOnNilPatch+ endenddiff --git a/spec/lib/api/v3/principals/principal_representer_factory_spec.rb b/spec/lib/api/v3/principals/principal_representer_factory_spec.rbindex a8f4e3de637..d6746bfc07f 100644--- a/spec/lib/api/v3/principals/principal_representer_factory_spec.rb+++ b/spec/lib/api/v3/principals/principal_representer_factory_spec.rb@@ -83,7 +83,7 @@ describe ::API::V3::Principals::PrincipalRepresenterFactory dodescribe '.create_link_lambda' dosubject(:link) doTestRepresenter- .new(represented, current_user: nil)+ .new(represented, current_user: current_user).instance_exec(&described_class.create_link_lambda('association'))end@@ -127,7 +127,7 @@ describe ::API::V3::Principals::PrincipalRepresenterFactory dodescribe '.create_getter_lambda' dosubject(:getter) doTestRepresenter- .new(represented, current_user: nil, embed_links: embed_links)+ .new(represented, current_user: current_user, embed_links: embed_links).instance_exec(&described_class.create_getter_lambda('association'))enddiff --git a/spec/requests/api/v3/user/create_form_resource_spec.rb b/spec/requests/api/v3/user/create_form_resource_spec.rbnew file mode 100644index 00000000000..2e6b534de3a--- /dev/null+++ b/spec/requests/api/v3/user/create_form_resource_spec.rb@@ -0,0 +1,196 @@+#-- 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.++require 'spec_helper'+require 'rack/test'++describe ::API::V3::Users::CreateFormAPI, content_type: :json do+ include Rack::Test::Methods+ include API::V3::Utilities::PathHelper++ let(:path) { api_v3_paths.create_user_form }++ before do+ login_as(current_user)++ post path, payload.to_json+ end++ subject(:response) { last_response }+ let(:body) { response.body }++ context 'with authorized user' do+ shared_let(:current_user) { FactoryBot.create :user, global_permission: :manage_user }++ describe 'empty params' do+ let(:payload) do+ {}+ end++ it 'returns a payload with validation errors', :aggregate_failures do+ expect(response.status).to eq(200)+ expect(response.body).to be_json_eql('Form'.to_json).at_path('_type')++ expect(body)+ .to be_json_eql(''.to_json)+ .at_path('_embedded/payload/login')+ expect(body)+ .to be_json_eql(''.to_json)+ .at_path('_embedded/payload/email')+ expect(body)+ .to be_json_eql(''.to_json)+ .at_path('_embedded/payload/language')+ expect(body)+ .to be_json_eql('active'.to_json)+ .at_path('_embedded/payload/status')++ expect(body)+ .to have_json_size(5)+ .at_path('_embedded/validationErrors')++ expect(body)+ .to have_json_path('_embedded/validationErrors/password')++ expect(body)+ .to have_json_path('_embedded/validationErrors/login')++ expect(body)+ .to have_json_path('_embedded/validationErrors/email')++ expect(body)+ .to have_json_path('_embedded/validationErrors/firstName')++ expect(body)+ .to have_json_path('_embedded/validationErrors/lastName')++ expect(body)+ .not_to have_json_path('_links/commit')+ end+ end++ describe 'inviting a user' do+ let(:payload) do+ {+ email: '[email protected]',+ status: 'invited'+ }+ end++ it 'returns a valid payload', :aggregate_failures do+ expect(response.status).to eq(200)+ expect(response.body).to be_json_eql('Form'.to_json).at_path('_type')++ expect(body)+ .to be_json_eql('invited'.to_json)+ .at_path('_embedded/payload/status')++ expect(body)+ .to be_json_eql('[email protected]'.to_json)+ .at_path('_embedded/payload/email')++ expect(body)+ .to be_json_eql('foo'.to_json)+ .at_path('_embedded/payload/firstName')++ expect(body)+ .to be_json_eql('@example.com'.to_json)+ .at_path('_embedded/payload/lastName')++ expect(body)+ .to have_json_size(0)+ .at_path('_embedded/validationErrors')+ end+ end++ describe 'with custom fields' do+ let!(:custom_field) do+ FactoryBot.create(:string_user_custom_field)+ end+ let!(:list_custom_field) do+ FactoryBot.create(:list_user_custom_field)+ end+ let(:custom_option_href) { api_v3_paths.custom_option(list_custom_field.custom_options.first.id) }++ let(:payload) do+ {+ email: '[email protected]',+ status: 'invited',+ "customField#{custom_field.id}": "A custom value",+ "_links": {+ "customField#{list_custom_field.id}": {+ "href": custom_option_href+ }+ }+ }+ end++ it 'returns a valid form response' do+ expect(response.status).to eq(200)+ expect(response.body).to be_json_eql('Form'.to_json).at_path('_type')++ expect(body)+ .to be_json_eql('invited'.to_json)+ .at_path('_embedded/payload/status')++ expect(body)+ .to be_json_eql('[email protected]'.to_json)+ .at_path('_embedded/payload/email')++ expect(body)+ .to be_json_eql('cfuser'.to_json)+ .at_path('_embedded/payload/firstName')++ expect(body)+ .to be_json_eql('@example.com'.to_json)+ .at_path('_embedded/payload/lastName')++ expect(body)+ .to be_json_eql('A custom value'.to_json)+ .at_path("_embedded/payload/customField#{custom_field.id}")++ expect(body)+ .to be_json_eql(custom_option_href.to_json)+ .at_path("_embedded/payload/_links/customField#{list_custom_field.id}/href")++ expect(body)+ .to have_json_size(0)+ .at_path('_embedded/validationErrors')+ end+ end+ end++ context 'with unauthorized user' do+ shared_let(:current_user) { FactoryBot.create :user }+ let(:payload) do+ {}+ end++ it_behaves_like 'unauthorized access'+ end+enddiff --git a/spec/requests/api/v3/user/create_user_common_examples.rb b/spec/requests/api/v3/user/create_user_common_examples.rbindex 9403287010e..5ecd186251c 100644--- a/spec/requests/api/v3/user/create_user_common_examples.rb+++ b/spec/requests/api/v3/user/create_user_common_examples.rb@@ -70,7 +70,7 @@ shared_examples 'create user request flow' doexpect(errors.count).to eq(5)expect(errors.collect { |el| el['_embedded']['details']['attribute'] })- .to contain_exactly('password', 'login', 'firstname', 'lastname', 'email')+ .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)@@ -131,7 +131,7 @@ shared_examples 'create user request flow' doexpect(errors.count).to eq 4attributes = errors.map { |error| error.dig('_embedded', 'details', 'attribute') }- expect(attributes).to contain_exactly('login', 'firstname', 'lastname', 'email')+ expect(attributes).to contain_exactly('login', 'firstName', 'lastName', 'email')endendenddiff --git a/spec/requests/api/v3/user/schemas/user_schema_resource_spec.rb b/spec/requests/api/v3/user/schemas/user_schema_resource_spec.rbnew file mode 100644index 00000000000..176ca730aad--- /dev/null+++ b/spec/requests/api/v3/user/schemas/user_schema_resource_spec.rb@@ -0,0 +1,63 @@+#-- 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'+require 'rack/test'++describe 'API v3 Users schema resource', type: :request, content_type: :json do+ include Rack::Test::Methods+ include API::V3::Utilities::PathHelper++ shared_let(:current_user) do+ FactoryBot.create(:user)+ end++ let(:path) { api_v3_paths.user_schema }++ before do+ login_as(current_user)+ end++ subject(:response) { last_response }++ describe '#GET /users/schema' do+ before do+ get path+ end++ it 'responds with 200 OK' do+ expect(subject.status).to eq(200)+ end++ it 'returns a schema' do+ expect(subject.body)+ .to be_json_eql('Schema'.to_json)+ .at_path '_type'+ end+ end+enddiff --git a/spec/requests/api/v3/user/update_form_resource_spec.rb b/spec/requests/api/v3/user/update_form_resource_spec.rbnew file mode 100644index 00000000000..9dedf1c8319--- /dev/null+++ b/spec/requests/api/v3/user/update_form_resource_spec.rb@@ -0,0 +1,173 @@+#-- 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.++require 'spec_helper'+require 'rack/test'++describe ::API::V3::Users::UpdateFormAPI, content_type: :json do+ include Rack::Test::Methods+ include API::V3::Utilities::PathHelper++ shared_let(:text_custom_field) do+ FactoryBot.create(:string_user_custom_field)+ end+ shared_let(:list_custom_field) do+ FactoryBot.create(:list_user_custom_field)+ end+ shared_let(:user) do+ FactoryBot.create(:user,+ "custom_field_#{text_custom_field.id}": "CF text",+ "custom_field_#{list_custom_field.id}": list_custom_field.custom_options.first)+ end++ let(:path) { api_v3_paths.user_form(user.id) }+ let(:payload) do+ {}+ end++ before do+ login_as(current_user)++ post path, payload.to_json+ end++ subject(:response) { last_response }+ let(:body) { response.body }++ context 'with authorized user' do+ shared_let(:current_user) do+ FactoryBot.create(:user, global_permission: :manage_user)+ end++ describe 'empty payload' do+ it 'returns a valid form', :aggregate_failures do+ expect(response.status).to eq(200)+ expect(response.body).to be_json_eql('Form'.to_json).at_path('_type')++ expect(body)+ .to be_json_eql(user.mail.to_json)+ .at_path('_embedded/payload/email')++ expect(body)+ .to be_json_eql(user.firstname.to_json)+ .at_path('_embedded/payload/firstName')++ expect(body)+ .to be_json_eql(user.lastname.to_json)+ .at_path('_embedded/payload/lastName')++ expect(body)+ .to have_json_size(0)+ .at_path('_embedded/validationErrors')+ end+ end++ describe 'with a non-writable status' do+ let(:payload) do+ {+ "status": 'locked'+ }+ end++ it 'returns an invalid form', :aggregate_failures do+ expect(response.status).to eq(200)+ expect(response.body).to be_json_eql('Form'.to_json).at_path('_type')++ expect(subject.body)+ .to have_json_size(1)+ .at_path('_embedded/validationErrors')++ expect(subject.body)+ .to have_json_path('_embedded/validationErrors/status')++ expect(body)+ .to be_json_eql('urn:openproject-org:api:v3:errors:PropertyIsReadOnly'.to_json)+ .at_path('_embedded/validationErrors/status/errorIdentifier')++ # Does not change the user's status+ user.reload+ expect(user.status).to eq 'active'+ end+ end++ describe 'with an empty firstname' do+ let(:payload) do+ {+ "firstName": nil+ }+ end++ it 'returns an invalid form', :aggregate_failures do+ expect(response.status).to eq(200)+ expect(response.body).to be_json_eql('Form'.to_json).at_path('_type')++ expect(body)+ .to be_json_eql(user.mail.to_json)+ .at_path('_embedded/payload/email')++ expect(body)+ .to_not have_json_path('_embedded/payload/firstName')++ expect(body)+ .to be_json_eql(user.lastname.to_json)+ .at_path('_embedded/payload/lastName')++ expect(subject.body)+ .to have_json_size(1)+ .at_path('_embedded/validationErrors')++ expect(subject.body)+ .to have_json_path('_embedded/validationErrors/firstName')++ expect(subject.body)+ .not_to have_json_path('_links/commit')++ name_before = user.name++ expect(user.reload.name)+ .to eql name_before+ end+ end++ context 'with a non existing id' do+ let(:path) { api_v3_paths.user_form(12345) }++ it 'returns 404 Not found' do+ expect(response.status).to eq(404)+ end+ end+ end++ context 'with unauthorized user' do+ let(:current_user) { FactoryBot.create :user }++ it_behaves_like 'unauthorized access'+ end++end