|
| 1 | +package application |
| 2 | + |
| 3 | +import ( |
| 4 | + "email-verification/config" |
| 5 | + "email-verification/domain" |
| 6 | + "fmt" |
| 7 | + "time" |
| 8 | +) |
| 9 | + |
| 10 | +type VerificationService struct { |
| 11 | + repo domain.VerificationRepository |
| 12 | + emailService domain.EmailService |
| 13 | + codeGen domain.CodeGenerator |
| 14 | + codeExpiration time.Duration |
| 15 | +} |
| 16 | + |
| 17 | +func NewVerificationService( |
| 18 | + repo domain.VerificationRepository, |
| 19 | + emailService domain.EmailService, |
| 20 | + codeGen domain.CodeGenerator, |
| 21 | + config *config.Config, |
| 22 | +) *VerificationService { |
| 23 | + return &VerificationService{ |
| 24 | + repo: repo, |
| 25 | + emailService: emailService, |
| 26 | + codeGen: codeGen, |
| 27 | + codeExpiration: config.CodeExpiration, |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +func (s *VerificationService) SendVerification(email string) error { |
| 32 | + if email == "" { |
| 33 | + return fmt.Errorf("email cannot be empty") |
| 34 | + } |
| 35 | + |
| 36 | + if _, err := s.repo.Get(email); err == nil { |
| 37 | + return fmt.Errorf("verification already pending") |
| 38 | + } |
| 39 | + |
| 40 | + code, err := s.codeGen.Generate() |
| 41 | + if err != nil { |
| 42 | + return err |
| 43 | + } |
| 44 | + |
| 45 | + if err := s.emailService.SendVerificationCode(email, code); err != nil { |
| 46 | + return err |
| 47 | + } |
| 48 | + |
| 49 | + verification := domain.Verification{ |
| 50 | + Code: s.codeGen.Hash(code), |
| 51 | + Exp: time.Now().Add(s.codeExpiration), |
| 52 | + } |
| 53 | + |
| 54 | + return s.repo.Store(email, verification) |
| 55 | +} |
| 56 | + |
| 57 | +func (s *VerificationService) VerifyCode(email, code string) error { |
| 58 | + if email == "" || code == "" { |
| 59 | + return fmt.Errorf("email and code cannot be empty") |
| 60 | + } |
| 61 | + |
| 62 | + verification, err := s.repo.Get(email) |
| 63 | + if err != nil { |
| 64 | + return err |
| 65 | + } |
| 66 | + |
| 67 | + hashedCode := s.codeGen.Hash(code) |
| 68 | + if verification.Code != hashedCode { |
| 69 | + return fmt.Errorf("invalid code") |
| 70 | + } |
| 71 | + |
| 72 | + if time.Now().After(verification.Exp) { |
| 73 | + if err := s.repo.Delete(email); err != nil { |
| 74 | + return fmt.Errorf("failed to delete expired code: %w", err) |
| 75 | + } |
| 76 | + return fmt.Errorf("code expired") |
| 77 | + } |
| 78 | + |
| 79 | + return s.repo.Delete(email) |
| 80 | +} |
0 commit comments