From 2dd5f3688ea6b29a0ea91cf5a8e8e9a30a6296b9 Mon Sep 17 00:00:00 2001 From: Zsombor Gegesy Date: Tue, 22 Dec 2020 11:28:44 +0100 Subject: [PATCH] Add AdminUserDTO and the PublicUserResource - to separate the publicly accessible user information from the private one. Porting https://github.com/jhipster/generator-jhipster/issues/12374 --- generators/server/files.cjs | 15 +- .../java/package/service/UserService.java.ejs | 17 +- .../package/service/dto/AdminUserDTO.java.ejs | 183 ++++++++++++++++++ .../java/package/service/dto/UserDTO.java.ejs | 152 ++------------- .../service/mapper/UserMapper.java.ejs | 16 +- .../package/web/rest/AccountResource.java.ejs | 15 +- .../web/rest/PublicUserResource.java.ejs | 63 ++++++ .../package/web/rest/UserResource.java.ejs | 42 ++-- .../web/rest/vm/ManagedUserVM.java.ejs | 6 +- .../package/service/UserServiceIT.java.ejs | 6 +- .../service/mapper/UserMapperIT.java.ejs | 11 +- .../web/rest/AccountResourceIT.java.ejs | 12 +- .../package/web/rest/UserResourceIT.java.ejs | 31 +-- 13 files changed, 357 insertions(+), 212 deletions(-) create mode 100644 generators/server/templates/src/main/java/package/service/dto/AdminUserDTO.java.ejs create mode 100644 generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs diff --git a/generators/server/files.cjs b/generators/server/files.cjs index 7cd90dde..5adeeb2c 100644 --- a/generators/server/files.cjs +++ b/generators/server/files.cjs @@ -621,9 +621,15 @@ const serverFiles = { condition: generator => !generator.skipUserManagement || generator.authenticationType === 'oauth2', path: SERVER_MAIN_SRC_DIR, templates: [ + { + file: 'package/service/dto/AdminUserDTO.java', + renameTo: generator => `${generator.javaDir}service/dto/${generator.asDto('AdminUser')}.java`, + useBluePrint: true, + }, + { file: 'package/service/dto/UserDTO.java', - renameTo: generator => `${generator.javaDir}service/dto/UserDTO.java`, + renameTo: generator => `${generator.javaDir}service/dto/${generator.asDto('User')}.java`, useBluePrint: true, }, { @@ -762,7 +768,12 @@ const serverFiles = { renameTo: generator => `${generator.javaDir}web/rest/vm/ManagedUserVM.java`, useBluePrint: true, }, - // Base rest pkg + { + file: 'package/web/rest/PublicUserResource.java', + renameTo: generator => `${generator.javaDir}web/rest/PublicUserResource.java`, + useBluePrint: true, + }, + // Base rest pkg { file: 'package/web/rest/ClientForwardController.java', renameTo: generator => `${generator.javaDir}web/rest/ClientForwardController.java`, diff --git a/generators/server/templates/src/main/java/package/service/UserService.java.ejs b/generators/server/templates/src/main/java/package/service/UserService.java.ejs index 2a4ccf6a..a0acaf7f 100644 --- a/generators/server/templates/src/main/java/package/service/UserService.java.ejs +++ b/generators/server/templates/src/main/java/package/service/UserService.java.ejs @@ -10,6 +10,7 @@ import <%=packageName%>.repository.AuthorityRepository; import <%=packageName%>.repository.UserRepository; import <%=packageName%>.security.AuthoritiesConstants; import <%=packageName%>.security.SecurityUtils; +import <%=packageName%>.service.dto.AdminUserDTO; import <%=packageName%>.service.dto.UserDTO; import <%=packageName%>.service.util.RandomUtil; import <%=packageName%>.web.rest.errors.*; @@ -141,7 +142,7 @@ public class UserService { }); } - public User registerUser(UserDTO userDTO, String password) { + public User registerUser(AdminUserDTO userDTO, String password) { userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).ifPresent(existingUser -> { boolean removed = removeNonActivatedUser(existingUser); if (!removed) { @@ -191,7 +192,7 @@ public class UserService { return true; } - public User createUser(UserDTO userDTO) { + public User createUser(AdminUserDTO userDTO) { User user = new User(); user.setLogin(userDTO.getLogin().toLowerCase()); user.setFirstName(userDTO.getFirstName()); @@ -230,7 +231,7 @@ public class UserService { * @param userDTO user to update. * @return updated user. */ - public Optional updateUser(UserDTO userDTO) { + public Optional updateUser(AdminUserDTO userDTO) { return Optional.of(userRepository .findById(userDTO.getId())) .filter(Optional::isPresent) @@ -260,7 +261,7 @@ public class UserService { log.debug("Changed Information for User: {}", user); return user; }) - .map(UserDTO::new); + .map(AdminUserDTO::new); } public void deleteUser(String login) { @@ -319,7 +320,13 @@ public class UserService { } @ReadOnly - public Page getAllManagedUsers(Pageable pageable) { + public Page getAllManagedUsers(Pageable pageable) { + Page userPage = userRepository.findAllByLoginNot(Constants.ANONYMOUS_USER, pageable); + return Page.of(userPage.getContent().stream().map(AdminUserDTO::new).collect(Collectors.toList()), pageable, userPage.getTotalSize()); + } + + @ReadOnly + public Page getAllPublicUsers(Pageable pageable) { Page userPage = userRepository.findAllByLoginNot(Constants.ANONYMOUS_USER, pageable); return Page.of(userPage.getContent().stream().map(UserDTO::new).collect(Collectors.toList()), pageable, userPage.getTotalSize()); } diff --git a/generators/server/templates/src/main/java/package/service/dto/AdminUserDTO.java.ejs b/generators/server/templates/src/main/java/package/service/dto/AdminUserDTO.java.ejs new file mode 100644 index 00000000..adaef869 --- /dev/null +++ b/generators/server/templates/src/main/java/package/service/dto/AdminUserDTO.java.ejs @@ -0,0 +1,183 @@ +package <%=packageName%>.service.dto; + +import <%=packageName%>.config.Constants; + +import <%=packageName%>.domain.Authority; +import <%=packageName%>.domain.User; +import io.micronaut.core.annotation.Introspected; + +import javax.validation.constraints.Email; +import javax.validation.constraints.NotBlank; + +import javax.validation.constraints.*; +import java.time.Instant; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * A DTO representing a user, with their authorities. + */ +@Introspected +public class <%= asDto('AdminUser') %> { + + private <%= userPkType %> id; + + @NotBlank + @Pattern(regexp = Constants.LOGIN_REGEX) + @Size(min = 1, max = 50) + private String login; + + @Size(max = 50) + private String firstName; + + @Size(max = 50) + private String lastName; + + @Email + @Size(min = 5, max = 254) + private String email; + + @Size(max = 256) + private String imageUrl; + + private boolean activated = false; + + @Size(min = 2, max = 6) + private String langKey; + + private String createdBy; + + private Instant createdDate; + + private String lastModifiedBy; + + private Instant lastModifiedDate; + + private Set authorities; + + public <%= asDto('AdminUser') %>() { + // Empty constructor needed for Jackson. + } + + public <%= asDto('AdminUser') %>(User user) { + this.id = user.getId(); + this.login = user.getLogin(); + this.firstName = user.getFirstName(); + this.lastName = user.getLastName(); + this.email = user.getEmail(); + this.activated = user.getActivated(); + this.imageUrl = user.getImageUrl(); + this.langKey = user.getLangKey(); + this.createdDate = user.getCreatedDate(); + this.lastModifiedDate = user.getLastModifiedDate(); + this.authorities = user.getAuthorities().stream() + .map(Authority::getName) + .collect(Collectors.toSet()); + } + + public <%= userPkType %> getId() { + return id; + } + + public void setId(<%= userPkType %> id) { + this.id = id; + } + + public String getLogin() { + return login; + } + + public void setLogin(String login) { + this.login = login; + } + + public String getFirstName() { + return firstName; + } + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public String getLastName() { + return lastName; + } + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } + + public String getImageUrl() { + return imageUrl; + } + + public void setImageUrl(String imageUrl) { + this.imageUrl = imageUrl; + } + + public boolean isActivated() { + return activated; + } + + public void setActivated(boolean activated) { + this.activated = activated; + } + + public String getLangKey() { + return langKey; + } + + public void setLangKey(String langKey) { + this.langKey = langKey; + } + + public Instant getCreatedDate() { + return createdDate; + } + + public void setCreatedDate(Instant createdDate) { + this.createdDate = createdDate; + } + + public Instant getLastModifiedDate() { + return lastModifiedDate; + } + + public void setLastModifiedDate(Instant lastModifiedDate) { + this.lastModifiedDate = lastModifiedDate; + } + + public Set getAuthorities() { + return authorities; + } + + public void setAuthorities(Set authorities) { + this.authorities = authorities; + } + + @Override + public String toString() { + return "<%= asDto('AdminUser') %>{" + + "login='" + login + '\'' + + ", firstName='" + firstName + '\'' + + ", lastName='" + lastName + '\'' + + ", email='" + email + '\'' + + ", imageUrl='" + imageUrl + '\'' + + ", activated=" + activated + + ", langKey='" + langKey + '\'' + + ", createdBy=" + createdBy + + ", createdDate=" + createdDate + + ", lastModifiedBy='" + lastModifiedBy + '\'' + + ", lastModifiedDate=" + lastModifiedDate + + ", authorities=" + authorities + + "}"; + } +} diff --git a/generators/server/templates/src/main/java/package/service/dto/UserDTO.java.ejs b/generators/server/templates/src/main/java/package/service/dto/UserDTO.java.ejs index 0fcb5475..91b40849 100644 --- a/generators/server/templates/src/main/java/package/service/dto/UserDTO.java.ejs +++ b/generators/server/templates/src/main/java/package/service/dto/UserDTO.java.ejs @@ -15,73 +15,31 @@ import java.util.Set; import java.util.stream.Collectors; /** - * A DTO representing a user, with their authorities. + * A DTO representing a user, with only the public attributes. */ @Introspected -public class UserDTO %> { +public class <%= asDto('User') %> { - private <% if (authenticationType === 'oauth2') { %>String<% } else { %>Long<% } %> id; - - @NotBlank - @Pattern(regexp = Constants.LOGIN_REGEX) - @Size(min = 1, max = 50) + private <%= userPkType %> id; private String login; - @Size(max = 50) - private String firstName; - - @Size(max = 50) - private String lastName; - - @Email - @Size(min = 5, max = 254) - private String email; - - @Size(max = 256) - private String imageUrl; - - private boolean activated = false; - - @Size(min = 2, max = 6) - private String langKey; - - private String createdBy; - - private Instant createdDate; - - private String lastModifiedBy; - - private Instant lastModifiedDate; - - private Set authorities; - - public UserDTO() { + <%_ if (databaseType !== 'no') { _%> + public <%= asDto('User') %>() { // Empty constructor needed for Jackson. } - public UserDTO(User user) { + public <%= asDto('User') %>(<%= asEntity('User') %> user) { this.id = user.getId(); + // Customize it here if you need firstName/lastName/etc this.login = user.getLogin(); - this.firstName = user.getFirstName(); - this.lastName = user.getLastName(); - this.email = user.getEmail(); - this.activated = user.getActivated(); - this.imageUrl = user.getImageUrl(); - this.langKey = user.getLangKey(); - //this.createdBy = user.getCreatedBy(); - this.createdDate = user.getCreatedDate(); - //this.lastModifiedBy = user.getLastModifiedBy(); - this.lastModifiedDate = user.getLastModifiedDate(); - this.authorities = user.getAuthorities().stream() - .map(Authority::getName) - .collect(Collectors.toSet()); } - public <% if (authenticationType === 'oauth2') { %>String<% } else { %>Long<% } %> getId() { + <%_ } _%> + public <%= userPkType %> getId() { return id; } - public void setId(<% if (authenticationType === 'oauth2') { %>String<% } else { %>Long<% } %> id) { + public void setId(<%= userPkType %> id) { this.id = id; } @@ -93,93 +51,13 @@ public class UserDTO %> { this.login = login; } - public String getFirstName() { - return firstName; - } - - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getEmail() { - return email; - } - - public void setEmail(String email) { - this.email = email; - } - - public String getImageUrl() { - return imageUrl; - } - - public void setImageUrl(String imageUrl) { - this.imageUrl = imageUrl; - } - - public boolean isActivated() { - return activated; - } - - public void setActivated(boolean activated) { - this.activated = activated; - } - - public String getLangKey() { - return langKey; - } - - public void setLangKey(String langKey) { - this.langKey = langKey; - } - - public Instant getCreatedDate() { - return createdDate; - } - - public void setCreatedDate(Instant createdDate) { - this.createdDate = createdDate; - } - - public Instant getLastModifiedDate() { - return lastModifiedDate; - } - - public void setLastModifiedDate(Instant lastModifiedDate) { - this.lastModifiedDate = lastModifiedDate; - } - - public Set getAuthorities() { - return authorities; - } - - public void setAuthorities(Set authorities) { - this.authorities = authorities; - } - + // prettier-ignore @Override public String toString() { - return "UserDTO{" + - "login='" + login + '\'' + - ", firstName='" + firstName + '\'' + - ", lastName='" + lastName + '\'' + - ", email='" + email + '\'' + - ", imageUrl='" + imageUrl + '\'' + - ", activated=" + activated + - ", langKey='" + langKey + '\'' + - ", createdBy=" + createdBy + - ", createdDate=" + createdDate + - ", lastModifiedBy='" + lastModifiedBy + '\'' + - ", lastModifiedDate=" + lastModifiedDate + - ", authorities=" + authorities + + return "<%= asDto('User') %>{" + + "id='" + id + '\'' + + ", login='" + login + '\'' + "}"; } + } diff --git a/generators/server/templates/src/main/java/package/service/mapper/UserMapper.java.ejs b/generators/server/templates/src/main/java/package/service/mapper/UserMapper.java.ejs index 5efeaa45..8f79024d 100644 --- a/generators/server/templates/src/main/java/package/service/mapper/UserMapper.java.ejs +++ b/generators/server/templates/src/main/java/package/service/mapper/UserMapper.java.ejs @@ -2,6 +2,7 @@ package <%=packageName%>.service.mapper; import <%=packageName%>.domain.Authority; import <%=packageName%>.domain.User; +import <%=packageName%>.service.dto.AdminUserDTO; import <%=packageName%>.service.dto.UserDTO; import javax.inject.Singleton; @@ -28,14 +29,25 @@ public class UserMapper { return new UserDTO(user); } - public List userDTOsToUsers(List userDTOs) { + public List usersToAdminUserDTOs(List users) { + return users.stream() + .filter(Objects::nonNull) + .map(this::userToAdminUserDTO) + .collect(Collectors.toList()); + } + + public AdminUserDTO userToAdminUserDTO(User user) { + return new AdminUserDTO(user); + } + + public List userDTOsToUsers(List userDTOs) { return userDTOs.stream() .filter(Objects::nonNull) .map(this::userDTOToUser) .collect(Collectors.toList()); } - public User userDTOToUser(UserDTO userDTO) { + public User userDTOToUser(AdminUserDTO userDTO) { if (userDTO == null) { return null; } else { diff --git a/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs index 3db73596..32656225 100644 --- a/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/AccountResource.java.ejs @@ -20,7 +20,7 @@ package <%= packageName %>.web.rest; <%_ if (authenticationType === 'oauth2') { _%> import <%=packageName%>.service.UserService; -import <%=packageName%>.service.dto.UserDTO; +import <%=packageName%>.service.dto.AdminUserDTO; import io.micronaut.http.annotation.*; import io.micronaut.scheduling.TaskExecutors; @@ -59,9 +59,9 @@ public class AccountResource { */ @Get("/account") @ExecuteOn(TaskExecutors.IO) - public UserDTO getAccount() { + public AdminUserDTO getAccount() { return userService.getUserWithAuthorities() - .map(UserDTO::new) + .map(AdminUserDTO::new) .orElseThrow(() -> new AccountResourceException("User could not be found")); } } @@ -69,11 +69,10 @@ public class AccountResource { import <%=packageName%>.domain.User; import <%=packageName%>.repository.UserRepository; -import <%=packageName%>.security.SecurityUtils; import <%=packageName%>.service.MailService; import <%=packageName%>.service.UserService; +import <%=packageName%>.service.dto.AdminUserDTO; import <%=packageName%>.service.dto.PasswordChangeDTO; -import <%=packageName%>.service.dto.UserDTO; import <%=packageName%>.web.rest.errors.*; import <%=packageName%>.web.rest.vm.KeyAndPasswordVM; import <%=packageName%>.web.rest.vm.ManagedUserVM; @@ -176,9 +175,9 @@ public class AccountResource { */ @Get("/account") @ExecuteOn(TaskExecutors.IO) - public UserDTO getAccount() { + public AdminUserDTO getAccount() { return userService.getUserWithAuthorities() - .map(UserDTO::new) + .map(AdminUserDTO::new) .orElseThrow(() -> new AccountResourceException("User could not be found")); } @@ -191,7 +190,7 @@ public class AccountResource { */ @Post("/account") @ExecuteOn(TaskExecutors.IO) - public void saveAccount(@Valid @Body UserDTO userDTO) { + public void saveAccount(@Valid @Body AdminUserDTO userDTO) { String userLogin = userService.getCurrentUserLogin().orElseThrow(() -> new AccountResourceException("Current user login not found")); Optional existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userLogin))) { diff --git a/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs new file mode 100644 index 00000000..2a552cd4 --- /dev/null +++ b/generators/server/templates/src/main/java/package/web/rest/PublicUserResource.java.ejs @@ -0,0 +1,63 @@ +package <%=packageName%>.web.rest; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import <%=packageName%>.service.UserService; +import <%=packageName%>.service.dto.UserDTO; +import <%=packageName%>.util.PaginationUtil; + +import io.micronaut.data.model.Page; +import io.micronaut.data.model.Pageable; +import io.micronaut.http.HttpRequest; +import io.micronaut.http.HttpResponse; +import io.micronaut.http.annotation.Controller; +import io.micronaut.http.annotation.Get; +import io.micronaut.http.uri.UriBuilder; +import io.micronaut.scheduling.TaskExecutors; +import io.micronaut.scheduling.annotation.ExecuteOn; + + +/** + * REST controller for providing public informations about users and roles. + */ +@Controller("/api") +public class PublicUserResource { + + private final Logger log = LoggerFactory.getLogger(PublicUserResource.class); + + private final UserService userService; + + public PublicUserResource(UserService userService) { + this.userService = userService; + } + + /** + * {@code GET /users} : get all users. + * + * @param pageable the pagination information. + * @return the {@link HttpResponse} with status {@code 200 (OK)} and with body all users. + */ + @Get("/users") + @ExecuteOn(TaskExecutors.IO) + public HttpResponse> getAllUsers(HttpRequest request, Pageable pageable) { + log.debug("REST request to get Users: {}", pageable); + final Page page = userService.getAllPublicUsers(pageable); + return HttpResponse.ok(page.getContent()).headers(headers -> + PaginationUtil.generatePaginationHttpHeaders(headers, UriBuilder.of(request.getPath()), page) + ); + } + + /** + * Gets a list of all roles. + * @return a string list of all roles. + */ + @Get("/authorities") + @ExecuteOn(TaskExecutors.IO) + public List getAuthorities() { + return userService.getAuthorities(); + } + +} \ No newline at end of file diff --git a/generators/server/templates/src/main/java/package/web/rest/UserResource.java.ejs b/generators/server/templates/src/main/java/package/web/rest/UserResource.java.ejs index 2f363df3..29cce256 100644 --- a/generators/server/templates/src/main/java/package/web/rest/UserResource.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/UserResource.java.ejs @@ -10,7 +10,7 @@ import <%=packageName%>.security.AuthoritiesConstants; import <%=packageName%>.service.MailService; <%_ } _%> import <%=packageName%>.service.UserService; -import <%=packageName%>.service.dto.UserDTO; +import <%=packageName%>.service.dto.AdminUserDTO; import <%=packageName%>.util.HeaderUtil; import <%=packageName%>.util.PaginationUtil; <%_ if (authenticationType !== 'oauth2') { _%> @@ -61,7 +61,7 @@ import java.util.*; *

* Another option would be to have a specific JPA entity graph to handle this case. */ -@Controller("/api") +@Controller("/api/admin") public class UserResource { private final Logger log = LoggerFactory.getLogger(UserResource.class); @@ -89,7 +89,7 @@ public class UserResource { <%_ if (authenticationType !== 'oauth2') { _%> /** - * {@code POST /users} : Creates a new user. + * {@code POST admin/users} : Creates a new user. *

* Creates a new user if the login and email are not already used, and sends an * mail with an activation link. @@ -103,7 +103,7 @@ public class UserResource { @Post("/users") @Secured(AuthoritiesConstants.ADMIN) @ExecuteOn(TaskExecutors.IO) - public HttpResponse createUser(@Valid @Body UserDTO userDTO) throws URISyntaxException { + public HttpResponse createUser(@Valid @Body AdminUserDTO userDTO) throws URISyntaxException { log.debug("REST request to save User : {}", userDTO); if (userDTO.getId() != null) { @@ -122,12 +122,12 @@ public class UserResource { applicationName, "userManagement.created", newUser.getLogin())) - .body(newUser); + .body(new AdminUserDTO(newUser)); } } /** - * {@code PUT /users} : Updates an existing User. + * {@code PUT admin/users} : Updates an existing User. * * @param userDTO the user to update. * @return the {@link HttpResponse} with status {@code 200 (OK)} and with body the updated user. @@ -137,7 +137,7 @@ public class UserResource { @Put("/users") @Secured(AuthoritiesConstants.ADMIN) @ExecuteOn(TaskExecutors.IO) - public HttpResponse updateUser(@Valid @Body UserDTO userDTO) { + public HttpResponse updateUser(@Valid @Body AdminUserDTO userDTO) { log.debug("REST request to update User : {}", userDTO); Optional existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()); if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { @@ -147,7 +147,7 @@ public class UserResource { if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) { throw new LoginAlreadyUsedException(); } - Optional updatedUser = userService.updateUser(userDTO); + Optional updatedUser = userService.updateUser(userDTO); return updatedUser.map(user -> HttpResponse.ok(user) @@ -157,48 +157,38 @@ public class UserResource { <%_ } _%> /** - * {@code GET /users} : get all users. + * {@code GET admin/users} : get all users. * * @param pageable the pagination information. * @return the {@link HttpResponse} with status {@code 200 (OK)} and with body all users. */ @Get("/users") @ExecuteOn(TaskExecutors.IO) - public HttpResponse> getAllUsers(HttpRequest request, Pageable pageable) { - final Page page = userService.getAllManagedUsers(pageable); + public HttpResponse> getAllUsers(HttpRequest request, Pageable pageable) { + log.debug("REST request to get Users for admin: {}", pageable); + final Page page = userService.getAllManagedUsers(pageable); return HttpResponse.ok(page.getContent()).headers(headers -> PaginationUtil.generatePaginationHttpHeaders(headers, UriBuilder.of(request.getPath()), page) ); } /** - * Gets a list of all roles. - * @return a string list of all roles. - */ - @Get("/users/authorities") - @Secured(AuthoritiesConstants.ADMIN) - @ExecuteOn(TaskExecutors.IO) - public List getAuthorities() { - return userService.getAuthorities(); - } - - /** - * {@code GET /users/:login} : get the "login" user. + * {@code GET /admin/users/:login} : get the "login" user. * * @param login the login of the user to find. * @return the {@link HttpResponse} with status {@code 200 (OK)} and with body the "login" user, or with status {@code 404 (Not Found)}. */ @Get("/users/{login:" + Constants.LOGIN_REGEX + "}") @ExecuteOn(TaskExecutors.IO) - public Optional getUser(@PathVariable String login) { + public Optional getUser(@PathVariable String login) { log.debug("REST request to get User : {}", login); return userService.getUserWithAuthoritiesByLogin(login) - .map(UserDTO::new); + .map(AdminUserDTO::new); } <%_ if (authenticationType !== 'oauth2') { _%> /** - * {@code DELETE /users/:login} : delete the "login" User. + * {@code DELETE /admin/users/:login} : delete the "login" User. * * @param login the login of the user to delete. * @return the {@link HttpResponse} with status {@code 204 (NO_CONTENT)}. diff --git a/generators/server/templates/src/main/java/package/web/rest/vm/ManagedUserVM.java.ejs b/generators/server/templates/src/main/java/package/web/rest/vm/ManagedUserVM.java.ejs index 320fc0a8..cf6fbc07 100644 --- a/generators/server/templates/src/main/java/package/web/rest/vm/ManagedUserVM.java.ejs +++ b/generators/server/templates/src/main/java/package/web/rest/vm/ManagedUserVM.java.ejs @@ -1,15 +1,15 @@ package <%=packageName%>.web.rest.vm; -import <%=packageName%>.service.dto.UserDTO; +import <%=packageName%>.service.dto.AdminUserDTO; import io.micronaut.core.annotation.Introspected; import javax.validation.constraints.Size; /** - * View Model extending the UserDTO, which is meant to be used in the user management UI. + * View Model extending the AdminUserDTO, which is meant to be used in the user management UI. */ @Introspected -public class ManagedUserVM extends UserDTO { +public class ManagedUserVM extends AdminUserDTO { public static final int PASSWORD_MIN_LENGTH = 4; diff --git a/generators/server/templates/src/test/java/package/service/UserServiceIT.java.ejs b/generators/server/templates/src/test/java/package/service/UserServiceIT.java.ejs index 8e916f95..69fc207b 100644 --- a/generators/server/templates/src/test/java/package/service/UserServiceIT.java.ejs +++ b/generators/server/templates/src/test/java/package/service/UserServiceIT.java.ejs @@ -8,7 +8,7 @@ import <%=packageName%>.domain.User; import <%=packageName%>.repository.AuthorityRepository; import <%=packageName%>.repository.UserRepository; import <%=packageName%>.security.AuthoritiesConstants; -import <%=packageName%>.service.dto.UserDTO; +import <%=packageName%>.service.dto.AdminUserDTO; import <%=packageName%>.service.util.RandomUtil; <%_ if (authenticationType !== 'oauth2') { _%> import <%=packageName%>.web.rest.errors.EmailAlreadyUsedException; @@ -181,7 +181,7 @@ public class UserServiceIT { userRepository.saveAndFlush(user); } final Pageable pageable = Pageable.from(0, (int) userRepository.count()); - final Page allManagedUsers = userService.getAllManagedUsers(pageable); + final Page allManagedUsers = userService.getAllManagedUsers(pageable); assertThat(allManagedUsers.getContent().stream() .noneMatch(user -> Constants.ANONYMOUS_USER.equals(user.getLogin()))) .isTrue(); @@ -304,7 +304,7 @@ public class UserServiceIT { assertThat(testUser4.get().getEmail()).isEqualTo("test-register-duplicate-email@example.com"); testUser4.get().setActivated(true); - userService.updateUser((new UserDTO(testUser4.get()))); + userService.updateUser(new AdminUserDTO(testUser4.get())); // Register 4th (already activated) user Assertions.assertThrows(EmailAlreadyUsedException.class, () -> { diff --git a/generators/server/templates/src/test/java/package/service/mapper/UserMapperIT.java.ejs b/generators/server/templates/src/test/java/package/service/mapper/UserMapperIT.java.ejs index 5cc7fba7..d4be86f5 100644 --- a/generators/server/templates/src/test/java/package/service/mapper/UserMapperIT.java.ejs +++ b/generators/server/templates/src/test/java/package/service/mapper/UserMapperIT.java.ejs @@ -4,6 +4,7 @@ import <%= packageName %>.RedisTestContainerExtension; <%_ } _%> import <%=packageName%>.<%= mainClass %>; import <%=packageName%>.domain.User; +import <%=packageName%>.service.dto.AdminUserDTO; import <%=packageName%>.service.dto.UserDTO; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import org.apache.commons.lang3.RandomStringUtils; @@ -41,7 +42,7 @@ public class UserMapperIT { @Inject UserMapper userMapper; private User user; - private UserDTO userDto; + private AdminUserDTO userDto; @BeforeEach public void init() { @@ -57,7 +58,7 @@ public class UserMapperIT { user.setImageUrl("image_url"); user.setLangKey("en"); - userDto = new UserDTO(user); + userDto = new AdminUserDTO(user); } @Test @@ -74,7 +75,7 @@ public class UserMapperIT { @Test public void userDTOsToUsersShouldMapOnlyNonNullUsers() { - List usersDto = new ArrayList<>(); + List usersDto = new ArrayList<>(); usersDto.add(userDto); usersDto.add(null); @@ -90,7 +91,7 @@ public class UserMapperIT { authoritiesAsString.add("ADMIN"); userDto.setAuthorities(authoritiesAsString); - List usersDto = new ArrayList<>(); + List usersDto = new ArrayList<>(); usersDto.add(userDto); List users = userMapper.userDTOsToUsers(usersDto); @@ -106,7 +107,7 @@ public class UserMapperIT { public void userDTOsToUsersMapWithNullAuthoritiesStringShouldReturnUserWithEmptyAuthorities() { userDto.setAuthorities(null); - List usersDto = new ArrayList<>(); + List usersDto = new ArrayList<>(); usersDto.add(userDto); List users = userMapper.userDTOsToUsers(usersDto); diff --git a/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs index 83c1e6b5..4fbf1413 100644 --- a/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/AccountResourceIT.java.ejs @@ -16,7 +16,7 @@ import <%=packageName%>.service.MailService; <%_ } _%> import <%=packageName%>.service.UserService; import <%=packageName%>.service.dto.PasswordChangeDTO; -import <%=packageName%>.service.dto.UserDTO; +import <%=packageName%>.service.dto.AdminUserDTO; import <%=packageName%>.web.rest.vm.ManagedUserVM; import io.micronaut.context.annotation.Property; import io.micronaut.core.type.Argument; @@ -110,7 +110,7 @@ public class AccountResourceIT { user.setAuthorities(authorities); when(userService.getUserWithAuthorities()).thenReturn(Optional.of(user)); - UserDTO userDTO = client.retrieve(HttpRequest.GET("/api/account"), UserDTO.class).blockingFirst(); + AdminUserDTO userDTO = client.retrieve(HttpRequest.GET("/api/account"), AdminUserDTO.class).blockingFirst(); assertThat(userDTO.getLogin()).isEqualTo("test"); assertThat(userDTO.getFirstName()).isEqualTo("john"); @@ -254,7 +254,7 @@ public class AccountResourceIT { userRepository.saveAndFlush(user); - UserDTO userDTO = new UserDTO(); + AdminUserDTO userDTO = new AdminUserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); @@ -284,7 +284,7 @@ public class AccountResourceIT { userRepository.saveAndFlush(user); - UserDTO userDTO = new UserDTO(); + AdminUserDTO userDTO = new AdminUserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); @@ -321,7 +321,7 @@ public class AccountResourceIT { userRepository.saveAndFlush(anotherUser); - UserDTO userDTO = new UserDTO(); + AdminUserDTO userDTO = new AdminUserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); @@ -352,7 +352,7 @@ public class AccountResourceIT { userRepository.saveAndFlush(user); - UserDTO userDTO = new UserDTO(); + AdminUserDTO userDTO = new AdminUserDTO(); userDTO.setLogin("not-used"); userDTO.setFirstName("firstname"); userDTO.setLastName("lastname"); diff --git a/generators/server/templates/src/test/java/package/web/rest/UserResourceIT.java.ejs b/generators/server/templates/src/test/java/package/web/rest/UserResourceIT.java.ejs index 3c8a7493..a16a00f7 100644 --- a/generators/server/templates/src/test/java/package/web/rest/UserResourceIT.java.ejs +++ b/generators/server/templates/src/test/java/package/web/rest/UserResourceIT.java.ejs @@ -14,6 +14,7 @@ import <%=packageName%>.security.AuthoritiesConstants; <%_ if (authenticationType !== 'oauth2') { _%> import <%=packageName%>.service.MailService; <%_ } _%> +import <%=packageName%>.service.dto.AdminUserDTO; import <%=packageName%>.service.dto.UserDTO; import <%=packageName%>.service.mapper.UserMapper; import <%=packageName%>.web.rest.vm.ManagedUserVM; @@ -205,7 +206,7 @@ public class UserResourceIT { managedUserVM.setLangKey(DEFAULT_LANGKEY); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - HttpResponse response = client.exchange(HttpRequest.POST("/api/users", managedUserVM), User.class).blockingFirst(); + HttpResponse response = client.exchange(HttpRequest.POST("/api/admin/users", managedUserVM), User.class).blockingFirst(); assertThat(response.status().getCode()).isEqualTo(HttpStatus.CREATED.getCode()); @@ -238,7 +239,7 @@ public class UserResourceIT { managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // An entity with an existing ID cannot be created, so this API call must fail - HttpResponse response = client.exchange(HttpRequest.POST("/api/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); + HttpResponse response = client.exchange(HttpRequest.POST("/api/admin/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); assertThat(response.status().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.getCode()); @@ -263,7 +264,7 @@ public class UserResourceIT { managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Create the User - HttpResponse response = client.exchange(HttpRequest.POST("/api/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); + HttpResponse response = client.exchange(HttpRequest.POST("/api/admin/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); assertThat(response.status().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.getCode()); @@ -288,7 +289,7 @@ public class UserResourceIT { managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); // Create the User - HttpResponse response = client.exchange(HttpRequest.POST("/api/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); + HttpResponse response = client.exchange(HttpRequest.POST("/api/admin/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); assertThat(response.status().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.getCode()); @@ -301,7 +302,7 @@ public class UserResourceIT { @Test public void getAllUsers() throws Exception { // Get all the users - List users = client.retrieve(HttpRequest.GET("/api/users?sort=id,desc"), Argument.listOf(User.class)).blockingFirst(); + List users = client.retrieve(HttpRequest.GET("/api/admin/users?sort=id,desc"), Argument.listOf(User.class)).blockingFirst(); assertThat(users.get(0).getLogin()).isEqualTo(DEFAULT_LOGIN); assertThat(users.get(0).getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); @@ -318,7 +319,7 @@ public class UserResourceIT { <%_ } _%> // Get the user - User u = client.retrieve(HttpRequest.GET("/api/users/" + user.getLogin()), User.class).blockingFirst(); + User u = client.retrieve(HttpRequest.GET("/api/admin/users/" + user.getLogin()), User.class).blockingFirst(); assertThat(u.getLogin()).isEqualTo(user.getLogin()); assertThat(u.getFirstName()).isEqualTo(DEFAULT_FIRSTNAME); @@ -334,7 +335,7 @@ public class UserResourceIT { @Test public void getNonExistingUser() throws Exception { - HttpResponse response = client.exchange(HttpRequest.GET("/api/users/unknown"), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); + HttpResponse response = client.exchange(HttpRequest.GET("/api/admin/users/unknown"), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); assertThat(response.getStatus().getCode()).isEqualTo(HttpStatus.NOT_FOUND.getCode()); } @@ -360,7 +361,7 @@ public class UserResourceIT { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - HttpResponse response = client.exchange(HttpRequest.PUT("/api/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); + HttpResponse response = client.exchange(HttpRequest.PUT("/api/admin/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); assertThat(response.status().getCode()).isEqualTo(HttpStatus.OK.getCode()); @@ -398,7 +399,7 @@ public class UserResourceIT { managedUserVM.setLastModifiedDate(oldUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - HttpResponse response = client.exchange(HttpRequest.PUT("/api/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); + HttpResponse response = client.exchange(HttpRequest.PUT("/api/admin/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); assertThat(response.status().getCode()).isEqualTo(HttpStatus.OK.getCode()); @@ -446,7 +447,7 @@ public class UserResourceIT { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - HttpResponse response = client.exchange(HttpRequest.PUT("/api/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); + HttpResponse response = client.exchange(HttpRequest.PUT("/api/admin/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); assertThat(response.status().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.getCode()); @@ -484,7 +485,7 @@ public class UserResourceIT { managedUserVM.setLastModifiedDate(updatedUser.getLastModifiedDate()); managedUserVM.setAuthorities(Collections.singleton(AuthoritiesConstants.USER)); - HttpResponse response = client.exchange(HttpRequest.PUT("/api/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); + HttpResponse response = client.exchange(HttpRequest.PUT("/api/admin/users", managedUserVM), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); assertThat(response.status().getCode()).isEqualTo(HttpStatus.BAD_REQUEST.getCode()); @@ -498,7 +499,7 @@ public class UserResourceIT { // Delete the user - HttpResponse response = client.exchange(HttpRequest.DELETE("/api/users/" + user.getLogin()), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); + HttpResponse response = client.exchange(HttpRequest.DELETE("/api/admin/users/" + user.getLogin()), User.class).onErrorReturn(t -> (HttpResponse) ((HttpClientResponseException) t).getResponse()).blockingFirst(); assertThat(response.status().getCode()).isEqualTo(HttpStatus.NO_CONTENT.getCode()); <%_ if (usesCache) { _%> @@ -518,7 +519,7 @@ public class UserResourceIT { @Test public void getAllAuthorities() throws Exception { - HttpResponse> response = client.exchange(HttpRequest.GET("/api/users/authorities"), Argument.listOf(String.class)).onErrorReturn(t -> (HttpResponse>) ((HttpClientResponseException) t).getResponse()).blockingFirst(); + HttpResponse> response = client.exchange(HttpRequest.GET("/api/authorities"), Argument.listOf(String.class)).onErrorReturn(t -> (HttpResponse>) ((HttpClientResponseException) t).getResponse()).blockingFirst(); assertThat(response.status().getCode()).isEqualTo(HttpStatus.OK.getCode()); assertThat(response.body()).contains(AuthoritiesConstants.USER); @@ -552,7 +553,7 @@ public class UserResourceIT { @Test public void testUserDTOtoUser() { - UserDTO userDTO = new UserDTO(); + AdminUserDTO userDTO = new AdminUserDTO(); userDTO.setId(DEFAULT_ID); userDTO.setLogin(DEFAULT_LOGIN); userDTO.setFirstName(DEFAULT_FIRSTNAME); @@ -588,7 +589,7 @@ public class UserResourceIT { authorities.add(authority); user.setAuthorities(authorities); - UserDTO userDTO = userMapper.userToUserDTO(user); + AdminUserDTO userDTO = userMapper.userToAdminUserDTO(user); assertThat(userDTO.getId()).isEqualTo(DEFAULT_ID); assertThat(userDTO.getLogin()).isEqualTo(DEFAULT_LOGIN);