chavdardim1990

Phone

Feb 24th, 2022
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. @Override
  2. public void update(User userToBeAuthorized, int userId, User userToBeUpdated,
  3. Optional<String> phoneFromUser, int newUserRole) {
  4.  
  5. boolean sameUser = userToBeAuthorized.getUserId() == userId;
  6. boolean loggedUserIsAdmin = userToBeAuthorized.getUserType().getUserRole().equalsIgnoreCase("admin");
  7. boolean sameOrLowerRole = newUserRole <= userToBeAuthorized.getUserType().getUserTypeId();
  8.  
  9. boolean duplicateExists = true;
  10. boolean sameUserInDB = false;
  11.  
  12. try {
  13. User existingUser = repository.getByEmail(userToBeUpdated.getEmail());
  14. if (existingUser.getUserId() == userToBeUpdated.getUserId()) {
  15. duplicateExists = false;
  16. sameUserInDB = true;
  17. }
  18. } catch (EntityNotFoundException e) {
  19. duplicateExists = false;
  20. }
  21. if (duplicateExists) {
  22. throw new DuplicateEntityException("User", "email", userToBeUpdated.getEmail());
  23. }
  24.  
  25. if (!sameUserInDB){
  26. throw new UnauthorizedOperationException(UPDATE_USER_ERROR_MESSAGE);
  27. }
  28.  
  29. /*Update USER || ADMIN*/
  30. if (sameUser && sameOrLowerRole){
  31. repository.update(userToBeUpdated);
  32. }
  33.  
  34. /*Promote user*/
  35. if(loggedUserIsAdmin && !sameUser && newUserRole == 3){
  36. repository.update(userToBeUpdated);
  37. }
  38.  
  39. Optional<Phone> existingPhone = phoneService.getByUserId(userId);
  40.  
  41. /*Admin can add or change its phone*/
  42. if (phoneFromUser.isPresent() && sameUser && loggedUserIsAdmin && newUserRole == 3){
  43. Phone phoneToBe = new Phone();
  44. phoneToBe.setPhone(phoneFromUser.get());
  45. phoneToBe.setUser(userId);
  46. if (existingPhone.isPresent()){
  47. phoneService.update(phoneToBe);
  48. if (phoneFromUser.get().equals(existingPhone.get().getPhone())){
  49. throw new DuplicateEntityException("Phone", "phoneNumber", phoneFromUser.get());
  50. }
  51. }
  52. else{
  53. phoneService.create(phoneToBe);
  54. }
  55. }
  56.  
  57. /*Admin can demote and phone should be deleted*/
  58. if (sameUser && loggedUserIsAdmin && newUserRole ==1 && existingPhone.isPresent()){
  59. phoneService.delete(existingPhone.get());
  60. }
  61. }
Advertisement
Add Comment
Please, Sign In to add comment