[SECARSP-111] +Auth API [SECARSP-115 +Get Devices]
[platform/core/security/suspicious-activity-monitor.git] / server / src / main / java / com / samsung / samserver / web / rest / UserResource.java
1 /*
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.
5  */
6 package com.samsung.samserver.web.rest;
7
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;
21
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.*;
31
32 import javax.validation.Valid;
33 import java.net.URI;
34 import java.net.URISyntaxException;
35 import java.util.*;
36
37 /**
38  * REST controller for managing users.
39  * <p>
40  * This class accesses the User entity, and needs to fetch its collection of authorities.
41  * <p>
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.
45  * <p>
46  * We use a View Model and a DTO for 3 reasons:
47  * <ul>
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>
57  * </ul>
58  * <p>
59  * Another option would be to have a specific JPA entity graph to handle this case.
60  */
61 @RestController
62 @RequestMapping("/api")
63 public class UserResource {
64
65     private final Logger log = LoggerFactory.getLogger(UserResource.class);
66
67     private final UserRepository userRepository;
68
69     private final UserService userService;
70
71     private final MailService mailService;
72
73     public UserResource(UserRepository userRepository, UserService userService, MailService mailService) {
74
75         this.userRepository = userRepository;
76         this.userService = userService;
77         this.mailService = mailService;
78     }
79
80     /**
81      * POST  /users  : Creates a new user.
82      * <p>
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.
86      *
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
91      */
92     @PostMapping("/users")
93     @Timed
94     @Secured(AuthoritiesConstants.ADMIN)
95     public ResponseEntity<User> createUser(@Valid @RequestBody UserDTO userDTO) throws URISyntaxException {
96         log.debug("REST request to save User : {}", userDTO);
97
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();
105         } else {
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()))
110                 .body(newUser);
111         }
112     }
113
114     /**
115      * PUT /users : Updates an existing User.
116      *
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
121      */
122     @PutMapping("/users")
123     @Timed
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();
130         }
131         existingUser = userRepository.findOneByLogin(userDTO.getLogin().toLowerCase());
132         if (existingUser.isPresent() && (!existingUser.get().getId().equals(userDTO.getId()))) {
133             throw new UserServiceError.LoginAlreadyUsedException();
134         }
135         Optional<UserDTO> updatedUser = userService.updateUser(userDTO);
136
137         return ResponseUtil.wrapOrNotFound(updatedUser,
138             HeaderUtil.createAlert("A user is updated with identifier " + userDTO.getLogin(), userDTO.getLogin()));
139     }
140
141     /**
142      * GET /users : get all users.
143      *
144      * @param pageable the pagination information
145      * @return the ResponseEntity with status 200 (OK) and with body all users
146      */
147     @GetMapping("/users")
148     @Timed
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);
153     }
154
155     /**
156      * @return a string list of the all of the roles
157      */
158     @GetMapping("/users/authorities")
159     @Timed
160     @Secured(AuthoritiesConstants.ADMIN)
161     public List<String> getAuthorities() {
162         return userService.getAuthorities();
163     }
164
165     /**
166      * GET /users/:login : get the "login" user.
167      *
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)
170      */
171     @GetMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
172     @Timed
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)
177                 .map(UserDTO::new));
178     }
179
180     /**
181      * DELETE /users/:login : delete the "login" User.
182      *
183      * @param login the login of the user to delete
184      * @return the ResponseEntity with status 200 (OK)
185      */
186     @DeleteMapping("/users/{login:" + Constants.LOGIN_REGEX + "}")
187     @Timed
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();
193     }
194 }