session_cleanup.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. package authtoken
  2. import (
  3. "context"
  4. "time"
  5. )
  6. func (srv *UserAuthTokenServiceImpl) Run(ctx context.Context) error {
  7. if srv.Cfg.ExpiredTokensCleanupIntervalDays <= 0 {
  8. srv.log.Debug("cleanup of expired auth tokens are disabled")
  9. return nil
  10. }
  11. jobInterval := time.Duration(srv.Cfg.ExpiredTokensCleanupIntervalDays) * 24 * time.Hour
  12. srv.log.Debug("cleanup of expired auth tokens are enabled", "intervalDays", srv.Cfg.ExpiredTokensCleanupIntervalDays)
  13. ticker := time.NewTicker(jobInterval)
  14. maxInactiveLifetime := time.Duration(srv.Cfg.LoginMaxInactiveLifetimeDays) * 24 * time.Hour
  15. maxLifetime := time.Duration(srv.Cfg.LoginMaxLifetimeDays) * 24 * time.Hour
  16. for {
  17. select {
  18. case <-ticker.C:
  19. srv.ServerLockService.LockAndExecute(ctx, "cleanup expired auth tokens", time.Hour*12, func() {
  20. srv.deleteExpiredTokens(maxInactiveLifetime, maxLifetime)
  21. })
  22. case <-ctx.Done():
  23. return ctx.Err()
  24. }
  25. }
  26. }
  27. func (srv *UserAuthTokenServiceImpl) deleteExpiredTokens(maxInactiveLifetime, maxLifetime time.Duration) (int64, error) {
  28. createdBefore := getTime().Add(-maxLifetime)
  29. rotatedBefore := getTime().Add(-maxInactiveLifetime)
  30. srv.log.Debug("starting cleanup of expired auth tokens", "createdBefore", createdBefore, "rotatedBefore", rotatedBefore)
  31. sql := `DELETE from user_auth_token WHERE created_at <= ? OR rotated_at <= ?`
  32. res, err := srv.SQLStore.NewSession().Exec(sql, createdBefore.Unix(), rotatedBefore.Unix())
  33. if err != nil {
  34. return 0, err
  35. }
  36. affected, err := res.RowsAffected()
  37. if err != nil {
  38. srv.log.Error("failed to cleanup expired auth tokens", "error", err)
  39. return 0, nil
  40. }
  41. srv.log.Info("cleanup of expired auth tokens done", "count", affected)
  42. return affected, err
  43. }