access_tokens_test.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package database
  5. import (
  6. "context"
  7. "testing"
  8. "time"
  9. "github.com/stretchr/testify/assert"
  10. "github.com/stretchr/testify/require"
  11. "gorm.io/gorm"
  12. "gogs.io/gogs/internal/errutil"
  13. )
  14. func TestAccessToken_BeforeCreate(t *testing.T) {
  15. now := time.Now()
  16. db := &gorm.DB{
  17. Config: &gorm.Config{
  18. SkipDefaultTransaction: true,
  19. NowFunc: func() time.Time {
  20. return now
  21. },
  22. },
  23. }
  24. t.Run("CreatedUnix has been set", func(t *testing.T) {
  25. token := &AccessToken{
  26. CreatedUnix: 1,
  27. }
  28. _ = token.BeforeCreate(db)
  29. assert.Equal(t, int64(1), token.CreatedUnix)
  30. assert.Equal(t, int64(0), token.UpdatedUnix) // Do not set UpdatedUnix until it is used.
  31. })
  32. t.Run("CreatedUnix has not been set", func(t *testing.T) {
  33. token := &AccessToken{}
  34. _ = token.BeforeCreate(db)
  35. assert.Equal(t, db.NowFunc().Unix(), token.CreatedUnix)
  36. assert.Equal(t, int64(0), token.UpdatedUnix) // Do not set UpdatedUnix until it is used.
  37. })
  38. }
  39. func TestAccessToken_AfterFind(t *testing.T) {
  40. now := time.Now()
  41. db := &gorm.DB{
  42. Config: &gorm.Config{
  43. SkipDefaultTransaction: true,
  44. NowFunc: func() time.Time {
  45. return now
  46. },
  47. },
  48. }
  49. t.Run("UpdatedUnix has been set and within 7 days", func(t *testing.T) {
  50. token := &AccessToken{
  51. CreatedUnix: now.Unix(),
  52. UpdatedUnix: now.Add(time.Second).Unix(),
  53. }
  54. _ = token.AfterFind(db)
  55. assert.Equal(t, token.CreatedUnix, token.Created.Unix())
  56. assert.Equal(t, token.UpdatedUnix, token.Updated.Unix())
  57. assert.True(t, token.HasUsed)
  58. assert.True(t, token.HasRecentActivity)
  59. })
  60. t.Run("UpdatedUnix has been set and not within 7 days", func(t *testing.T) {
  61. token := &AccessToken{
  62. CreatedUnix: now.Add(-1 * 9 * 24 * time.Hour).Unix(),
  63. UpdatedUnix: now.Add(-1 * 8 * 24 * time.Hour).Unix(),
  64. }
  65. _ = token.AfterFind(db)
  66. assert.Equal(t, token.CreatedUnix, token.Created.Unix())
  67. assert.Equal(t, token.UpdatedUnix, token.Updated.Unix())
  68. assert.True(t, token.HasUsed)
  69. assert.False(t, token.HasRecentActivity)
  70. })
  71. t.Run("UpdatedUnix has not been set", func(t *testing.T) {
  72. token := &AccessToken{
  73. CreatedUnix: now.Unix(),
  74. }
  75. _ = token.AfterFind(db)
  76. assert.Equal(t, token.CreatedUnix, token.Created.Unix())
  77. assert.True(t, token.Updated.IsZero())
  78. assert.False(t, token.HasUsed)
  79. assert.False(t, token.HasRecentActivity)
  80. })
  81. }
  82. func TestAccessTokens(t *testing.T) {
  83. if testing.Short() {
  84. t.Skip()
  85. }
  86. t.Parallel()
  87. ctx := context.Background()
  88. s := &AccessTokensStore{
  89. db: newTestDB(t, "AccessTokensStore"),
  90. }
  91. for _, tc := range []struct {
  92. name string
  93. test func(t *testing.T, ctx context.Context, s *AccessTokensStore)
  94. }{
  95. {"Create", accessTokensCreate},
  96. {"DeleteByID", accessTokensDeleteByID},
  97. {"GetBySHA1", accessTokensGetBySHA},
  98. {"List", accessTokensList},
  99. {"Touch", accessTokensTouch},
  100. } {
  101. t.Run(tc.name, func(t *testing.T) {
  102. t.Cleanup(func() {
  103. err := clearTables(t, s.db)
  104. require.NoError(t, err)
  105. })
  106. tc.test(t, ctx, s)
  107. })
  108. if t.Failed() {
  109. break
  110. }
  111. }
  112. }
  113. func accessTokensCreate(t *testing.T, ctx context.Context, s *AccessTokensStore) {
  114. // Create first access token with name "Test"
  115. token, err := s.Create(ctx, 1, "Test")
  116. require.NoError(t, err)
  117. assert.Equal(t, int64(1), token.UserID)
  118. assert.Equal(t, "Test", token.Name)
  119. assert.Equal(t, 40, len(token.Sha1), "sha1 length")
  120. // Get it back and check the Created field
  121. token, err = s.GetBySHA1(ctx, token.Sha1)
  122. require.NoError(t, err)
  123. assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), token.Created.UTC().Format(time.RFC3339))
  124. // Try create second access token with same name should fail
  125. _, err = s.Create(ctx, token.UserID, token.Name)
  126. wantErr := ErrAccessTokenAlreadyExist{
  127. args: errutil.Args{
  128. "userID": token.UserID,
  129. "name": token.Name,
  130. },
  131. }
  132. assert.Equal(t, wantErr, err)
  133. }
  134. func accessTokensDeleteByID(t *testing.T, ctx context.Context, s *AccessTokensStore) {
  135. // Create an access token with name "Test"
  136. token, err := s.Create(ctx, 1, "Test")
  137. require.NoError(t, err)
  138. // Delete a token with mismatched user ID is noop
  139. err = s.DeleteByID(ctx, 2, token.ID)
  140. require.NoError(t, err)
  141. // We should be able to get it back
  142. _, err = s.GetBySHA1(ctx, token.Sha1)
  143. require.NoError(t, err)
  144. // Now delete this token with correct user ID
  145. err = s.DeleteByID(ctx, token.UserID, token.ID)
  146. require.NoError(t, err)
  147. // We should get token not found error
  148. _, err = s.GetBySHA1(ctx, token.Sha1)
  149. wantErr := ErrAccessTokenNotExist{
  150. args: errutil.Args{
  151. "sha": token.Sha1,
  152. },
  153. }
  154. assert.Equal(t, wantErr, err)
  155. }
  156. func accessTokensGetBySHA(t *testing.T, ctx context.Context, s *AccessTokensStore) {
  157. // Create an access token with name "Test"
  158. token, err := s.Create(ctx, 1, "Test")
  159. require.NoError(t, err)
  160. // We should be able to get it back
  161. _, err = s.GetBySHA1(ctx, token.Sha1)
  162. require.NoError(t, err)
  163. // Try to get a non-existent token
  164. _, err = s.GetBySHA1(ctx, "bad_sha")
  165. wantErr := ErrAccessTokenNotExist{
  166. args: errutil.Args{
  167. "sha": "bad_sha",
  168. },
  169. }
  170. assert.Equal(t, wantErr, err)
  171. }
  172. func accessTokensList(t *testing.T, ctx context.Context, s *AccessTokensStore) {
  173. // Create two access tokens for user 1
  174. _, err := s.Create(ctx, 1, "user1_1")
  175. require.NoError(t, err)
  176. _, err = s.Create(ctx, 1, "user1_2")
  177. require.NoError(t, err)
  178. // Create one access token for user 2
  179. _, err = s.Create(ctx, 2, "user2_1")
  180. require.NoError(t, err)
  181. // List all access tokens for user 1
  182. tokens, err := s.List(ctx, 1)
  183. require.NoError(t, err)
  184. require.Equal(t, 2, len(tokens), "number of tokens")
  185. assert.Equal(t, int64(1), tokens[0].UserID)
  186. assert.Equal(t, "user1_1", tokens[0].Name)
  187. assert.Equal(t, int64(1), tokens[1].UserID)
  188. assert.Equal(t, "user1_2", tokens[1].Name)
  189. }
  190. func accessTokensTouch(t *testing.T, ctx context.Context, s *AccessTokensStore) {
  191. // Create an access token with name "Test"
  192. token, err := s.Create(ctx, 1, "Test")
  193. require.NoError(t, err)
  194. // Updated field is zero now
  195. assert.True(t, token.Updated.IsZero())
  196. err = s.Touch(ctx, token.ID)
  197. require.NoError(t, err)
  198. // Get back from DB should have Updated set
  199. token, err = s.GetBySHA1(ctx, token.Sha1)
  200. require.NoError(t, err)
  201. assert.Equal(t, s.db.NowFunc().Format(time.RFC3339), token.Updated.UTC().Format(time.RFC3339))
  202. }