Advertisement
Guest User

Untitled

a guest
Mar 30th, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.59 KB | None | 0 0
  1. package com.sombrainc.service.implementation;
  2.  
  3. import com.google.common.base.Strings;
  4. import com.sombrainc.dto.common.RestMessageDTO;
  5. import com.sombrainc.dto.regular.*;
  6. import com.sombrainc.entity.Client;
  7. import com.sombrainc.entity.regular.User;
  8. import com.sombrainc.enums.ActivationEnum;
  9. import com.sombrainc.enums.RoleEnum;
  10. import com.sombrainc.exception.EntityNotFulfilledException;
  11. import com.sombrainc.exception.GeneralServiceException;
  12. import com.sombrainc.repository.ClientRepository;
  13. import com.sombrainc.repository.RecruiterRepository;
  14. import com.sombrainc.repository.regular.CountryRepository;
  15. import com.sombrainc.repository.regular.UserRepository;
  16. import com.sombrainc.service.EmailService;
  17. import com.sombrainc.service.UserService;
  18. import com.sombrainc.util.ActivationKeyGenerator;
  19. import com.sombrainc.util.EmailGenerator;
  20. import org.slf4j.Logger;
  21. import org.slf4j.LoggerFactory;
  22. import org.springframework.beans.factory.annotation.Autowired;
  23. import org.springframework.beans.factory.annotation.Value;
  24. import org.springframework.scheduling.annotation.Async;
  25. import org.springframework.security.authentication.*;
  26. import org.springframework.security.core.Authentication;
  27. import org.springframework.security.core.AuthenticationException;
  28. import org.springframework.security.core.GrantedAuthority;
  29. import org.springframework.security.core.context.SecurityContext;
  30. import org.springframework.security.core.context.SecurityContextHolder;
  31. import org.springframework.security.core.userdetails.UserDetails;
  32. import org.springframework.security.crypto.password.PasswordEncoder;
  33. import org.springframework.stereotype.Service;
  34. import org.springframework.transaction.annotation.Transactional;
  35.  
  36. import javax.persistence.EntityNotFoundException;
  37. import java.time.LocalDate;
  38. import java.util.HashMap;
  39. import java.util.Map;
  40. import java.util.Objects;
  41.  
  42. import static com.sombrainc.dto.common.RestMessageDTO.createFailureRestMessageDTO;
  43. import static com.sombrainc.dto.common.RestMessageDTO.createSuccessRestMessageDTO;
  44.  
  45. @Service
  46. public class UserServiceImpl implements UserService {
  47.  
  48.     private final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
  49.  
  50.     @Value("${app.mail.module.base.url}")
  51.     private String BASE_URL;
  52.     @Value("${app.email.template.forgotPassword}")
  53.     private String CONFIRM_FORGOT_PASSWORD_LOCATION;
  54.     @Value("${app.email.template.activation}")
  55.     private String ACTIVATION_LOCATION;
  56.  
  57.     @Autowired
  58.     private PasswordEncoder passwordEncoder;
  59.     @Autowired
  60.     private UserRepository userRepository;
  61.     @Autowired
  62.     private AuthenticationManager authManager;
  63.     @Autowired
  64.     private EmailService emailService;
  65.     @Autowired
  66.     private CountryRepository countryRepository;
  67.     @Autowired
  68.     private ClientRepository clientRepository;
  69.     @Autowired
  70.     private RecruiterRepository recruiterRepository;
  71.     @Autowired
  72.     private ActivationKeyGenerator keyGenerator;
  73.  
  74.     @Transactional
  75.     public RestMessageDTO createUnableUser(ClientRegistrationDTO dto) {
  76.         if (isNotFilledFieldsExist(dto)) {
  77.             LOGGER.warn("Please, fill all fields");
  78.             throw new EntityNotFulfilledException("Please, fill all fields");
  79.         }
  80.         if (dto.getUsername().matches("@")) {
  81.             LOGGER.warn("Username must not match '@'");
  82.             throw new IllegalArgumentException("Username must not match '@'");
  83.         }
  84.         if (Objects.nonNull(userRepository.findByEmailOrUsername(dto.getEmail().trim(), dto.getUsername().trim()))) {
  85.             LOGGER.warn("User with such email or username already exists");
  86.             throw new GeneralServiceException("User with such email or username already exists");
  87.         }
  88.         if (!Objects.equals(dto.getPassword(), dto.getPasswordConfirm())) {
  89.             LOGGER.warn("Wrong confirm password");
  90.             throw new IllegalArgumentException("Wrong confirm password");
  91.         }
  92.  
  93.         final String encodedPassword = passwordEncoder.encode(dto.getPassword());
  94.         User user = saveUser(dto, encodedPassword, RoleEnum.ROLE_CLIENT);
  95.         Client client = new Client(dto.getCompanyName(), null);
  96.         client.getUsers().add(user);
  97.  
  98.         user.setClient(clientRepository.save(client));
  99.         sendActivationEmail(user);
  100.  
  101.         return new RestMessageDTO("Success, check your email", true);
  102.     }
  103.  
  104.     public AuthUserDTO authenticateUser(LoginUserDTO loginUserDTO) {
  105.         UsernamePasswordAuthenticationToken authenticationToken =
  106.                 new UsernamePasswordAuthenticationToken(loginUserDTO.getEmail().trim(), loginUserDTO.getPassword());
  107.         Authentication authentication;
  108.         try {
  109.             authentication = this.authManager.authenticate(authenticationToken);
  110.         } catch (DisabledException e) {
  111.             LOGGER.error("Failed to authenticate : " + loginUserDTO.getEmail(), e);
  112.             throw new GeneralServiceException("Please confirm your sign up using link in your email");
  113.         } catch (BadCredentialsException e) {
  114.             LOGGER.error("Failed to authenticate : " + loginUserDTO.getEmail(), e);
  115.             throw new GeneralServiceException("Invalid credentials");
  116.         } catch (AccountExpiredException e) {
  117.             LOGGER.error("Failed to authenticate : " + loginUserDTO.getEmail(), e);
  118.             throw new GeneralServiceException("Your account has expired");
  119.         } catch (AuthenticationException e) {
  120.             LOGGER.error("Failed to authenticate : " + loginUserDTO.getEmail(), e);
  121.             throw new GeneralServiceException("Failed to authenticate, please check your credentials");
  122.         }
  123.         SecurityContextHolder.getContext().setAuthentication(authentication);
  124.  
  125.         return transformAuthenticationToAuthUserDTO(authentication);
  126.     }
  127.  
  128.     @Override
  129.     @Transactional
  130.     public RestMessageDTO activateUser(String key, ActivationEnum activationType) {
  131.         LOGGER.debug("Activating user for activation key {}", key);
  132.  
  133.         User user = userRepository.findByActivationKey(key)
  134.                 .orElseThrow(() -> new EntityNotFoundException("No users found by activation key"));
  135.  
  136.         switch (activationType) {
  137.             case ACTIVATION_ENUM_SIGN_UP:
  138.                 user.setActivated(true);
  139.                 user.setActivationKey(null);
  140.                 userRepository.save(user);
  141.                 return createSuccessRestMessageDTO("User has been successfully activated");
  142.  
  143.             case ACTIVATION_ENUM_CHANGE_PASSWORD:
  144.                 user.setActivationKey(null);
  145.                 user.setPassword(user.getTemporaryData());
  146.                 userRepository.save(user);
  147.                 return createSuccessRestMessageDTO("Password has been successfully changed");
  148.  
  149.             default:
  150.                 return createFailureRestMessageDTO("Wrong activation type!");
  151.         }
  152.     }
  153.  
  154.     @Override
  155.     @Transactional
  156.     public RestMessageDTO changePassword(ForgotPasswordDTO forgotPasswordDTO) {
  157.         String trimmedEmail = forgotPasswordDTO.getEmail().trim();
  158.         User user = userRepository.findByEmailOrUsername(trimmedEmail, trimmedEmail);
  159.         if (Objects.isNull(user)) {
  160.             LOGGER.warn("User not found");
  161.             throw new EntityNotFoundException("User not found");
  162.         }
  163.         if (!forgotPasswordDTO.getPassword().equals(forgotPasswordDTO.getPasswordConfirm())) {
  164.             LOGGER.warn("Passwords don't match");
  165.             return createFailureRestMessageDTO("Passwords don't match");
  166.         }
  167.         String hashedPassword = passwordEncoder.encode(forgotPasswordDTO.getPassword());
  168.  
  169.         user.setActivationKey(keyGenerator.generateActivationKey());
  170.         user.setTemporaryData(hashedPassword);
  171.         userRepository.save(user);
  172.  
  173.         sendChangePasswordEmail(user);
  174.  
  175.         return createSuccessRestMessageDTO("Please, confirm password change via email");
  176.     }
  177.  
  178.     @Override
  179.     @Transactional
  180.     public RestMessageDTO finishSignUp(UserRegistrationDTO dto) {
  181.         if (Objects.isNull(dto)
  182.                 || Strings.isNullOrEmpty(dto.getActivationKey())
  183.                 || Strings.isNullOrEmpty(dto.getUsername())
  184.                 || Strings.isNullOrEmpty(dto.getPassword())) {
  185.             LOGGER.warn("Please, fill all fields");
  186.             throw new IllegalArgumentException("Please, fill all fields");
  187.         }
  188.         if (dto.getUsername().matches("@")) {
  189.             LOGGER.warn("Username must not match '@'");
  190.             throw new IllegalArgumentException("Username must not match '@'");
  191.         }
  192.         String trimmedUsername = dto.getUsername().trim();
  193.         if (Objects.nonNull(userRepository.findByUsername(trimmedUsername))) {
  194.             LOGGER.warn("User with such email already exists");
  195.             throw new IllegalArgumentException("User with such email already exists");
  196.         }
  197.  
  198.         User user = userRepository.findByActivationKey(dto.getActivationKey())
  199.                 .orElseThrow(() -> new EntityNotFoundException("User not found or activation key is corrupted"));
  200.  
  201.         String hashedPassword = passwordEncoder.encode(dto.getPassword());
  202.  
  203.         user.setActivated(true);
  204.         user.setActivationKey(null);
  205.         user.setUsername(trimmedUsername);
  206.         user.setPassword(hashedPassword);
  207.  
  208.         userRepository.save(user);
  209.  
  210.         return createSuccessRestMessageDTO("Registration has been successfully finished");
  211.     }
  212.  
  213.     @Override
  214.     public String navigateAfterActivateUser(String key) {
  215.         if (activateUser(key, ActivationEnum.ACTIVATION_ENUM_SIGN_UP).isSuccess()) {
  216.             return "redirect:/login/success";
  217.         } else {
  218.             return "redirect:/error";
  219.         }
  220.     }
  221.  
  222.     @Override
  223.     public String navigateAfterChangePassword(String key) {
  224.         if (activateUser(key, ActivationEnum.ACTIVATION_ENUM_CHANGE_PASSWORD).isSuccess()) {
  225.             return "redirect:/login";
  226.         } else {
  227.             return "redirect:/error";
  228.         }
  229.     }
  230.  
  231.     @Override
  232.     public String navigateAfterConfirmInvite(String key) {
  233.         if (Objects.isNull(userRepository.findByActivationKey(key))) {
  234.             return "redirect:/error";
  235.         } else {
  236.             return "redirect:/sign-up/recruiter/" + key;
  237.         }
  238.     }
  239.  
  240.     @Override
  241.     public AuthUserDTO getAuthUser() {
  242.         SecurityContext securityContext = SecurityContextHolder.getContext();
  243.         return transformAuthenticationToAuthUserDTO(securityContext.getAuthentication());
  244.     }
  245.  
  246.     @Override
  247.     public User getLoggedInUser() {
  248.         String principal = getAuthUser().getEmail();
  249.         if (Strings.isNullOrEmpty(principal)) {
  250.             LOGGER.warn("Principal is null");
  251.             throw new GeneralServiceException("You must be logged in");
  252.         }
  253.         return userRepository.findByEmailOrUsername(principal, principal);
  254.     }
  255.  
  256.     private AuthUserDTO transformAuthenticationToAuthUserDTO(Authentication authentication) {
  257.         if (authentication == null) {
  258.             return new AuthUserDTO()
  259.                     .setMessage("Failed to obtain authentication, please check your credentials");
  260.         }
  261.         Object principal = authentication.getPrincipal();
  262.         if (principal instanceof String && (principal).equals("anonymousUser")) {
  263.             return new AuthUserDTO()
  264.                     .setMessage("Anonymous")
  265.                     .setAnonymous(true);
  266.         }
  267.         UserDetails userDetails = (UserDetails) principal;
  268.         User user = userRepository.findByEmail(userDetails.getUsername());
  269.         user.setLastLoggedInDate(LocalDate.now());
  270.         userRepository.save(user);
  271.  
  272.  
  273.         return new AuthUserDTO()
  274.                 .setFirstName(user.getFirstName())
  275.                 .setLastName(user.getLastName())
  276.                 .setEmail(userDetails.getUsername())
  277.                 .setEnabled(userDetails.isEnabled())
  278.                 .setMessage("Success")
  279.                 .setRoles(createRoleMap(userDetails));
  280.     }
  281.  
  282.     private Map<String, Boolean> createRoleMap(UserDetails userDetails) {
  283.         Map<String, Boolean> roles = new HashMap<>();
  284.         for (GrantedAuthority authority : userDetails.getAuthorities()) {
  285.             roles.put(authority.getAuthority(), Boolean.TRUE);
  286.         }
  287.         return roles;
  288.     }
  289.  
  290.     private boolean isNotFilledFieldsExist(ClientRegistrationDTO registrationDTO) {
  291.         return Objects.isNull(registrationDTO)
  292.                 || Strings.isNullOrEmpty(registrationDTO.getFirstName())
  293.                 || Strings.isNullOrEmpty(registrationDTO.getLastName())
  294.                 || Strings.isNullOrEmpty(registrationDTO.getPassword())
  295.                 || Strings.isNullOrEmpty(registrationDTO.getPasswordConfirm())
  296.                 || Strings.isNullOrEmpty(registrationDTO.getEmail())
  297.                 || Strings.isNullOrEmpty(registrationDTO.getUsername())
  298.                 || Strings.isNullOrEmpty(registrationDTO.getCompanyName());
  299.     }
  300.  
  301.     private User saveUser(ClientRegistrationDTO dto, String encodedPassword, RoleEnum role) {
  302.         User user;
  303.         user = createUser(dto, encodedPassword, role);
  304.         user = userRepository.save(user);
  305.         return user;
  306.     }
  307.  
  308.     private User createUser(ClientRegistrationDTO dto, String encodedPassword, RoleEnum role) {
  309.         User user = new User(
  310.                 dto.getEmail(),
  311.                 dto.getUsername(),
  312.                 dto.getFirstName(),
  313.                 dto.getLastName(),
  314.                 null
  315.         );
  316.         user.setActivationKey(keyGenerator.generateActivationKey());
  317.         user.setPassword(encodedPassword);
  318.         user.setRole(role);
  319.  
  320.         return user;
  321.     }
  322.  
  323.     @Async
  324.     private void sendChangePasswordEmail(User user) {
  325.         String username = user.getFirstName() + ' ' + user.getLastName();
  326.         String link = BASE_URL + "/public/user/confirm-new-password/" + user.getActivationKey();
  327.         String buttonText = "Confirm";
  328.         final String emailBody = EmailGenerator
  329.                 .generateEmail(link, CONFIRM_FORGOT_PASSWORD_LOCATION, username, buttonText);
  330.         String subject = "Change password";
  331.         emailService.sendHtmlEmail(user.getEmail(), subject, emailBody);
  332.     }
  333.  
  334.     @Async
  335.     private void sendActivationEmail(User user) {
  336.         String username = user.getFirstName() + ' ' + user.getLastName();
  337.         String link = BASE_URL + "/public/user/activate/" + user.getActivationKey();
  338.         String buttonText = "Activate account";
  339.         final String activationEmail = EmailGenerator
  340.                 .generateEmail(link, ACTIVATION_LOCATION, username, buttonText);
  341.         String subject = "Welcome to SelectPOP";
  342.         emailService.sendHtmlEmail(user.getEmail(), subject, activationEmail);
  343.     }
  344.  
  345. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement