token_cleanup_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package auth
  2. import (
  3. "context"
  4. "fmt"
  5. "testing"
  6. "time"
  7. . "github.com/smartystreets/goconvey/convey"
  8. )
  9. func TestUserAuthTokenCleanup(t *testing.T) {
  10. Convey("Test user auth token cleanup", t, func() {
  11. ctx := createTestContext(t)
  12. ctx.tokenService.Cfg.LoginMaxInactiveLifetimeDays = 7
  13. ctx.tokenService.Cfg.LoginMaxLifetimeDays = 30
  14. insertToken := func(token string, prev string, createdAt, rotatedAt int64) {
  15. ut := userAuthToken{AuthToken: token, PrevAuthToken: prev, CreatedAt: createdAt, RotatedAt: rotatedAt, UserAgent: "", ClientIp: ""}
  16. _, err := ctx.sqlstore.NewSession().Insert(&ut)
  17. So(err, ShouldBeNil)
  18. }
  19. t := time.Date(2018, 12, 13, 13, 45, 0, 0, time.UTC)
  20. getTime = func() time.Time {
  21. return t
  22. }
  23. Convey("should delete tokens where token rotation age is older than or equal 7 days", func() {
  24. from := t.Add(-7 * 24 * time.Hour)
  25. // insert three old tokens that should be deleted
  26. for i := 0; i < 3; i++ {
  27. insertToken(fmt.Sprintf("oldA%d", i), fmt.Sprintf("oldB%d", i), from.Unix(), from.Unix())
  28. }
  29. // insert three active tokens that should not be deleted
  30. for i := 0; i < 3; i++ {
  31. from = from.Add(time.Second)
  32. insertToken(fmt.Sprintf("newA%d", i), fmt.Sprintf("newB%d", i), from.Unix(), from.Unix())
  33. }
  34. affected, err := ctx.tokenService.deleteExpiredTokens(context.Background(), 7*24*time.Hour, 30*24*time.Hour)
  35. So(err, ShouldBeNil)
  36. So(affected, ShouldEqual, 3)
  37. })
  38. Convey("should delete tokens where token age is older than or equal 30 days", func() {
  39. from := t.Add(-30 * 24 * time.Hour)
  40. fromRotate := t.Add(-time.Second)
  41. // insert three old tokens that should be deleted
  42. for i := 0; i < 3; i++ {
  43. insertToken(fmt.Sprintf("oldA%d", i), fmt.Sprintf("oldB%d", i), from.Unix(), fromRotate.Unix())
  44. }
  45. // insert three active tokens that should not be deleted
  46. for i := 0; i < 3; i++ {
  47. from = from.Add(time.Second)
  48. insertToken(fmt.Sprintf("newA%d", i), fmt.Sprintf("newB%d", i), from.Unix(), fromRotate.Unix())
  49. }
  50. affected, err := ctx.tokenService.deleteExpiredTokens(context.Background(), 7*24*time.Hour, 30*24*time.Hour)
  51. So(err, ShouldBeNil)
  52. So(affected, ShouldEqual, 3)
  53. })
  54. })
  55. }