Skip to content

Commit

Permalink
Fixes jhipster#12374: backend changes - Use UserDTO for user manageme…
Browse files Browse the repository at this point in the history
…nt and PublicUserDTO for public consumptions
  • Loading branch information
gzsombor committed Nov 21, 2020
1 parent e60974d commit 85656a8
Show file tree
Hide file tree
Showing 7 changed files with 254 additions and 41 deletions.
8 changes: 8 additions & 0 deletions generators/server/files.js
Original file line number Diff line number Diff line change
Expand Up @@ -1635,6 +1635,10 @@ const serverFiles = {
file: 'package/service/dto/package-info.java',
renameTo: generator => `${generator.javaDir}service/dto/package-info.java`,
},
{
file: 'package/service/dto/PublicUserDTO.java',
renameTo: generator => `${generator.javaDir}service/dto/${generator.asDto('PublicUser')}.java`,
},
{
file: 'package/service/dto/UserDTO.java',
renameTo: generator => `${generator.javaDir}service/dto/${generator.asDto('User')}.java`,
Expand Down Expand Up @@ -1779,6 +1783,10 @@ const serverFiles = {
file: 'package/service/dto/UserDTO.java',
renameTo: generator => `${generator.javaDir}service/dto/${generator.asDto('User')}.java`,
},
{
file: 'package/service/dto/PublicUserDTO.java',
renameTo: generator => `${generator.javaDir}service/dto/${generator.asDto('PublicUser')}.java`,
},
{
file: 'package/service/dto/PasswordChangeDTO.java',
renameTo: generator => `${generator.javaDir}service/dto/PasswordChangeDTO.java`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,9 @@ public interface UserRepository extends <% if (databaseType === 'sql') { %>JpaRe
<%_ } _%>
<%_ if (authenticationType !== 'oauth2') { _%>

<% if (reactive) { %>Flux<% } else { %>List<% } %><<%= asEntity('User') %>> findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant dateTime);
<%= listOrFlux %><<%= asEntity('User') %>> findAllByActivatedIsFalseAndActivationKeyIsNotNullAndCreatedDateBefore(Instant dateTime);
<%_ } _%>

<%_ if (authenticationType !== 'oauth2') { _%>

<%= optionalOrMono %><<%= asEntity('User') %>> findOneByResetKey(String resetKey);
Expand Down Expand Up @@ -221,12 +222,17 @@ public interface UserRepository extends <% if (databaseType === 'sql') { %>JpaRe

<%_ } _%>
<%_ } _%>

<% if (reactive) { %>
Flux<<%= asEntity('User') %>>findAllByIdNotNull(Pageable pageable);

Flux<<%= asEntity('User') %>>findAllByIdNotNullAndActivatedIsTrue(Pageable pageable);

Mono<Long> count();
<% } else { %>
Page<<%= asEntity('User') %>>findAll(Pageable pageable);
Page<<%= asEntity('User') %>> findAll(Pageable pageable);

Page<<%= asEntity('User') %>> findAllByIdNotNullAndActivatedIsTrue(Pageable pageable);
<% } %>
}
<%_ } else if (databaseType === 'sql' && reactive) { _%>
Expand All @@ -247,6 +253,8 @@ public interface UserRepository extends R2dbcRepository<User, <% if (authenticat

Flux<User> findAllByIdNotNull(Pageable pageable);

Flux<User> findAllByIdNotNullAndActivatedIsTrue(Pageable pageable);

Mono<Long> count();

@Query("INSERT INTO <%= jhiTablePrefix %>_user_authority VALUES(:userId, :authority)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import <%= packageName %>.security.AuthoritiesConstants;
<%_ } _%>
import <%= packageName %>.security.SecurityUtils;
<%_ } _%>
import <%= packageName %>.service.dto.<%= asDto('PublicUser') %>;
import <%= packageName %>.service.dto.<%= asDto('User') %>;
<%_ if (authenticationType !== 'oauth2') { _%>

Expand Down Expand Up @@ -740,6 +741,14 @@ public class UserService {
public <% if (reactive) { %>Flux<% } else { %>Page<% } %><<%= asDto('User') %>> getAllManagedUsers(Pageable pageable) {
return userRepository.findAll<% if (reactive) { %>ByIdNotNull<% } %>(pageable).map(<%= asDto('User') %>::new);
}

<%_ if (databaseType === 'sql') { _%>
@Transactional(readOnly = true)
<%_ } _%>
public <% if (reactive) { %>Flux<% } else { %>Page<% } %><<%= asDto('PublicUser') %>> getAllPublicUsers(Pageable pageable) {
return userRepository.findAllByIdNotNullAndActivatedIsTrue(pageable).map(<%= asDto('PublicUser') %>::new);
}

<%_ if (reactive) { _%>

<%_ if (databaseType === 'sql') { _%>
Expand All @@ -755,6 +764,13 @@ public class UserService {
.map(<%= asDto('User') %>::new)<% if (!reactive) { %>
.collect(Collectors.toList())<% } %>;
}

public <% if (reactive) { %>Flux<% } else { %>List<% } %><<%= asDto('PublicUser') %>> getAllPublicUsers() {
return userRepository.findAll()<% if (!reactive) { %>.stream()<% } %>
.filter(user -> user.isActivated())
.map(<%= asDto('PublicUser') %>::new)<% if (!reactive) { %>
.collect(Collectors.toList())<% } %>;
}
<%_ } _%>

<%_ if (databaseType === 'sql') { _%>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<%#
Copyright 2013-2020 the original author or authors from the JHipster project.

This file is part of the JHipster project, see https://www.jhipster.tech/
for more information.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-%>
package <%= packageName %>.service.dto;

<%_
let userPk = (databaseType === 'mongodb' || databaseType === 'neo4j' || databaseType === 'couchbase' || databaseType === 'cassandra' || authenticationType === 'oauth2') ? "String" : "Long";
_%>
<%_ if (databaseType !== 'no') { _%>
import <%= packageName %>.domain.<%= asEntity('User') %>;
<%_ } _%>
/**
* A DTO representing a user, with all the public attributes.
*/
public class <%= asDto('PublicUser') %> {
private <%= userPk %> id;
private String login;
private String firstName;
private String lastName;
<%_ if (databaseType !== 'no') { _%>
public <%= asDto('PublicUser') %>() {
// Empty constructor needed for Jackson.
}
public <%= asDto('PublicUser') %>(User user) {
this.id = user.getId();
this.login = user.getLogin();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
}
<%_ } _%>
public <%= userPk %> getId() {
return id;
}
public void setId(<%= userPk %> 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;
}
// prettier-ignore
@Override
public String toString() {
return "<%= asDto('PublicUser') %>{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
"}";
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
-%>
package <%= packageName %>.service.dto;

<%_
let userPk = (databaseType === 'mongodb' || databaseType === 'neo4j' || databaseType === 'couchbase' || databaseType === 'cassandra' || authenticationType === 'oauth2') ? "String" : "Long";
_%>
import <%= packageName %>.config.Constants;
<% if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'neo4j') { %>
import <%= packageName %>.domain.Authority;<% } %>
Expand All @@ -39,7 +42,7 @@ import java.util.stream.Collectors;
*/
public class <%= asDto('User') %> {
private <% if (databaseType === 'mongodb' || databaseType === 'neo4j' || databaseType === 'couchbase' || databaseType === 'cassandra' || authenticationType === 'oauth2') { %>String<% } else { %>Long<% } %> id;
private <%= userPk %> id;
@NotBlank
@Pattern(regexp = Constants.LOGIN_REGEX)
Expand Down Expand Up @@ -110,11 +113,11 @@ public class <%= asDto('User') %> {
}
<%_ } _%>
public <% if (databaseType === 'mongodb' || databaseType === 'neo4j' || databaseType === 'couchbase' || databaseType === 'cassandra' || authenticationType === 'oauth2') { %>String<% } else { %>Long<% } %> getId() {
public <%= userPk %> getId() {
return id;
}
public void setId(<% if (databaseType === 'mongodb' || databaseType === 'neo4j' || databaseType === 'couchbase' || databaseType === 'cassandra' || authenticationType === 'oauth2') { %>String<% } else { %>Long<% } %> id) {
public void setId(<%= userPk %> id) {
this.id = id;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import org.springframework.data.domain.Sort;
import java.util.Collections;
<%_ } _%>
import <%= packageName %>.service.UserService;
import <%= packageName %>.service.dto.<%= asDto('PublicUser') %>;
import <%= packageName %>.service.dto.<%= asDto('User') %>;
<%_ if (authenticationType !== 'oauth2') { _%>
import <%= packageName %>.web.rest.errors.BadRequestAlertException;
Expand Down Expand Up @@ -163,7 +164,7 @@ public class UserResource {

<%_ if (authenticationType !== 'oauth2') { _%>
/**
* {@code POST /users} : Creates a new user.
* {@code POST /admin/users} : Creates a new user.
* <p>
* Creates a new user if the login and email are not already used, and sends an
* mail with an activation link.
Expand All @@ -176,7 +177,7 @@ public class UserResource {
<%_ } _%>
* @throws BadRequestAlertException {@code 400 (Bad Request)} if the login or email is already in use.
*/
@PostMapping("/users")
@PostMapping("/admin/users")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
public <% if (reactive) { %>Mono<ResponseEntity<<%= asEntity('User') %>>><% } else { %>ResponseEntity<<%= asEntity('User') %>><% } %> createUser(@Valid @RequestBody <%= asDto('User') %> userDTO)<% if (!reactive) { %> throws URISyntaxException<% } %> {
log.debug("REST request to save User : {}", userDTO);
Expand All @@ -192,7 +193,7 @@ public class UserResource {
} else {
<%= asEntity('User') %> newUser = userService.createUser(userDTO);
mailService.sendCreationEmail(newUser);
return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin()))
return ResponseEntity.created(new URI("/api/admin/users/" + newUser.getLogin()))
.headers(HeaderUtil.createAlert(applicationName, <% if (enableTranslation) { %> "userManagement.created"<% } else { %> "A user is created with identifier " + newUser.getLogin()<% } %>, newUser.getLogin()))
.body(newUser);
}
Expand All @@ -216,7 +217,7 @@ public class UserResource {
.doOnSuccess(mailService::sendCreationEmail)
.map(user -> {
try {
return ResponseEntity.created(new URI("/api/users/" + user.getLogin()))
return ResponseEntity.created(new URI("/api/admin/users/" + user.getLogin()))
.headers(HeaderUtil.createAlert(applicationName, "userManagement.created", user.getLogin()))
.body(user);
} catch (URISyntaxException e) {
Expand All @@ -227,14 +228,14 @@ public class UserResource {
}

/**
* {@code PUT /users} : Updates an existing User.
* {@code PUT /admin/users} : Updates an existing User.
*
* @param userDTO the user to update.
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated user.
* @throws EmailAlreadyUsedException {@code 400 (Bad Request)} if the email is already in use.
* @throws LoginAlreadyUsedException {@code 400 (Bad Request)} if the login is already in use.
*/
@PutMapping("/users")
@PutMapping("/admin/users")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
<%_ if (!reactive) { _%>
public ResponseEntity<<%= asDto('User') %>> updateUser(@Valid @RequestBody <%= asDto('User') %> userDTO) {
Expand Down Expand Up @@ -281,15 +282,16 @@ public class UserResource {

<%_ } _%>
/**
* {@code GET /users} : get all users.
* {@code GET /admin/users} : get all users with all the details - calling this are only allowed for the administrators.
*<% if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType == 'neo4j' || databaseType === 'couchbase') { %>
<%_ if (reactive) { _%>
* @param request a {@link ServerHttpRequest} request.
<%_ } _%>
* @param pageable the pagination information.<% } %>
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users.
*/
@GetMapping("/users")
@GetMapping("/admin/users")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
<%_ if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType === 'neo4j' || databaseType === 'couchbase') { _%>
<%_ if (!reactive) { _%>
public ResponseEntity<List<<%= asDto('User') %>>> getAllUsers(Pageable pageable) {
Expand Down Expand Up @@ -317,6 +319,44 @@ public class UserResource {
<%_ } _%>
}


/**
* {@code GET /users} : get all users with only the public informations - calling this are allowed for anyone.
*<% if (databaseType === 'sql' || databaseType === 'mongodb' || databaseType == 'neo4j' || databaseType === 'couchbase') { %>
<%_ if (reactive) { _%>
* @param request a {@link ServerHttpRequest} request.
<%_ } _%>
* @param pageable the pagination information.<% } %>
* @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body all users.
*/
@GetMapping("/users")
<%_ if (!reactive) { _%>
public ResponseEntity<List<<%= asDto('PublicUser') %>>> getAllPublicUsers(Pageable pageable) {
<%_ if (authenticationType !== 'oauth2') { _%>
if (!onlyContainsAllowedProperties(pageable)) {
return ResponseEntity.badRequest().build();
}
<%_ } _%>

final Page<<%= asDto('PublicUser') %>> page = userService.getAllPublicUsers(pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
}
<%_ } else { _%>
public Mono<ResponseEntity<Flux<<%= asDto('PublicUser') %>>>> getAllPublicUsers(ServerHttpRequest request, Pageable pageable) {
<%_ if (authenticationType !== 'oauth2') { _%>
if (!onlyContainsAllowedProperties(pageable)) {
return Mono.just(ResponseEntity.badRequest().build());
}
<%_ } _%>

return userService.countManagedUsers()
.map(total -> new PageImpl<>(new ArrayList<>(), pageable, total))
.map(page -> PaginationUtil.generatePaginationHttpHeaders(UriComponentsBuilder.fromHttpRequest(request), page))
.map(headers -> ResponseEntity.ok().headers(headers).body(userService.getAllManagedUsers(pageable)));
}
<%_ } _%>

<%_ if (authenticationType !== 'oauth2') { _%>
private boolean onlyContainsAllowedProperties(Pageable pageable) {
return pageable.getSort().stream().map(Sort.Order::getProperty).allMatch(ALLOWED_ORDERED_PROPERTIES::contains);
Expand All @@ -336,15 +376,21 @@ public class UserResource {
public <% if (reactive) { %>Flux<% } else { %>List<% } %><<%= asDto('User') %>> getAllUsers() {
return userService.getAllManagedUsers();
}

public <% if (reactive) { %>Flux<% } else { %>List<% } %><<%= asDto('PublicUser') %>> getAllPublicUsers() {
return userService.getAllPublicUsers();
}

<%_ } _%>

/**
* {@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 ResponseEntity} with status {@code 200 (OK)} and with body the "login" user, or with status {@code 404 (Not Found)}.
*/
@GetMapping("/users/{login}")
@GetMapping("/admin/users/{login}")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
<%_ if (!reactive) { _%>
public ResponseEntity<<%= asDto('User') %>> getUser(@PathVariable @Pattern(regexp = Constants.LOGIN_REGEX) String login) {
log.debug("REST request to get User : {}", login);
Expand All @@ -362,12 +408,12 @@ public class UserResource {
<%_ 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 ResponseEntity} with status {@code 204 (NO_CONTENT)}.
*/
@DeleteMapping("/users/{login}")
@DeleteMapping("/admin/users/{login}")
@PreAuthorize("hasAuthority(\"" + AuthoritiesConstants.ADMIN + "\")")
<%_ if (!reactive) { _%>
public ResponseEntity<Void> deleteUser(@PathVariable @Pattern(regexp = Constants.LOGIN_REGEX) String login) {
Expand Down
Loading

0 comments on commit 85656a8

Please sign in to comment.