users_test.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  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. "fmt"
  8. "testing"
  9. "time"
  10. "github.com/stretchr/testify/assert"
  11. "github.com/stretchr/testify/require"
  12. "gogs.io/gogs/internal/auth"
  13. "gogs.io/gogs/internal/errutil"
  14. )
  15. func TestUsers(t *testing.T) {
  16. if testing.Short() {
  17. t.Skip()
  18. }
  19. t.Parallel()
  20. tables := []interface{}{new(User), new(EmailAddress)}
  21. db := &users{
  22. DB: initTestDB(t, "users", tables...),
  23. }
  24. for _, tc := range []struct {
  25. name string
  26. test func(*testing.T, *users)
  27. }{
  28. {"Authenticate", usersAuthenticate},
  29. {"Create", usersCreate},
  30. {"GetByEmail", usersGetByEmail},
  31. {"GetByID", usersGetByID},
  32. {"GetByUsername", usersGetByUsername},
  33. } {
  34. t.Run(tc.name, func(t *testing.T) {
  35. t.Cleanup(func() {
  36. err := clearTables(t, db.DB, tables...)
  37. require.NoError(t, err)
  38. })
  39. tc.test(t, db)
  40. })
  41. if t.Failed() {
  42. break
  43. }
  44. }
  45. }
  46. func usersAuthenticate(t *testing.T, db *users) {
  47. ctx := context.Background()
  48. password := "pa$$word"
  49. alice, err := db.Create(ctx, "alice", "[email protected]",
  50. CreateUserOpts{
  51. Password: password,
  52. },
  53. )
  54. require.NoError(t, err)
  55. t.Run("user not found", func(t *testing.T) {
  56. _, err := db.Authenticate(ctx, "bob", password, -1)
  57. wantErr := auth.ErrBadCredentials{Args: map[string]interface{}{"login": "bob"}}
  58. assert.Equal(t, wantErr, err)
  59. })
  60. t.Run("invalid password", func(t *testing.T) {
  61. _, err := db.Authenticate(ctx, alice.Name, "bad_password", -1)
  62. wantErr := auth.ErrBadCredentials{Args: map[string]interface{}{"login": alice.Name, "userID": alice.ID}}
  63. assert.Equal(t, wantErr, err)
  64. })
  65. t.Run("via email and password", func(t *testing.T) {
  66. user, err := db.Authenticate(ctx, alice.Email, password, -1)
  67. require.NoError(t, err)
  68. assert.Equal(t, alice.Name, user.Name)
  69. })
  70. t.Run("via username and password", func(t *testing.T) {
  71. user, err := db.Authenticate(ctx, alice.Name, password, -1)
  72. require.NoError(t, err)
  73. assert.Equal(t, alice.Name, user.Name)
  74. })
  75. t.Run("login source mismatch", func(t *testing.T) {
  76. _, err := db.Authenticate(ctx, alice.Email, password, 1)
  77. gotErr := fmt.Sprintf("%v", err)
  78. wantErr := ErrLoginSourceMismatch{args: map[string]interface{}{"actual": 0, "expect": 1}}.Error()
  79. assert.Equal(t, wantErr, gotErr)
  80. })
  81. t.Run("via login source", func(t *testing.T) {
  82. mockLoginSources := NewMockLoginSourcesStore()
  83. mockLoginSources.GetByIDFunc.SetDefaultHook(func(ctx context.Context, id int64) (*LoginSource, error) {
  84. mockProvider := NewMockProvider()
  85. mockProvider.AuthenticateFunc.SetDefaultReturn(&auth.ExternalAccount{}, nil)
  86. s := &LoginSource{
  87. IsActived: true,
  88. Provider: mockProvider,
  89. }
  90. return s, nil
  91. })
  92. setMockLoginSourcesStore(t, mockLoginSources)
  93. bob, err := db.Create(ctx, "bob", "[email protected]",
  94. CreateUserOpts{
  95. Password: password,
  96. LoginSource: 1,
  97. },
  98. )
  99. require.NoError(t, err)
  100. user, err := db.Authenticate(ctx, bob.Email, password, 1)
  101. require.NoError(t, err)
  102. assert.Equal(t, bob.Name, user.Name)
  103. })
  104. t.Run("new user via login source", func(t *testing.T) {
  105. mockLoginSources := NewMockLoginSourcesStore()
  106. mockLoginSources.GetByIDFunc.SetDefaultHook(func(ctx context.Context, id int64) (*LoginSource, error) {
  107. mockProvider := NewMockProvider()
  108. mockProvider.AuthenticateFunc.SetDefaultReturn(
  109. &auth.ExternalAccount{
  110. Name: "cindy",
  111. Email: "[email protected]",
  112. },
  113. nil,
  114. )
  115. s := &LoginSource{
  116. IsActived: true,
  117. Provider: mockProvider,
  118. }
  119. return s, nil
  120. })
  121. setMockLoginSourcesStore(t, mockLoginSources)
  122. user, err := db.Authenticate(ctx, "cindy", password, 1)
  123. require.NoError(t, err)
  124. assert.Equal(t, "cindy", user.Name)
  125. user, err = db.GetByUsername(ctx, "cindy")
  126. require.NoError(t, err)
  127. assert.Equal(t, "[email protected]", user.Email)
  128. })
  129. }
  130. func usersCreate(t *testing.T, db *users) {
  131. ctx := context.Background()
  132. alice, err := db.Create(ctx, "alice", "[email protected]",
  133. CreateUserOpts{
  134. Activated: true,
  135. },
  136. )
  137. require.NoError(t, err)
  138. t.Run("name not allowed", func(t *testing.T) {
  139. _, err := db.Create(ctx, "-", "", CreateUserOpts{})
  140. wantErr := ErrNameNotAllowed{args: errutil.Args{"reason": "reserved", "name": "-"}}
  141. assert.Equal(t, wantErr, err)
  142. })
  143. t.Run("name already exists", func(t *testing.T) {
  144. _, err := db.Create(ctx, alice.Name, "", CreateUserOpts{})
  145. wantErr := ErrUserAlreadyExist{args: errutil.Args{"name": alice.Name}}
  146. assert.Equal(t, wantErr, err)
  147. })
  148. t.Run("email already exists", func(t *testing.T) {
  149. _, err := db.Create(ctx, "bob", alice.Email, CreateUserOpts{})
  150. wantErr := ErrEmailAlreadyUsed{args: errutil.Args{"email": alice.Email}}
  151. assert.Equal(t, wantErr, err)
  152. })
  153. user, err := db.GetByUsername(ctx, alice.Name)
  154. require.NoError(t, err)
  155. assert.Equal(t, db.NowFunc().Format(time.RFC3339), user.Created.UTC().Format(time.RFC3339))
  156. assert.Equal(t, db.NowFunc().Format(time.RFC3339), user.Updated.UTC().Format(time.RFC3339))
  157. }
  158. func usersGetByEmail(t *testing.T, db *users) {
  159. ctx := context.Background()
  160. t.Run("empty email", func(t *testing.T) {
  161. _, err := db.GetByEmail(ctx, "")
  162. wantErr := ErrUserNotExist{args: errutil.Args{"email": ""}}
  163. assert.Equal(t, wantErr, err)
  164. })
  165. t.Run("ignore organization", func(t *testing.T) {
  166. // TODO: Use Orgs.Create to replace SQL hack when the method is available.
  167. org, err := db.Create(ctx, "gogs", "[email protected]", CreateUserOpts{})
  168. require.NoError(t, err)
  169. err = db.Model(&User{}).Where("id", org.ID).UpdateColumn("type", UserOrganization).Error
  170. require.NoError(t, err)
  171. _, err = db.GetByEmail(ctx, org.Email)
  172. wantErr := ErrUserNotExist{args: errutil.Args{"email": org.Email}}
  173. assert.Equal(t, wantErr, err)
  174. })
  175. t.Run("by primary email", func(t *testing.T) {
  176. alice, err := db.Create(ctx, "alice", "[email protected]", CreateUserOpts{})
  177. require.NoError(t, err)
  178. _, err = db.GetByEmail(ctx, alice.Email)
  179. wantErr := ErrUserNotExist{args: errutil.Args{"email": alice.Email}}
  180. assert.Equal(t, wantErr, err)
  181. // Mark user as activated
  182. // TODO: Use UserEmails.Verify to replace SQL hack when the method is available.
  183. err = db.Model(&User{}).Where("id", alice.ID).UpdateColumn("is_active", true).Error
  184. require.NoError(t, err)
  185. user, err := db.GetByEmail(ctx, alice.Email)
  186. require.NoError(t, err)
  187. assert.Equal(t, alice.Name, user.Name)
  188. })
  189. t.Run("by secondary email", func(t *testing.T) {
  190. bob, err := db.Create(ctx, "bob", "[email protected]", CreateUserOpts{})
  191. require.NoError(t, err)
  192. // TODO: Use UserEmails.Create to replace SQL hack when the method is available.
  193. email2 := "[email protected]"
  194. err = db.Exec(`INSERT INTO email_address (uid, email) VALUES (?, ?)`, bob.ID, email2).Error
  195. require.NoError(t, err)
  196. _, err = db.GetByEmail(ctx, email2)
  197. wantErr := ErrUserNotExist{args: errutil.Args{"email": email2}}
  198. assert.Equal(t, wantErr, err)
  199. // TODO: Use UserEmails.Verify to replace SQL hack when the method is available.
  200. err = db.Exec(`UPDATE email_address SET is_activated = ? WHERE email = ?`, true, email2).Error
  201. require.NoError(t, err)
  202. user, err := db.GetByEmail(ctx, email2)
  203. require.NoError(t, err)
  204. assert.Equal(t, bob.Name, user.Name)
  205. })
  206. }
  207. func usersGetByID(t *testing.T, db *users) {
  208. ctx := context.Background()
  209. alice, err := db.Create(ctx, "alice", "[email protected]", CreateUserOpts{})
  210. require.NoError(t, err)
  211. user, err := db.GetByID(ctx, alice.ID)
  212. require.NoError(t, err)
  213. assert.Equal(t, alice.Name, user.Name)
  214. _, err = db.GetByID(ctx, 404)
  215. wantErr := ErrUserNotExist{args: errutil.Args{"userID": int64(404)}}
  216. assert.Equal(t, wantErr, err)
  217. }
  218. func usersGetByUsername(t *testing.T, db *users) {
  219. ctx := context.Background()
  220. alice, err := db.Create(ctx, "alice", "[email protected]", CreateUserOpts{})
  221. require.NoError(t, err)
  222. user, err := db.GetByUsername(ctx, alice.Name)
  223. require.NoError(t, err)
  224. assert.Equal(t, alice.Name, user.Name)
  225. _, err = db.GetByUsername(ctx, "bad_username")
  226. wantErr := ErrUserNotExist{args: errutil.Args{"name": "bad_username"}}
  227. assert.Equal(t, wantErr, err)
  228. }