Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Override
- public void update(User userToBeAuthorized, int userId, User userToBeUpdated,
- Optional<String> phoneFromUser, int newUserRole) {
- boolean sameUser = userToBeAuthorized.getUserId() == userId;
- boolean loggedUserIsAdmin = userToBeAuthorized.getUserType().getUserRole().equalsIgnoreCase("admin");
- boolean sameOrLowerRole = newUserRole <= userToBeAuthorized.getUserType().getUserTypeId();
- boolean duplicateExists = true;
- boolean sameUserInDB = false;
- try {
- User existingUser = repository.getByEmail(userToBeUpdated.getEmail());
- if (existingUser.getUserId() == userToBeUpdated.getUserId()) {
- duplicateExists = false;
- sameUserInDB = true;
- }
- } catch (EntityNotFoundException e) {
- duplicateExists = false;
- }
- if (duplicateExists) {
- throw new DuplicateEntityException("User", "email", userToBeUpdated.getEmail());
- }
- if (!sameUserInDB){
- throw new UnauthorizedOperationException(UPDATE_USER_ERROR_MESSAGE);
- }
- /*Update USER || ADMIN*/
- if (sameUser && sameOrLowerRole){
- repository.update(userToBeUpdated);
- }
- /*Promote user*/
- if(loggedUserIsAdmin && !sameUser && newUserRole == 3){
- repository.update(userToBeUpdated);
- }
- Optional<Phone> existingPhone = phoneService.getByUserId(userId);
- /*Admin can add or change its phone*/
- if (phoneFromUser.isPresent() && sameUser && loggedUserIsAdmin && newUserRole == 3){
- Phone phoneToBe = new Phone();
- phoneToBe.setPhone(phoneFromUser.get());
- phoneToBe.setUser(userId);
- if (existingPhone.isPresent()){
- phoneService.update(phoneToBe);
- if (phoneFromUser.get().equals(existingPhone.get().getPhone())){
- throw new DuplicateEntityException("Phone", "phoneNumber", phoneFromUser.get());
- }
- }
- else{
- phoneService.create(phoneToBe);
- }
- }
- /*Admin can demote and phone should be deleted*/
- if (sameUser && loggedUserIsAdmin && newUserRole ==1 && existingPhone.isPresent()){
- phoneService.delete(existingPhone.get());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment