PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/jhipster3/monolithic/src/main/java/com/arkix/monolithic/web/rest/AccountResource.java

https://gitlab.com/cortizqgitlab/test-first
Java | 275 lines | 177 code | 23 blank | 75 comment | 4 complexity | 89d89f0106839d0218d4a3c998e02baa MD5 | raw file
  1. package com.arkix.monolithic.web.rest;
  2. import com.codahale.metrics.annotation.Timed;
  3. import com.arkix.monolithic.domain.Authority;
  4. import com.arkix.monolithic.domain.PersistentToken;
  5. import com.arkix.monolithic.domain.User;
  6. import com.arkix.monolithic.repository.PersistentTokenRepository;
  7. import com.arkix.monolithic.repository.UserRepository;
  8. import com.arkix.monolithic.security.SecurityUtils;
  9. import com.arkix.monolithic.service.MailService;
  10. import com.arkix.monolithic.service.UserService;
  11. import com.arkix.monolithic.web.rest.dto.KeyAndPasswordDTO;
  12. import com.arkix.monolithic.web.rest.dto.UserDTO;
  13. import com.arkix.monolithic.web.rest.util.HeaderUtil;
  14. import org.apache.commons.lang.StringUtils;
  15. import org.slf4j.Logger;
  16. import org.slf4j.LoggerFactory;
  17. import org.springframework.http.HttpHeaders;
  18. import org.springframework.http.HttpStatus;
  19. import org.springframework.http.MediaType;
  20. import org.springframework.http.ResponseEntity;
  21. import org.springframework.web.bind.annotation.*;
  22. import javax.inject.Inject;
  23. import javax.servlet.http.HttpServletRequest;
  24. import javax.validation.Valid;
  25. import java.io.UnsupportedEncodingException;
  26. import java.net.URLDecoder;
  27. import java.util.*;
  28. /**
  29. * REST controller for managing the current user's account.
  30. */
  31. @RestController
  32. @RequestMapping("/api")
  33. public class AccountResource {
  34. private final Logger log = LoggerFactory.getLogger(AccountResource.class);
  35. @Inject
  36. private UserRepository userRepository;
  37. @Inject
  38. private UserService userService;
  39. @Inject
  40. private PersistentTokenRepository persistentTokenRepository;
  41. @Inject
  42. private MailService mailService;
  43. /**
  44. * POST /register : register the user.
  45. *
  46. * @param userDTO the user DTO
  47. * @param request the HTTP request
  48. * @return the ResponseEntity with status 201 (Created) if the user is registred or 400 (Bad Request) if the login or e-mail is already in use
  49. */
  50. @RequestMapping(value = "/register",
  51. method = RequestMethod.POST,
  52. produces={MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE})
  53. @Timed
  54. public ResponseEntity<?> registerAccount(@Valid @RequestBody UserDTO userDTO, HttpServletRequest request) {
  55. HttpHeaders textPlainHeaders = new HttpHeaders();
  56. textPlainHeaders.setContentType(MediaType.TEXT_PLAIN);
  57. return userRepository.findOneByLogin(userDTO.getLogin())
  58. .map(user -> new ResponseEntity<>("login already in use", textPlainHeaders, HttpStatus.BAD_REQUEST))
  59. .orElseGet(() -> userRepository.findOneByEmail(userDTO.getEmail())
  60. .map(user -> new ResponseEntity<>("e-mail address already in use", textPlainHeaders, HttpStatus.BAD_REQUEST))
  61. .orElseGet(() -> {
  62. User user = userService.createUserInformation(userDTO.getLogin(), userDTO.getPassword(),
  63. userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail().toLowerCase(),
  64. userDTO.getLangKey());
  65. String baseUrl = request.getScheme() + // "http"
  66. "://" + // "://"
  67. request.getServerName() + // "myhost"
  68. ":" + // ":"
  69. request.getServerPort() + // "80"
  70. request.getContextPath(); // "/myContextPath" or "" if deployed in root context
  71. mailService.sendActivationEmail(user, baseUrl);
  72. return new ResponseEntity<>(HttpStatus.CREATED);
  73. })
  74. );
  75. }
  76. /**
  77. * GET /activate : activate the registered user.
  78. *
  79. * @param key the activation key
  80. * @return the ResponseEntity with status 200 (OK) and the activated user in body, or status 500 (Internal Server Error) if the user couldn't be activated
  81. */
  82. @RequestMapping(value = "/activate",
  83. method = RequestMethod.GET,
  84. produces = MediaType.APPLICATION_JSON_VALUE)
  85. @Timed
  86. public ResponseEntity<String> activateAccount(@RequestParam(value = "key") String key) {
  87. return userService.activateRegistration(key)
  88. .map(user -> new ResponseEntity<String>(HttpStatus.OK))
  89. .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
  90. }
  91. /**
  92. * GET /authenticate : check if the user is authenticated, and return its login.
  93. *
  94. * @param request the HTTP request
  95. * @return the login if the user is authenticated
  96. */
  97. @RequestMapping(value = "/authenticate",
  98. method = RequestMethod.GET,
  99. produces = MediaType.APPLICATION_JSON_VALUE)
  100. @Timed
  101. public String isAuthenticated(HttpServletRequest request) {
  102. log.debug("REST request to check if the current user is authenticated");
  103. return request.getRemoteUser();
  104. }
  105. /**
  106. * GET /account : get the current user.
  107. *
  108. * @return the ResponseEntity with status 200 (OK) and the current user in body, or status 500 (Internal Server Error) if the user couldn't be returned
  109. */
  110. @RequestMapping(value = "/account",
  111. method = RequestMethod.GET,
  112. produces = MediaType.APPLICATION_JSON_VALUE)
  113. @Timed
  114. public ResponseEntity<UserDTO> getAccount() {
  115. return Optional.ofNullable(userService.getUserWithAuthorities())
  116. .map(user -> new ResponseEntity<>(new UserDTO(user), HttpStatus.OK))
  117. .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
  118. }
  119. /**
  120. * POST /account : update the current user information.
  121. *
  122. * @param userDTO the current user information
  123. * @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) or 500 (Internal Server Error) if the user couldn't be updated
  124. */
  125. @RequestMapping(value = "/account",
  126. method = RequestMethod.POST,
  127. produces = MediaType.APPLICATION_JSON_VALUE)
  128. @Timed
  129. public ResponseEntity<String> saveAccount(@RequestBody UserDTO userDTO) {
  130. Optional<User> existingUser = userRepository.findOneByEmail(userDTO.getEmail());
  131. if (existingUser.isPresent() && (!existingUser.get().getLogin().equalsIgnoreCase(userDTO.getLogin()))) {
  132. return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert("user-management", "emailexists", "Email already in use")).body(null);
  133. }
  134. return userRepository
  135. .findOneByLogin(SecurityUtils.getCurrentUserLogin())
  136. .map(u -> {
  137. userService.updateUserInformation(userDTO.getFirstName(), userDTO.getLastName(), userDTO.getEmail(),
  138. userDTO.getLangKey());
  139. return new ResponseEntity<String>(HttpStatus.OK);
  140. })
  141. .orElseGet(() -> new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
  142. }
  143. /**
  144. * POST /account/change_password : changes the current user's password
  145. *
  146. * @param password the new password
  147. * @return the ResponseEntity with status 200 (OK), or status 400 (Bad Request) if the new password is not strong enough
  148. */
  149. @RequestMapping(value = "/account/change_password",
  150. method = RequestMethod.POST,
  151. produces = MediaType.TEXT_PLAIN_VALUE)
  152. @Timed
  153. public ResponseEntity<?> changePassword(@RequestBody String password) {
  154. if (!checkPasswordLength(password)) {
  155. return new ResponseEntity<>("Incorrect password", HttpStatus.BAD_REQUEST);
  156. }
  157. userService.changePassword(password);
  158. return new ResponseEntity<>(HttpStatus.OK);
  159. }
  160. /**
  161. * GET /account/sessions : get the current open sessions.
  162. *
  163. * @return the ResponseEntity with status 200 (OK) and the current open sessions in body,
  164. * or status 500 (Internal Server Error) if the current open sessions couldn't be retrieved
  165. */
  166. @RequestMapping(value = "/account/sessions",
  167. method = RequestMethod.GET,
  168. produces = MediaType.APPLICATION_JSON_VALUE)
  169. @Timed
  170. public ResponseEntity<List<PersistentToken>> getCurrentSessions() {
  171. return userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin())
  172. .map(user -> new ResponseEntity<>(
  173. persistentTokenRepository.findByUser(user),
  174. HttpStatus.OK))
  175. .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
  176. }
  177. /**
  178. * DELETE /account/sessions?series={series} : invalidate an existing session.
  179. *
  180. * - You can only delete your own sessions, not any other user's session
  181. * - If you delete one of your existing sessions, and that you are currently logged in on that session, you will
  182. * still be able to use that session, until you quit your browser: it does not work in real time (there is
  183. * no API for that), it only removes the "remember me" cookie
  184. * - This is also true if you invalidate your current session: you will still be able to use it until you close
  185. * your browser or that the session times out. But automatic login (the "remember me" cookie) will not work
  186. * anymore.
  187. * There is an API to invalidate the current session, but there is no API to check which session uses which
  188. * cookie.
  189. *
  190. * @param series the series of an existing session
  191. * @throws UnsupportedEncodingException if the series couldnt be URL decoded
  192. */
  193. @RequestMapping(value = "/account/sessions/{series}",
  194. method = RequestMethod.DELETE)
  195. @Timed
  196. public void invalidateSession(@PathVariable String series) throws UnsupportedEncodingException {
  197. String decodedSeries = URLDecoder.decode(series, "UTF-8");
  198. userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(u -> {
  199. persistentTokenRepository.findByUser(u).stream()
  200. .filter(persistentToken -> StringUtils.equals(persistentToken.getSeries(), decodedSeries))
  201. .findAny().ifPresent(t -> persistentTokenRepository.delete(decodedSeries));
  202. });
  203. }
  204. /**
  205. * POST /account/reset_password/init : Send an e-mail to reset the password of the user
  206. *
  207. * @param mail the mail of the user
  208. * @param request the HTTP request
  209. * @return the ResponseEntity with status 200 (OK) if the e-mail was sent, or status 400 (Bad Request) if the e-mail address is not registred
  210. */
  211. @RequestMapping(value = "/account/reset_password/init",
  212. method = RequestMethod.POST,
  213. produces = MediaType.TEXT_PLAIN_VALUE)
  214. @Timed
  215. public ResponseEntity<?> requestPasswordReset(@RequestBody String mail, HttpServletRequest request) {
  216. return userService.requestPasswordReset(mail)
  217. .map(user -> {
  218. String baseUrl = request.getScheme() +
  219. "://" +
  220. request.getServerName() +
  221. ":" +
  222. request.getServerPort() +
  223. request.getContextPath();
  224. mailService.sendPasswordResetMail(user, baseUrl);
  225. return new ResponseEntity<>("e-mail was sent", HttpStatus.OK);
  226. }).orElse(new ResponseEntity<>("e-mail address not registered", HttpStatus.BAD_REQUEST));
  227. }
  228. /**
  229. * POST /account/reset_password/finish : Finish to reset the password of the user
  230. *
  231. * @param keyAndPassword the generated key and the new password
  232. * @return the ResponseEntity with status 200 (OK) if the password has been reset,
  233. * or status 400 (Bad Request) or 500 (Internal Server Error) if the password could not be reset
  234. */
  235. @RequestMapping(value = "/account/reset_password/finish",
  236. method = RequestMethod.POST,
  237. produces = MediaType.TEXT_PLAIN_VALUE)
  238. @Timed
  239. public ResponseEntity<String> finishPasswordReset(@RequestBody KeyAndPasswordDTO keyAndPassword) {
  240. if (!checkPasswordLength(keyAndPassword.getNewPassword())) {
  241. return new ResponseEntity<>("Incorrect password", HttpStatus.BAD_REQUEST);
  242. }
  243. return userService.completePasswordReset(keyAndPassword.getNewPassword(), keyAndPassword.getKey())
  244. .map(user -> new ResponseEntity<String>(HttpStatus.OK))
  245. .orElse(new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR));
  246. }
  247. private boolean checkPasswordLength(String password) {
  248. return (!StringUtils.isEmpty(password) &&
  249. password.length() >= UserDTO.PASSWORD_MIN_LENGTH &&
  250. password.length() <= UserDTO.PASSWORD_MAX_LENGTH);
  251. }
  252. }