Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.sombrainc.service.implementation;
- import com.google.common.base.Strings;
- import com.sombrainc.dto.common.RestMessageDTO;
- import com.sombrainc.dto.regular.*;
- import com.sombrainc.entity.Client;
- import com.sombrainc.entity.regular.User;
- import com.sombrainc.enums.ActivationEnum;
- import com.sombrainc.enums.RoleEnum;
- import com.sombrainc.exception.EntityNotFulfilledException;
- import com.sombrainc.exception.GeneralServiceException;
- import com.sombrainc.repository.ClientRepository;
- import com.sombrainc.repository.RecruiterRepository;
- import com.sombrainc.repository.regular.CountryRepository;
- import com.sombrainc.repository.regular.UserRepository;
- import com.sombrainc.service.EmailService;
- import com.sombrainc.service.UserService;
- import com.sombrainc.util.ActivationKeyGenerator;
- import com.sombrainc.util.EmailGenerator;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.scheduling.annotation.Async;
- import org.springframework.security.authentication.*;
- import org.springframework.security.core.Authentication;
- import org.springframework.security.core.AuthenticationException;
- import org.springframework.security.core.GrantedAuthority;
- import org.springframework.security.core.context.SecurityContext;
- import org.springframework.security.core.context.SecurityContextHolder;
- import org.springframework.security.core.userdetails.UserDetails;
- import org.springframework.security.crypto.password.PasswordEncoder;
- import org.springframework.stereotype.Service;
- import org.springframework.transaction.annotation.Transactional;
- import javax.persistence.EntityNotFoundException;
- import java.time.LocalDate;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.Objects;
- import static com.sombrainc.dto.common.RestMessageDTO.createFailureRestMessageDTO;
- import static com.sombrainc.dto.common.RestMessageDTO.createSuccessRestMessageDTO;
- @Service
- public class UserServiceImpl implements UserService {
- private final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);
- @Value("${app.mail.module.base.url}")
- private String BASE_URL;
- @Value("${app.email.template.forgotPassword}")
- private String CONFIRM_FORGOT_PASSWORD_LOCATION;
- @Value("${app.email.template.activation}")
- private String ACTIVATION_LOCATION;
- @Autowired
- private PasswordEncoder passwordEncoder;
- @Autowired
- private UserRepository userRepository;
- @Autowired
- private AuthenticationManager authManager;
- @Autowired
- private EmailService emailService;
- @Autowired
- private CountryRepository countryRepository;
- @Autowired
- private ClientRepository clientRepository;
- @Autowired
- private RecruiterRepository recruiterRepository;
- @Autowired
- private ActivationKeyGenerator keyGenerator;
- @Transactional
- public RestMessageDTO createUnableUser(ClientRegistrationDTO dto) {
- if (isNotFilledFieldsExist(dto)) {
- LOGGER.warn("Please, fill all fields");
- throw new EntityNotFulfilledException("Please, fill all fields");
- }
- if (dto.getUsername().matches("@")) {
- LOGGER.warn("Username must not match '@'");
- throw new IllegalArgumentException("Username must not match '@'");
- }
- if (Objects.nonNull(userRepository.findByEmailOrUsername(dto.getEmail().trim(), dto.getUsername().trim()))) {
- LOGGER.warn("User with such email or username already exists");
- throw new GeneralServiceException("User with such email or username already exists");
- }
- if (!Objects.equals(dto.getPassword(), dto.getPasswordConfirm())) {
- LOGGER.warn("Wrong confirm password");
- throw new IllegalArgumentException("Wrong confirm password");
- }
- final String encodedPassword = passwordEncoder.encode(dto.getPassword());
- User user = saveUser(dto, encodedPassword, RoleEnum.ROLE_CLIENT);
- Client client = new Client(dto.getCompanyName(), null);
- client.getUsers().add(user);
- user.setClient(clientRepository.save(client));
- sendActivationEmail(user);
- return new RestMessageDTO("Success, check your email", true);
- }
- public AuthUserDTO authenticateUser(LoginUserDTO loginUserDTO) {
- UsernamePasswordAuthenticationToken authenticationToken =
- new UsernamePasswordAuthenticationToken(loginUserDTO.getEmail().trim(), loginUserDTO.getPassword());
- Authentication authentication;
- try {
- authentication = this.authManager.authenticate(authenticationToken);
- } catch (DisabledException e) {
- LOGGER.error("Failed to authenticate : " + loginUserDTO.getEmail(), e);
- throw new GeneralServiceException("Please confirm your sign up using link in your email");
- } catch (BadCredentialsException e) {
- LOGGER.error("Failed to authenticate : " + loginUserDTO.getEmail(), e);
- throw new GeneralServiceException("Invalid credentials");
- } catch (AccountExpiredException e) {
- LOGGER.error("Failed to authenticate : " + loginUserDTO.getEmail(), e);
- throw new GeneralServiceException("Your account has expired");
- } catch (AuthenticationException e) {
- LOGGER.error("Failed to authenticate : " + loginUserDTO.getEmail(), e);
- throw new GeneralServiceException("Failed to authenticate, please check your credentials");
- }
- SecurityContextHolder.getContext().setAuthentication(authentication);
- return transformAuthenticationToAuthUserDTO(authentication);
- }
- @Override
- @Transactional
- public RestMessageDTO activateUser(String key, ActivationEnum activationType) {
- LOGGER.debug("Activating user for activation key {}", key);
- User user = userRepository.findByActivationKey(key)
- .orElseThrow(() -> new EntityNotFoundException("No users found by activation key"));
- switch (activationType) {
- case ACTIVATION_ENUM_SIGN_UP:
- user.setActivated(true);
- user.setActivationKey(null);
- userRepository.save(user);
- return createSuccessRestMessageDTO("User has been successfully activated");
- case ACTIVATION_ENUM_CHANGE_PASSWORD:
- user.setActivationKey(null);
- user.setPassword(user.getTemporaryData());
- userRepository.save(user);
- return createSuccessRestMessageDTO("Password has been successfully changed");
- default:
- return createFailureRestMessageDTO("Wrong activation type!");
- }
- }
- @Override
- @Transactional
- public RestMessageDTO changePassword(ForgotPasswordDTO forgotPasswordDTO) {
- String trimmedEmail = forgotPasswordDTO.getEmail().trim();
- User user = userRepository.findByEmailOrUsername(trimmedEmail, trimmedEmail);
- if (Objects.isNull(user)) {
- LOGGER.warn("User not found");
- throw new EntityNotFoundException("User not found");
- }
- if (!forgotPasswordDTO.getPassword().equals(forgotPasswordDTO.getPasswordConfirm())) {
- LOGGER.warn("Passwords don't match");
- return createFailureRestMessageDTO("Passwords don't match");
- }
- String hashedPassword = passwordEncoder.encode(forgotPasswordDTO.getPassword());
- user.setActivationKey(keyGenerator.generateActivationKey());
- user.setTemporaryData(hashedPassword);
- userRepository.save(user);
- sendChangePasswordEmail(user);
- return createSuccessRestMessageDTO("Please, confirm password change via email");
- }
- @Override
- @Transactional
- public RestMessageDTO finishSignUp(UserRegistrationDTO dto) {
- if (Objects.isNull(dto)
- || Strings.isNullOrEmpty(dto.getActivationKey())
- || Strings.isNullOrEmpty(dto.getUsername())
- || Strings.isNullOrEmpty(dto.getPassword())) {
- LOGGER.warn("Please, fill all fields");
- throw new IllegalArgumentException("Please, fill all fields");
- }
- if (dto.getUsername().matches("@")) {
- LOGGER.warn("Username must not match '@'");
- throw new IllegalArgumentException("Username must not match '@'");
- }
- String trimmedUsername = dto.getUsername().trim();
- if (Objects.nonNull(userRepository.findByUsername(trimmedUsername))) {
- LOGGER.warn("User with such email already exists");
- throw new IllegalArgumentException("User with such email already exists");
- }
- User user = userRepository.findByActivationKey(dto.getActivationKey())
- .orElseThrow(() -> new EntityNotFoundException("User not found or activation key is corrupted"));
- String hashedPassword = passwordEncoder.encode(dto.getPassword());
- user.setActivated(true);
- user.setActivationKey(null);
- user.setUsername(trimmedUsername);
- user.setPassword(hashedPassword);
- userRepository.save(user);
- return createSuccessRestMessageDTO("Registration has been successfully finished");
- }
- @Override
- public String navigateAfterActivateUser(String key) {
- if (activateUser(key, ActivationEnum.ACTIVATION_ENUM_SIGN_UP).isSuccess()) {
- return "redirect:/login/success";
- } else {
- return "redirect:/error";
- }
- }
- @Override
- public String navigateAfterChangePassword(String key) {
- if (activateUser(key, ActivationEnum.ACTIVATION_ENUM_CHANGE_PASSWORD).isSuccess()) {
- return "redirect:/login";
- } else {
- return "redirect:/error";
- }
- }
- @Override
- public String navigateAfterConfirmInvite(String key) {
- if (Objects.isNull(userRepository.findByActivationKey(key))) {
- return "redirect:/error";
- } else {
- return "redirect:/sign-up/recruiter/" + key;
- }
- }
- @Override
- public AuthUserDTO getAuthUser() {
- SecurityContext securityContext = SecurityContextHolder.getContext();
- return transformAuthenticationToAuthUserDTO(securityContext.getAuthentication());
- }
- @Override
- public User getLoggedInUser() {
- String principal = getAuthUser().getEmail();
- if (Strings.isNullOrEmpty(principal)) {
- LOGGER.warn("Principal is null");
- throw new GeneralServiceException("You must be logged in");
- }
- return userRepository.findByEmailOrUsername(principal, principal);
- }
- private AuthUserDTO transformAuthenticationToAuthUserDTO(Authentication authentication) {
- if (authentication == null) {
- return new AuthUserDTO()
- .setMessage("Failed to obtain authentication, please check your credentials");
- }
- Object principal = authentication.getPrincipal();
- if (principal instanceof String && (principal).equals("anonymousUser")) {
- return new AuthUserDTO()
- .setMessage("Anonymous")
- .setAnonymous(true);
- }
- UserDetails userDetails = (UserDetails) principal;
- User user = userRepository.findByEmail(userDetails.getUsername());
- user.setLastLoggedInDate(LocalDate.now());
- userRepository.save(user);
- return new AuthUserDTO()
- .setFirstName(user.getFirstName())
- .setLastName(user.getLastName())
- .setEmail(userDetails.getUsername())
- .setEnabled(userDetails.isEnabled())
- .setMessage("Success")
- .setRoles(createRoleMap(userDetails));
- }
- private Map<String, Boolean> createRoleMap(UserDetails userDetails) {
- Map<String, Boolean> roles = new HashMap<>();
- for (GrantedAuthority authority : userDetails.getAuthorities()) {
- roles.put(authority.getAuthority(), Boolean.TRUE);
- }
- return roles;
- }
- private boolean isNotFilledFieldsExist(ClientRegistrationDTO registrationDTO) {
- return Objects.isNull(registrationDTO)
- || Strings.isNullOrEmpty(registrationDTO.getFirstName())
- || Strings.isNullOrEmpty(registrationDTO.getLastName())
- || Strings.isNullOrEmpty(registrationDTO.getPassword())
- || Strings.isNullOrEmpty(registrationDTO.getPasswordConfirm())
- || Strings.isNullOrEmpty(registrationDTO.getEmail())
- || Strings.isNullOrEmpty(registrationDTO.getUsername())
- || Strings.isNullOrEmpty(registrationDTO.getCompanyName());
- }
- private User saveUser(ClientRegistrationDTO dto, String encodedPassword, RoleEnum role) {
- User user;
- user = createUser(dto, encodedPassword, role);
- user = userRepository.save(user);
- return user;
- }
- private User createUser(ClientRegistrationDTO dto, String encodedPassword, RoleEnum role) {
- User user = new User(
- dto.getEmail(),
- dto.getUsername(),
- dto.getFirstName(),
- dto.getLastName(),
- null
- );
- user.setActivationKey(keyGenerator.generateActivationKey());
- user.setPassword(encodedPassword);
- user.setRole(role);
- return user;
- }
- @Async
- private void sendChangePasswordEmail(User user) {
- String username = user.getFirstName() + ' ' + user.getLastName();
- String link = BASE_URL + "/public/user/confirm-new-password/" + user.getActivationKey();
- String buttonText = "Confirm";
- final String emailBody = EmailGenerator
- .generateEmail(link, CONFIRM_FORGOT_PASSWORD_LOCATION, username, buttonText);
- String subject = "Change password";
- emailService.sendHtmlEmail(user.getEmail(), subject, emailBody);
- }
- @Async
- private void sendActivationEmail(User user) {
- String username = user.getFirstName() + ' ' + user.getLastName();
- String link = BASE_URL + "/public/user/activate/" + user.getActivationKey();
- String buttonText = "Activate account";
- final String activationEmail = EmailGenerator
- .generateEmail(link, ACTIVATION_LOCATION, username, buttonText);
- String subject = "Welcome to SelectPOP";
- emailService.sendHtmlEmail(user.getEmail(), subject, activationEmail);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement