2 * In Samsung Ukraine R&D Center (SRK under a contract between)
3 * LLC "Samsung Electronics Co", Ltd (Seoul, Republic of Korea)
4 * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved.
6 package com.samsung.samserver.web.rest;
8 import com.codahale.metrics.annotation.Timed;
9 import com.samsung.samserver.config.Constants;
10 import com.samsung.samserver.domain.User;
11 import com.samsung.samserver.repository.UserRepository;
12 import com.samsung.samserver.security.AuthoritiesConstants;
13 import com.samsung.samserver.service.impl.MailService;
14 import com.samsung.samserver.service.impl.UserService;
15 import com.samsung.samserver.service.dto.UserDTO;
16 import com.samsung.samserver.web.rest.errors.BadRequestAlertException;
17 import com.samsung.samserver.web.rest.errors.UserServiceError;
18 import com.samsung.samserver.web.rest.util.HeaderUtil;
19 import com.samsung.samserver.web.rest.util.PaginationUtil;
20 import io.github.jhipster.web.util.ResponseUtil;
22 import org.slf4j.Logger;
23 import org.slf4j.LoggerFactory;
24 import org.springframework.data.domain.Page;
25 import org.springframework.data.domain.Pageable;
26 import org.springframework.http.HttpHeaders;
27 import org.springframework.http.HttpStatus;
28 import org.springframework.http.ResponseEntity;
29 import org.springframework.security.access.annotation.Secured;
30 import org.springframework.web.bind.annotation.*;
32 import javax.validation.Valid;
34 import java.net.URISyntaxException;
38 * REST controller for managing users.
40 * This class accesses the User entity, and needs to fetch its collection of authorities.
42 * For a normal use-case, it would be better to have an eager relationship between User and Authority,
43 * and send everything to the client side: there would be no View Model and DTO, a lot less code, and an outer-join
44 * which would be good for performance.
46 * We use a View Model and a DTO for 3 reasons:
48 * <li>We want to keep a lazy association between the user and the authorities, because people will
49 * quite often do relationships with the user, and we don't want them to get the authorities all
50 * the time for nothing (for performance reasons). This is the #1 goal: we should not impact our users'
51 * application because of this use-case.</li>
52 * <li> Not having an outer join causes n+1 requests to the database. This is not a real issue as
53 * we have by default a second-level cache. This means on the first HTTP call we do the n+1 requests,
54 * but then all authorities come from the cache, so in fact it's much better than doing an outer join
55 * (which will get lots of data from the database, for each HTTP call).</li>
56 * <li> As this manages users, for security reasons, we'd rather have a DTO layer.</li>
59 * Another option would be to have a specific JPA entity graph to handle this case.
62 @RequestMapping("/api")
63 public class UserResource {
65 private final Logger log = LoggerFactory.getLogger(UserResource.class);
67 private final UserRepository userRepository;
69 private final UserService userService;
71 private final MailService mailService;
73 public UserResource(UserRepository userRepository, UserService userService, MailService mailService) {
75 this.userRepository = userRepository;
76 this.userService = userService;
77 this.mailService = mailService;
81 * POST /users : Creates a new user.
83 * Creates a new user if the login and email are not already used, and sends an
84 * mail with an activation link.
85 * The user needs to be activated on creation.
87 * @param userDTO the user to create
88 * @return the ResponseEntity with status 201 (Created) and with body the new user, or with status 400 (Bad Request) if the login or email is already in use
89 * @throws URISyntaxException if the Location URI syntax is incorrect
90 * @throws BadRequestAlertException 400 (Bad Request) if the login or email is already in use
92 @PostMapping("/users")
94 @Secured(AuthoritiesConstants.ADMIN)
95 public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) throws URISyntaxException {
96 log.debug("REST request to save User : {}", userDTO);
98 if (userDTO.getId() != null) {
99 throw new BadRequestAlertException("A new user cannot already have an ID", "userManagement", "idexists");
100 // Lowercase the user login before comparing with database
101 } else if (userRepository.findOneByLogin(userDTO.getLogin().toLowerCase()).isPresent()) {
102 throw new UserServiceError.LoginAlreadyUsedException();
103 } else if (userRepository.findOneByEmailIgnoreCase(userDTO.getEmail()).isPresent()) {
104 throw new UserServiceError.EmailAlreadyUsedException();
106 User newUser = userService.createUser(userDTO);
107 mailService.sendCreationEmail(newUser);
108 return ResponseEntity.created(new URI("/api/users/" + newUser.getLogin()))
109 .headers(HeaderUtil.createAlert( "A user is created with identifier " + newUser.getLogin(), newUser.getLogin()))
115 * PUT /users : Updates an existing User.
117 * @param userDTO the user to update
118 * @return the ResponseEntity with status 200 (OK) and with body the updated user
119 * @throws UserServiceError.EmailAlreadyUsedException 400 (Bad Request) if the email is already in use
120 * @throws UserServiceError.LoginAlreadyUsedException 400 (Bad Request) if the login is already in use
122 @PutMapping("/users")
124 @Secured(AuthoritiesConstants.ADMIN)
125 public ResponseEntity<UserDTO> updateUser(@Valid @RequestBody UserDTO userDTO) {
126 log.debug("REST request to update User : {}", userDTO);
127 Optional<User> existingUser = userRepository.findOneByEmailIgnoreCase(userDTO.getEmail());
128 if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) {
129 throw new UserServiceError.EmailAlreadyUsedException();
131 existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase());
132 if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) {
133 throw new UserServiceError.LoginAlreadyUsedException();
135 Optional<UserDTO> updatedUser = userService.updateUser(userDTO);
137 return ResponseUtil.wrapOrNotFound(updatedUser,
138 HeaderUtil.createAlert("A user is updated with identifier " + userDTO.getLogin(), userDTO.getLogin()));
142 * GET /users : get all users.
144 * @param pageable the pagination information
145 * @return the ResponseEntity with status 200 (OK) and with body all users
147 @GetMapping("/users")
149 public ResponseEntity<List<UserDTO>> getAllUsers(Pageable pageable) {
150 final Page<UserDTO> page = userService.getAllManagedUsers(pageable);
151 HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/users");
152 return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
156 * @return a string list of the all of the roles
158 @GetMapping("/users/authorities")
160 @Secured(AuthoritiesConstants.ADMIN)
161 public List<String> getAuthorities() {
162 return userService.getAuthorities();
166 * GET /users/:login : get the "login" user.
168 * @param login the login of the user to find
169 * @return the ResponseEntity with status 200 (OK) and with body the "login" user, or with status 404 (Not Found)
171 @GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
173 public ResponseEntity<UserDTO> getUser(@PathVariable String login) {
174 log.debug("REST request to get User : {}", login);
175 return ResponseUtil.wrapOrNotFound(
176 userService.getUserWithAuthoritiesByLogin(login)
181 * DELETE /users/:login : delete the "login" User.
183 * @param login the login of the user to delete
184 * @return the ResponseEntity with status 200 (OK)
186 @DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
188 @Secured(AuthoritiesConstants.ADMIN)
189 public ResponseEntity<Void> deleteUser(@PathVariable String login) {
190 log.debug("REST request to delete User: {}", login);
191 userService.deleteUser(login);
192 return ResponseEntity.ok().headers(HeaderUtil.createAlert( "A user is deleted with identifier " + login, login)).build();