access_tokens_test.go 6.3 KB

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