token_cleanup_test.go 2.1 KB

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