Merge pull request 'Add periodic cleanup for expired email tokens' (#47) from fix/email-token-cleanup into main

Reviewed-on: https://git.ts.mattnite.net/mattnite/forgejo-tickets/pulls/47
This commit is contained in:
Matthew Knight 2026-02-18 00:24:50 +00:00
commit 0982129bf1
2 changed files with 19 additions and 0 deletions

View File

@ -62,6 +62,7 @@ func main() {
defer cancel() defer cancel()
go sessionStore.Cleanup(ctx, 30*time.Minute) go sessionStore.Cleanup(ctx, 30*time.Minute)
go authService.CleanupExpiredTokens(ctx, 1*time.Hour)
publicRouter := publichandlers.NewRouter(publichandlers.Dependencies{ publicRouter := publichandlers.NewRouter(publichandlers.Dependencies{
DB: db, DB: db,

View File

@ -10,6 +10,7 @@ import (
"github.com/google/uuid" "github.com/google/uuid"
"github.com/mattnite/forgejo-tickets/internal/models" "github.com/mattnite/forgejo-tickets/internal/models"
"github.com/rs/zerolog/log"
"golang.org/x/crypto/bcrypt" "golang.org/x/crypto/bcrypt"
) )
@ -85,6 +86,23 @@ func (s *Service) redeemToken(ctx context.Context, plainToken string, tokenType
return &user, nil return &user, nil
} }
// CleanupExpiredTokens periodically deletes expired and used email tokens.
func (s *Service) CleanupExpiredTokens(ctx context.Context, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
result := s.db.Where("expires_at <= ? OR used_at IS NOT NULL", time.Now()).Delete(&models.EmailToken{})
if result.Error != nil {
log.Error().Err(result.Error).Msg("email token cleanup error")
}
}
}
}
func hashToken(plainToken string) string { func hashToken(plainToken string) string {
h := sha256.Sum256([]byte(plainToken)) h := sha256.Sum256([]byte(plainToken))
return hex.EncodeToString(h[:]) return hex.EncodeToString(h[:])