package com.example.plantsforyou.registration; import com.example.plantsforyou.appuser.AppUser; import com.example.plantsforyou.appuser.AppUserRole; import com.example.plantsforyou.appuser.AppUserService; import com.example.plantsforyou.email.EmailSender; import com.example.plantsforyou.email.EmailService; import com.example.plantsforyou.registration.token.ConfirmationToken; import com.example.plantsforyou.registration.token.ConfirmationTokenService; import lombok.AllArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.time.LocalDateTime; @Service @AllArgsConstructor public class RegistrationService { private final AppUserService appUserService; private final EmailValidator emailValidator; private ConfirmationTokenService confirmationTokenService; private final EmailSender emailSender; public String register(RegistrationRequest request) { boolean isValidEmail = emailValidator.test(request.getEmail()); if(!isValidEmail){ throw new IllegalStateException("email not valid"); } String token = appUserService.signUpUser( new AppUser( request.getFirstName(), request.getLastName(), request.getEmail(), request.getPassword(), AppUserRole.USER )); String link = "http://localhost:8080/confirm?token=" + token; emailSender.send(request.getEmail(), buildEmail(request.getFirstName(), link)); //TODO: Email server configration return token; } @Transactional public String confirmToken(String token) { ConfirmationToken confirmationToken = confirmationTokenService .getToken(token) .orElseThrow(() -> new IllegalStateException("token not found")); if (confirmationToken.getConfirmedAt() != null) { throw new IllegalStateException("email already confirmed"); } LocalDateTime expiredAt = confirmationToken.getExpiresAt(); if (expiredAt.isBefore(LocalDateTime.now())) { throw new IllegalStateException("token expired"); } confirmationTokenService.setConfirmedAt(token); appUserService.enableAppUser( confirmationToken.getAppUser().getEmail()); return "confirmed"; } private String buildEmail(String name, String link) { return "
\n" + "\n" + "\n" + "\n" + " \n" + " \n" + " \n" + " \n" + "
\n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
\n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
\n" + " \n" + " \n" + " Confirm your email\n" + "
\n" + " \n" + "
\n" + " \n" + "
\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
\n" + " \n" + " \n" + " \n" + " \n" + " \n" + "
\n" + " \n" + "
\n" + "\n" + "\n" + "\n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + " \n" + "


\n" + " \n" + "

Hi " + name + ",

Thank you for registering. Please click on the below link to activate your account:

Activate Now

\n Link will expire in 15 minutes.

See you soon

" + " \n" + "


\n" + "\n" + "
"; } }