UserProfileController.java

  1. /*
  2.  * Copyright 2022 Global Crop Diversity Trust
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *   http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16. package org.genesys.server.api.admin.v1;

  17. import java.util.List;
  18. import java.util.Set;
  19. import java.util.UUID;

  20. import org.apache.commons.lang3.StringUtils;
  21. import org.genesys.blocks.security.UserException;
  22. import org.genesys.server.api.ApiBaseController;
  23. import org.genesys.server.exception.InvalidApiUsageException;
  24. import org.genesys.server.exception.NotFoundElement;
  25. import org.genesys.server.model.UserRole;
  26. import org.genesys.server.model.impl.User;
  27. import org.genesys.server.mvc.BaseController;
  28. import org.genesys.server.service.EMailVerificationService;
  29. import org.genesys.server.service.TokenVerificationService.NoSuchVerificationTokenException;
  30. import org.genesys.server.service.TokenVerificationService.TokenExpiredException;
  31. import org.genesys.server.service.UserService;
  32. import org.springframework.beans.factory.annotation.Autowired;
  33. import org.springframework.data.domain.Page;
  34. import org.springframework.data.domain.PageRequest;
  35. import org.springframework.data.domain.Sort;
  36. import org.springframework.http.MediaType;
  37. import org.springframework.security.access.prepost.PreAuthorize;
  38. import org.springframework.web.bind.annotation.DeleteMapping;
  39. import org.springframework.web.bind.annotation.GetMapping;
  40. import org.springframework.web.bind.annotation.PathVariable;
  41. import org.springframework.web.bind.annotation.PostMapping;
  42. import org.springframework.web.bind.annotation.RequestBody;
  43. import org.springframework.web.bind.annotation.RequestMapping;
  44. import org.springframework.web.bind.annotation.RequestParam;
  45. import org.springframework.web.bind.annotation.RestController;

  46. @RestController("adminUsersControllerV1")
  47. @RequestMapping(UserProfileController.CONTROLLER_URL)
  48. @PreAuthorize("hasRole('ADMINISTRATOR')")
  49. public class UserProfileController extends BaseController {

  50.     /** The Constant CONTROLLER_URL. */
  51.     public static final String CONTROLLER_URL = ApiBaseController.APIv1_BASE + "/admin/users/";

  52.     @Autowired
  53.     private UserService userService;

  54.     @Autowired
  55.     private EMailVerificationService emailVerificationService;

  56.     @GetMapping(value = "", produces = { MediaType.APPLICATION_JSON_VALUE })
  57.     public Page<User> list(@RequestParam(value = "page", defaultValue = "1") int page) {
  58.         return userService.listUsers(PageRequest.of(page - 1, 50, Sort.by("fullName")));
  59.     }

  60.     @PostMapping("/{uuid:.+}/vetted-user")
  61.     public void addRoleVettedUser(@PathVariable("uuid") UUID uuid) {
  62.         userService.addVettedUserRole(uuid);
  63.     }

  64.     @GetMapping(value = "/{uuid:.+}", produces = { MediaType.APPLICATION_JSON_VALUE })
  65.     public User someProfile(@PathVariable("uuid") UUID uuid) {
  66.         final User user = userService.getUser(uuid);
  67.         if (user == null) {
  68.             throw new NotFoundElement();
  69.         }

  70.         return user;
  71.     }

  72.     @GetMapping(value = "/roles", produces = { MediaType.APPLICATION_JSON_VALUE })
  73.     public List<UserRole> getAvailableRoles() {

  74.         return userService.listAvailableRoles();
  75.     }

  76.     @PostMapping(value = "/{uuid}/send")
  77.     public void sendEmail(@PathVariable("uuid") UUID uuid) {
  78.         final User user = userService.getUser(uuid);
  79.         emailVerificationService.sendVerificationEmail(user);
  80.     }

  81.     @PostMapping(value = "/{tokenUuid:.+}/cancel")
  82.     public void cancelValidation(@PathVariable("tokenUuid") String tokenUuid) throws Exception {
  83.         emailVerificationService.cancelValidation(tokenUuid);
  84.     }

  85.     @PostMapping(value = "/{tokenUuid:.+}/validate")
  86.     public void validateEmail2(@PathVariable("tokenUuid") String tokenUuid, @RequestParam(value = "key", required = true) String key) throws NoSuchVerificationTokenException, TokenExpiredException {
  87.         emailVerificationService.validateEMail(tokenUuid, key);
  88.     }

  89.     @PostMapping(value = "/password/reset")
  90.     public void resetPassword(@RequestParam("email") String email) {
  91.         final User user = userService.getUserByEmail(email);

  92.         if (user != null) {
  93.             emailVerificationService.sendPasswordResetEmail(user);
  94.         }
  95.     }

  96.     @PostMapping(value = "/{tokenUuid:.+}/pwdreset")
  97.     public void updatePassword(@PathVariable("tokenUuid") String tokenUuid, @RequestParam(value = "key") String key, @RequestParam("password") String password)
  98.             throws UserException, NoSuchVerificationTokenException, TokenExpiredException {
  99.         emailVerificationService.changePassword(tokenUuid, key, password);
  100.     }

  101.     @PostMapping(value = "/{uuid:.+}/update")
  102.     public void update(@PathVariable("uuid") final UUID uuid, @RequestBody User updatedUser, @RequestParam("pwd1") String pwd1) throws UserException {
  103.         final User user = userService.getUser(UUID.fromString(updatedUser.getUuid()));
  104.         if (user == null) {
  105.             throw new NotFoundElement();
  106.         }

  107.         userService.updateUser(user, updatedUser.getEmail(), updatedUser.getFullName());

  108.         if (StringUtils.isNotBlank(pwd1)) {
  109.             if (pwd1.equals(updatedUser.getPassword())) {
  110.                 LOG.info("Updating password for {}", user);
  111.                 userService.changePassword(user, updatedUser.getPassword());
  112.                 LOG.warn("Password updated for {}", user);
  113.             }
  114.         }
  115.     }

  116.     @DeleteMapping(value = "/{uuid:.+}")
  117.     public void delete(@PathVariable("uuid") UUID uuid) throws UserException {
  118.         final User user = userService.getUser(uuid);

  119.         if (user==null) {
  120.             throw new NotFoundElement();
  121.         }

  122.         if (! user.isAccountNonExpired()) {
  123.             throw new InvalidApiUsageException("User is already expired");
  124.         }

  125.         LOG.warn("Archiving user account {}", user.getEmail());
  126.         userService.archiveUser(user);

  127.     }

  128.     @PostMapping(value = "/{uuid:.+}/update-roles")
  129.     public void updateRoles(@PathVariable("uuid") UUID uuid, @RequestParam("role") Set<UserRole> selectedRoles) {
  130.         final User user = userService.getUser(uuid);
  131.         if (user == null) {
  132.             throw new NotFoundElement();
  133.         }

  134.         userService.setRoles(user, selectedRoles);
  135.     }

  136. }