63 lines
1.4 KiB
Go
63 lines
1.4 KiB
Go
package auth
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"time"
|
|
|
|
"base/internal/domain/auth"
|
|
"base/internal/dto"
|
|
"base/pkg/email"
|
|
)
|
|
|
|
func (s *service) SendVerificationEmail(ctx context.Context, request dto.SendVerificationEmailRequest) error {
|
|
emailMsg := email.Request{
|
|
To: request.Email,
|
|
Subject: "Verify Your Email",
|
|
Template: email.TemplateData{EmailTemplateName: email.TemplateEmailVerification},
|
|
}
|
|
|
|
if _, err := s.emailService.Send(ctx, emailMsg); err != nil {
|
|
s.logger.Error().Err(err).Msg("failed to send verification email")
|
|
return fmt.Errorf("failed to send verification email: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
func (s *service) VerifyAccount(ctx context.Context, request dto.VerifyAccountRequest) error {
|
|
user, err := s.userRepo.FindByEmail(ctx, request.Email)
|
|
if err != nil {
|
|
return ErrUserNotFound
|
|
}
|
|
|
|
if user.EmailVerified {
|
|
return ErrEmailAlreadyVerified
|
|
}
|
|
|
|
// Get code from cache
|
|
key := fmt.Sprintf("verification:%s", request.Email)
|
|
|
|
storedCode, found, err := s.verificationStore.Get(ctx, key)
|
|
if err != nil || !found {
|
|
return ErrInvalidVerificationCode
|
|
}
|
|
|
|
if storedCode != request.Code {
|
|
return ErrInvalidVerificationCode
|
|
}
|
|
|
|
user.EmailVerified = true
|
|
user.Status = auth.UserStatusActive
|
|
user.UpdatedAt = time.Now()
|
|
|
|
if err := s.userRepo.Update(ctx, user); err != nil {
|
|
return fmt.Errorf("failed to update user: %w", err)
|
|
}
|
|
|
|
// Delete verification code from cache
|
|
_ = s.verificationStore.Delete(ctx, key)
|
|
|
|
return nil
|
|
}
|