[74af394] | 1 | package com.example.salonbella.service.mail;
|
---|
| 2 |
|
---|
| 3 | import com.example.salonbella.entity.ConfirmationTokenEntity;
|
---|
| 4 | import com.example.salonbella.entity.UserEntity;
|
---|
| 5 | import com.example.salonbella.repository.ConfirmationTokenRepository;
|
---|
| 6 | import com.example.salonbella.repository.UserRepository;
|
---|
| 7 | import org.springframework.beans.factory.annotation.Autowired;
|
---|
| 8 | import org.springframework.stereotype.Service;
|
---|
| 9 |
|
---|
| 10 | import javax.transaction.Transactional;
|
---|
| 11 | import java.time.LocalDateTime;
|
---|
| 12 | import java.util.Optional;
|
---|
| 13 |
|
---|
| 14 | @Service
|
---|
| 15 | public class ConfirmationTokenService {
|
---|
| 16 | private final ConfirmationTokenRepository confirmationTokenRepository;
|
---|
| 17 | private final UserRepository userRepository;
|
---|
| 18 |
|
---|
| 19 | @Autowired
|
---|
| 20 | public ConfirmationTokenService(ConfirmationTokenRepository confirmationTokenRepository, UserRepository userRepository) {
|
---|
| 21 | this.confirmationTokenRepository = confirmationTokenRepository;
|
---|
| 22 | this.userRepository = userRepository;
|
---|
| 23 | }
|
---|
| 24 |
|
---|
| 25 |
|
---|
| 26 | public void saveConfirmationToken(ConfirmationTokenEntity confirmationTokenEntity) {
|
---|
| 27 | confirmationTokenRepository.save(confirmationTokenEntity);
|
---|
| 28 | }
|
---|
| 29 |
|
---|
| 30 | @Transactional
|
---|
| 31 | public void confirmToken(String token) throws Exception {
|
---|
| 32 | ConfirmationTokenEntity confirmationTokenEntity = confirmationTokenRepository.findByToken(token).orElseThrow(IllegalStateException::new);
|
---|
| 33 | if (confirmationTokenEntity.getConfirmedAt() != null) {
|
---|
| 34 | throw new Exception();
|
---|
| 35 | }
|
---|
| 36 | LocalDateTime expiresAt = confirmationTokenEntity.getExpiresAt();
|
---|
| 37 |
|
---|
| 38 | if (expiresAt.isBefore(LocalDateTime.now())) {
|
---|
| 39 | throw new Exception();
|
---|
| 40 | }
|
---|
| 41 |
|
---|
| 42 | Optional<UserEntity> userEntity = userRepository.findById(confirmationTokenEntity.getUser().getId());
|
---|
| 43 | userEntity.ifPresent(entity -> entity.setValid(true));
|
---|
| 44 | confirmationTokenRepository.delete(confirmationTokenEntity);
|
---|
| 45 |
|
---|
| 46 | }
|
---|
| 47 | }
|
---|