users_test.go 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408
  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. "os"
  9. "path/filepath"
  10. "strings"
  11. "testing"
  12. "time"
  13. "github.com/stretchr/testify/assert"
  14. "github.com/stretchr/testify/require"
  15. "gorm.io/gorm"
  16. "gogs.io/gogs/internal/auth"
  17. "gogs.io/gogs/internal/conf"
  18. "gogs.io/gogs/internal/dbtest"
  19. "gogs.io/gogs/internal/errutil"
  20. "gogs.io/gogs/internal/osutil"
  21. "gogs.io/gogs/internal/repoutil"
  22. "gogs.io/gogs/internal/userutil"
  23. "gogs.io/gogs/public"
  24. )
  25. func TestUser_BeforeCreate(t *testing.T) {
  26. now := time.Now()
  27. db := &gorm.DB{
  28. Config: &gorm.Config{
  29. SkipDefaultTransaction: true,
  30. NowFunc: func() time.Time {
  31. return now
  32. },
  33. },
  34. }
  35. t.Run("CreatedUnix has been set", func(t *testing.T) {
  36. user := &User{
  37. CreatedUnix: 1,
  38. }
  39. _ = user.BeforeCreate(db)
  40. assert.Equal(t, int64(1), user.CreatedUnix)
  41. assert.Equal(t, int64(0), user.UpdatedUnix)
  42. })
  43. t.Run("CreatedUnix has not been set", func(t *testing.T) {
  44. user := &User{}
  45. _ = user.BeforeCreate(db)
  46. assert.Equal(t, db.NowFunc().Unix(), user.CreatedUnix)
  47. assert.Equal(t, db.NowFunc().Unix(), user.UpdatedUnix)
  48. })
  49. }
  50. func TestUser_AfterFind(t *testing.T) {
  51. now := time.Now()
  52. db := &gorm.DB{
  53. Config: &gorm.Config{
  54. SkipDefaultTransaction: true,
  55. NowFunc: func() time.Time {
  56. return now
  57. },
  58. },
  59. }
  60. user := &User{
  61. FullName: "user1<script src=http://localhost:8181/xss.js>",
  62. CreatedUnix: now.Unix(),
  63. UpdatedUnix: now.Unix(),
  64. }
  65. _ = user.AfterFind(db)
  66. assert.Equal(t, "user1", user.FullName)
  67. assert.Equal(t, user.CreatedUnix, user.Created.Unix())
  68. assert.Equal(t, user.UpdatedUnix, user.Updated.Unix())
  69. }
  70. func TestUsers(t *testing.T) {
  71. if testing.Short() {
  72. t.Skip()
  73. }
  74. t.Parallel()
  75. ctx := context.Background()
  76. tables := []any{
  77. new(User), new(EmailAddress), new(Repository), new(Follow), new(PullRequest), new(PublicKey), new(OrgUser),
  78. new(Watch), new(Star), new(Issue), new(AccessToken), new(Collaboration), new(Action), new(IssueUser),
  79. new(Access), new(Team), new(TeamUser),
  80. }
  81. db := &users{
  82. DB: dbtest.NewDB(t, "users", tables...),
  83. }
  84. for _, tc := range []struct {
  85. name string
  86. test func(t *testing.T, ctx context.Context, db *users)
  87. }{
  88. {"Authenticate", usersAuthenticate},
  89. {"ChangeUsername", usersChangeUsername},
  90. {"Count", usersCount},
  91. {"Create", usersCreate},
  92. {"DeleteCustomAvatar", usersDeleteCustomAvatar},
  93. {"DeleteByID", usersDeleteByID},
  94. {"DeleteInactivated", usersDeleteInactivated},
  95. {"GetByEmail", usersGetByEmail},
  96. {"GetByID", usersGetByID},
  97. {"GetByUsername", usersGetByUsername},
  98. {"GetByKeyID", usersGetByKeyID},
  99. {"GetMailableEmailsByUsernames", usersGetMailableEmailsByUsernames},
  100. {"IsUsernameUsed", usersIsUsernameUsed},
  101. {"List", usersList},
  102. {"ListFollowers", usersListFollowers},
  103. {"ListFollowings", usersListFollowings},
  104. {"SearchByName", usersSearchByName},
  105. {"Update", usersUpdate},
  106. {"UseCustomAvatar", usersUseCustomAvatar},
  107. {"AddEmail", usersAddEmail},
  108. {"GetEmail", usersGetEmail},
  109. {"ListEmails", usersListEmails},
  110. {"MarkEmailActivated", usersMarkEmailActivated},
  111. {"MarkEmailPrimary", usersMarkEmailPrimary},
  112. {"DeleteEmail", usersDeleteEmail},
  113. {"Follow", usersFollow},
  114. {"IsFollowing", usersIsFollowing},
  115. {"Unfollow", usersUnfollow},
  116. } {
  117. t.Run(tc.name, func(t *testing.T) {
  118. t.Cleanup(func() {
  119. err := clearTables(t, db.DB, tables...)
  120. require.NoError(t, err)
  121. })
  122. tc.test(t, ctx, db)
  123. })
  124. if t.Failed() {
  125. break
  126. }
  127. }
  128. }
  129. func usersAuthenticate(t *testing.T, ctx context.Context, db *users) {
  130. password := "pa$$word"
  131. alice, err := db.Create(ctx, "alice", "alice@example.com",
  132. CreateUserOptions{
  133. Password: password,
  134. },
  135. )
  136. require.NoError(t, err)
  137. t.Run("user not found", func(t *testing.T) {
  138. _, err := db.Authenticate(ctx, "bob", password, -1)
  139. wantErr := auth.ErrBadCredentials{Args: map[string]any{"login": "bob"}}
  140. assert.Equal(t, wantErr, err)
  141. })
  142. t.Run("invalid password", func(t *testing.T) {
  143. _, err := db.Authenticate(ctx, alice.Name, "bad_password", -1)
  144. wantErr := auth.ErrBadCredentials{Args: map[string]any{"login": alice.Name, "userID": alice.ID}}
  145. assert.Equal(t, wantErr, err)
  146. })
  147. t.Run("via email and password", func(t *testing.T) {
  148. user, err := db.Authenticate(ctx, alice.Email, password, -1)
  149. require.NoError(t, err)
  150. assert.Equal(t, alice.Name, user.Name)
  151. })
  152. t.Run("via username and password", func(t *testing.T) {
  153. user, err := db.Authenticate(ctx, alice.Name, password, -1)
  154. require.NoError(t, err)
  155. assert.Equal(t, alice.Name, user.Name)
  156. })
  157. t.Run("login source mismatch", func(t *testing.T) {
  158. _, err := db.Authenticate(ctx, alice.Email, password, 1)
  159. gotErr := fmt.Sprintf("%v", err)
  160. wantErr := ErrLoginSourceMismatch{args: map[string]any{"actual": 0, "expect": 1}}.Error()
  161. assert.Equal(t, wantErr, gotErr)
  162. })
  163. t.Run("via login source", func(t *testing.T) {
  164. mockLoginSources := NewMockLoginSourcesStore()
  165. mockLoginSources.GetByIDFunc.SetDefaultHook(func(ctx context.Context, id int64) (*LoginSource, error) {
  166. mockProvider := NewMockProvider()
  167. mockProvider.AuthenticateFunc.SetDefaultReturn(&auth.ExternalAccount{}, nil)
  168. s := &LoginSource{
  169. IsActived: true,
  170. Provider: mockProvider,
  171. }
  172. return s, nil
  173. })
  174. setMockLoginSourcesStore(t, mockLoginSources)
  175. bob, err := db.Create(ctx, "bob", "bob@example.com",
  176. CreateUserOptions{
  177. Password: password,
  178. LoginSource: 1,
  179. },
  180. )
  181. require.NoError(t, err)
  182. user, err := db.Authenticate(ctx, bob.Email, password, 1)
  183. require.NoError(t, err)
  184. assert.Equal(t, bob.Name, user.Name)
  185. })
  186. t.Run("new user via login source", func(t *testing.T) {
  187. mockLoginSources := NewMockLoginSourcesStore()
  188. mockLoginSources.GetByIDFunc.SetDefaultHook(func(ctx context.Context, id int64) (*LoginSource, error) {
  189. mockProvider := NewMockProvider()
  190. mockProvider.AuthenticateFunc.SetDefaultReturn(
  191. &auth.ExternalAccount{
  192. Name: "cindy",
  193. Email: "cindy@example.com",
  194. },
  195. nil,
  196. )
  197. s := &LoginSource{
  198. IsActived: true,
  199. Provider: mockProvider,
  200. }
  201. return s, nil
  202. })
  203. setMockLoginSourcesStore(t, mockLoginSources)
  204. user, err := db.Authenticate(ctx, "cindy", password, 1)
  205. require.NoError(t, err)
  206. assert.Equal(t, "cindy", user.Name)
  207. user, err = db.GetByUsername(ctx, "cindy")
  208. require.NoError(t, err)
  209. assert.Equal(t, "cindy@example.com", user.Email)
  210. })
  211. }
  212. func usersChangeUsername(t *testing.T, ctx context.Context, db *users) {
  213. alice, err := db.Create(
  214. ctx,
  215. "alice",
  216. "alice@example.com",
  217. CreateUserOptions{
  218. Activated: true,
  219. },
  220. )
  221. require.NoError(t, err)
  222. t.Run("name not allowed", func(t *testing.T) {
  223. err := db.ChangeUsername(ctx, alice.ID, "-")
  224. wantErr := ErrNameNotAllowed{
  225. args: errutil.Args{
  226. "reason": "reserved",
  227. "name": "-",
  228. },
  229. }
  230. assert.Equal(t, wantErr, err)
  231. })
  232. t.Run("name already exists", func(t *testing.T) {
  233. bob, err := db.Create(
  234. ctx,
  235. "bob",
  236. "bob@example.com",
  237. CreateUserOptions{
  238. Activated: true,
  239. },
  240. )
  241. require.NoError(t, err)
  242. err = db.ChangeUsername(ctx, alice.ID, bob.Name)
  243. wantErr := ErrUserAlreadyExist{
  244. args: errutil.Args{
  245. "name": bob.Name,
  246. },
  247. }
  248. assert.Equal(t, wantErr, err)
  249. })
  250. tempRepositoryRoot := filepath.Join(os.TempDir(), "usersChangeUsername-tempRepositoryRoot")
  251. conf.SetMockRepository(t, conf.RepositoryOpts{Root: tempRepositoryRoot})
  252. err = os.RemoveAll(tempRepositoryRoot)
  253. require.NoError(t, err)
  254. defer func() { _ = os.RemoveAll(tempRepositoryRoot) }()
  255. tempServerAppDataPath := filepath.Join(os.TempDir(), "usersChangeUsername-tempServerAppDataPath")
  256. conf.SetMockServer(
  257. t,
  258. conf.ServerOpts{
  259. AppDataPath: tempServerAppDataPath,
  260. },
  261. )
  262. err = os.RemoveAll(tempServerAppDataPath)
  263. require.NoError(t, err)
  264. defer func() { _ = os.RemoveAll(tempServerAppDataPath) }()
  265. repo, err := NewRepositoriesStore(db.DB).Create(
  266. ctx,
  267. alice.ID,
  268. CreateRepoOptions{
  269. Name: "test-repo-1",
  270. },
  271. )
  272. require.NoError(t, err)
  273. // TODO: Use PullRequests.Create to replace SQL hack when the method is available.
  274. err = db.Exec(`INSERT INTO pull_request (head_user_name) VALUES (?)`, alice.Name).Error
  275. require.NoError(t, err)
  276. err = db.Model(&User{}).Where("id = ?", alice.ID).Update("updated_unix", 0).Error
  277. require.NoError(t, err)
  278. err = os.MkdirAll(repoutil.UserPath(alice.Name), os.ModePerm)
  279. require.NoError(t, err)
  280. err = os.MkdirAll(repoutil.RepositoryLocalPath(repo.ID), os.ModePerm)
  281. require.NoError(t, err)
  282. err = os.MkdirAll(repoutil.RepositoryLocalWikiPath(repo.ID), os.ModePerm)
  283. require.NoError(t, err)
  284. // Make sure mock data is set up correctly
  285. // TODO: Use PullRequests.GetByID to replace SQL hack when the method is available.
  286. var headUserName string
  287. err = db.Model(&PullRequest{}).Select("head_user_name").Row().Scan(&headUserName)
  288. require.NoError(t, err)
  289. assert.Equal(t, headUserName, alice.Name)
  290. var updatedUnix int64
  291. err = db.Model(&User{}).Select("updated_unix").Where("id = ?", alice.ID).Row().Scan(&updatedUnix)
  292. require.NoError(t, err)
  293. assert.Equal(t, int64(0), updatedUnix)
  294. assert.True(t, osutil.IsExist(repoutil.UserPath(alice.Name)))
  295. assert.True(t, osutil.IsExist(repoutil.RepositoryLocalPath(repo.ID)))
  296. assert.True(t, osutil.IsExist(repoutil.RepositoryLocalWikiPath(repo.ID)))
  297. const newUsername = "alice-new"
  298. err = db.ChangeUsername(ctx, alice.ID, newUsername)
  299. require.NoError(t, err)
  300. // TODO: Use PullRequests.GetByID to replace SQL hack when the method is available.
  301. err = db.Model(&PullRequest{}).Select("head_user_name").Row().Scan(&headUserName)
  302. require.NoError(t, err)
  303. assert.Equal(t, headUserName, newUsername)
  304. assert.True(t, osutil.IsExist(repoutil.UserPath(newUsername)))
  305. assert.False(t, osutil.IsExist(repoutil.UserPath(alice.Name)))
  306. assert.False(t, osutil.IsExist(repoutil.RepositoryLocalPath(repo.ID)))
  307. assert.False(t, osutil.IsExist(repoutil.RepositoryLocalWikiPath(repo.ID)))
  308. alice, err = db.GetByID(ctx, alice.ID)
  309. require.NoError(t, err)
  310. assert.Equal(t, newUsername, alice.Name)
  311. assert.Equal(t, db.NowFunc().Unix(), alice.UpdatedUnix)
  312. // Change the cases of the username should just be fine
  313. err = db.ChangeUsername(ctx, alice.ID, strings.ToUpper(newUsername))
  314. require.NoError(t, err)
  315. alice, err = db.GetByID(ctx, alice.ID)
  316. require.NoError(t, err)
  317. assert.Equal(t, strings.ToUpper(newUsername), alice.Name)
  318. }
  319. func usersCount(t *testing.T, ctx context.Context, db *users) {
  320. // Has no user initially
  321. got := db.Count(ctx)
  322. assert.Equal(t, int64(0), got)
  323. _, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  324. require.NoError(t, err)
  325. got = db.Count(ctx)
  326. assert.Equal(t, int64(1), got)
  327. tempPictureAvatarUploadPath := filepath.Join(os.TempDir(), "usersCount-tempPictureAvatarUploadPath")
  328. conf.SetMockPicture(t, conf.PictureOpts{AvatarUploadPath: tempPictureAvatarUploadPath})
  329. // Create an organization shouldn't count
  330. _, err = NewOrganizationsStore(db.DB).Create(ctx, "org1", 1, CreateOrganizationOptions{})
  331. require.NoError(t, err)
  332. got = db.Count(ctx)
  333. assert.Equal(t, int64(1), got)
  334. }
  335. func usersCreate(t *testing.T, ctx context.Context, db *users) {
  336. alice, err := db.Create(
  337. ctx,
  338. "alice",
  339. "alice@example.com",
  340. CreateUserOptions{
  341. FullName: "Alice Jones",
  342. Location: "Earth",
  343. Website: "alice@example.com",
  344. Activated: true,
  345. },
  346. )
  347. require.NoError(t, err)
  348. t.Run("name not allowed", func(t *testing.T) {
  349. _, err := db.Create(ctx, "-", "", CreateUserOptions{})
  350. wantErr := ErrNameNotAllowed{
  351. args: errutil.Args{
  352. "reason": "reserved",
  353. "name": "-",
  354. },
  355. }
  356. assert.Equal(t, wantErr, err)
  357. })
  358. t.Run("name already exists", func(t *testing.T) {
  359. _, err := db.Create(ctx, alice.Name, "", CreateUserOptions{})
  360. wantErr := ErrUserAlreadyExist{
  361. args: errutil.Args{
  362. "name": alice.Name,
  363. },
  364. }
  365. assert.Equal(t, wantErr, err)
  366. })
  367. t.Run("email already exists", func(t *testing.T) {
  368. _, err := db.Create(ctx, "bob", alice.Email, CreateUserOptions{})
  369. wantErr := ErrEmailAlreadyUsed{
  370. args: errutil.Args{
  371. "email": alice.Email,
  372. },
  373. }
  374. assert.Equal(t, wantErr, err)
  375. })
  376. got, err := db.GetByUsername(ctx, alice.Name)
  377. require.NoError(t, err)
  378. assert.Equal(t, alice.Name, got.Name)
  379. assert.Equal(t, alice.FullName, got.FullName)
  380. assert.Equal(t, alice.Location, got.Location)
  381. assert.Equal(t, alice.Website, got.Website)
  382. assert.Equal(t, db.NowFunc().Format(time.RFC3339), got.Created.UTC().Format(time.RFC3339))
  383. assert.Equal(t, db.NowFunc().Format(time.RFC3339), got.Updated.UTC().Format(time.RFC3339))
  384. }
  385. func usersDeleteCustomAvatar(t *testing.T, ctx context.Context, db *users) {
  386. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  387. require.NoError(t, err)
  388. avatar, err := public.Files.ReadFile("img/avatar_default.png")
  389. require.NoError(t, err)
  390. tempPictureAvatarUploadPath := filepath.Join(os.TempDir(), "usersDeleteCustomAvatar-tempPictureAvatarUploadPath")
  391. conf.SetMockPicture(t, conf.PictureOpts{AvatarUploadPath: tempPictureAvatarUploadPath})
  392. avatarPath := userutil.CustomAvatarPath(alice.ID)
  393. _ = os.Remove(avatarPath)
  394. defer func() { _ = os.Remove(avatarPath) }()
  395. err = db.UseCustomAvatar(ctx, alice.ID, avatar)
  396. require.NoError(t, err)
  397. // Make sure avatar is saved and the user flag is updated.
  398. got := osutil.IsFile(avatarPath)
  399. assert.True(t, got)
  400. alice, err = db.GetByID(ctx, alice.ID)
  401. require.NoError(t, err)
  402. assert.True(t, alice.UseCustomAvatar)
  403. // Delete avatar should remove the file and revert the user flag.
  404. err = db.DeleteCustomAvatar(ctx, alice.ID)
  405. require.NoError(t, err)
  406. got = osutil.IsFile(avatarPath)
  407. assert.False(t, got)
  408. alice, err = db.GetByID(ctx, alice.ID)
  409. require.NoError(t, err)
  410. assert.False(t, alice.UseCustomAvatar)
  411. }
  412. func usersDeleteByID(t *testing.T, ctx context.Context, db *users) {
  413. reposStore := NewRepositoriesStore(db.DB)
  414. t.Run("user still has repository ownership", func(t *testing.T) {
  415. alice, err := db.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
  416. require.NoError(t, err)
  417. _, err = reposStore.Create(ctx, alice.ID, CreateRepoOptions{Name: "repo1"})
  418. require.NoError(t, err)
  419. err = db.DeleteByID(ctx, alice.ID, false)
  420. wantErr := ErrUserOwnRepos{errutil.Args{"userID": alice.ID}}
  421. assert.Equal(t, wantErr, err)
  422. })
  423. tempPictureAvatarUploadPath := filepath.Join(os.TempDir(), "usersDeleteByID-tempPictureAvatarUploadPath")
  424. conf.SetMockPicture(t, conf.PictureOpts{AvatarUploadPath: tempPictureAvatarUploadPath})
  425. t.Run("user still has organization membership", func(t *testing.T) {
  426. bob, err := db.Create(ctx, "bob", "bob@exmaple.com", CreateUserOptions{})
  427. require.NoError(t, err)
  428. _, err = NewOrganizationsStore(db.DB).Create(ctx, "org1", bob.ID, CreateOrganizationOptions{})
  429. require.NoError(t, err)
  430. err = db.DeleteByID(ctx, bob.ID, false)
  431. wantErr := ErrUserHasOrgs{errutil.Args{"userID": bob.ID}}
  432. assert.Equal(t, wantErr, err)
  433. })
  434. cindy, err := db.Create(ctx, "cindy", "cindy@exmaple.com", CreateUserOptions{})
  435. require.NoError(t, err)
  436. frank, err := db.Create(ctx, "frank", "frank@exmaple.com", CreateUserOptions{})
  437. require.NoError(t, err)
  438. repo2, err := reposStore.Create(ctx, cindy.ID, CreateRepoOptions{Name: "repo2"})
  439. require.NoError(t, err)
  440. testUser, err := db.Create(ctx, "testUser", "testUser@exmaple.com", CreateUserOptions{})
  441. require.NoError(t, err)
  442. // Mock watches, stars and follows
  443. err = reposStore.Watch(
  444. ctx,
  445. WatchRepositoryOptions{
  446. UserID: testUser.ID,
  447. RepoID: repo2.ID,
  448. RepoOwnerID: repo2.OwnerID,
  449. RepoIsPrivate: repo2.IsPrivate,
  450. },
  451. )
  452. require.NoError(t, err)
  453. err = reposStore.Star(ctx, testUser.ID, repo2.ID)
  454. require.NoError(t, err)
  455. err = db.Follow(ctx, testUser.ID, cindy.ID)
  456. require.NoError(t, err)
  457. err = db.Follow(ctx, frank.ID, testUser.ID)
  458. require.NoError(t, err)
  459. // Mock "authorized_keys" file
  460. // TODO: Use PublicKeys.Add to replace SQL hack when the method is available.
  461. publicKey := &PublicKey{
  462. OwnerID: testUser.ID,
  463. Name: "test-key",
  464. Fingerprint: "12:f8:7e:78:61:b4:bf:e2:de:24:15:96:4e:d4:72:53",
  465. Content: "test-key-content",
  466. }
  467. err = db.DB.Create(publicKey).Error
  468. require.NoError(t, err)
  469. tempSSHRootPath := filepath.Join(os.TempDir(), "usersDeleteByID-tempSSHRootPath")
  470. conf.SetMockSSH(t, conf.SSHOpts{RootPath: tempSSHRootPath})
  471. err = NewPublicKeysStore(db.DB).RewriteAuthorizedKeys()
  472. require.NoError(t, err)
  473. // Mock issue assignee
  474. // TODO: Use Issues.Assign to replace SQL hack when the method is available.
  475. issue := &Issue{
  476. RepoID: repo2.ID,
  477. Index: 1,
  478. PosterID: cindy.ID,
  479. Title: "test-issue",
  480. AssigneeID: testUser.ID,
  481. }
  482. err = db.DB.Create(issue).Error
  483. require.NoError(t, err)
  484. // Mock random entries in related tables
  485. for _, table := range []any{
  486. &AccessToken{UserID: testUser.ID},
  487. &Collaboration{UserID: testUser.ID},
  488. &Access{UserID: testUser.ID},
  489. &Action{UserID: testUser.ID},
  490. &IssueUser{UserID: testUser.ID},
  491. &EmailAddress{UserID: testUser.ID},
  492. } {
  493. err = db.DB.Create(table).Error
  494. require.NoError(t, err, "table for %T", table)
  495. }
  496. // Mock user directory
  497. tempRepositoryRoot := filepath.Join(os.TempDir(), "usersDeleteByID-tempRepositoryRoot")
  498. conf.SetMockRepository(t, conf.RepositoryOpts{Root: tempRepositoryRoot})
  499. tempUserPath := repoutil.UserPath(testUser.Name)
  500. err = os.MkdirAll(tempUserPath, os.ModePerm)
  501. require.NoError(t, err)
  502. // Mock user custom avatar
  503. err = os.MkdirAll(tempPictureAvatarUploadPath, os.ModePerm)
  504. require.NoError(t, err)
  505. tempCustomAvatarPath := userutil.CustomAvatarPath(testUser.ID)
  506. err = os.WriteFile(tempCustomAvatarPath, []byte("test"), 0600)
  507. require.NoError(t, err)
  508. // Verify mock data
  509. repo2, err = reposStore.GetByID(ctx, repo2.ID)
  510. require.NoError(t, err)
  511. assert.Equal(t, 2, repo2.NumWatches) // The owner is watching the repo by default.
  512. assert.Equal(t, 1, repo2.NumStars)
  513. cindy, err = db.GetByID(ctx, cindy.ID)
  514. require.NoError(t, err)
  515. assert.Equal(t, 1, cindy.NumFollowers)
  516. frank, err = db.GetByID(ctx, frank.ID)
  517. require.NoError(t, err)
  518. assert.Equal(t, 1, frank.NumFollowing)
  519. authorizedKeys, err := os.ReadFile(authorizedKeysPath())
  520. require.NoError(t, err)
  521. assert.Contains(t, string(authorizedKeys), fmt.Sprintf("key-%d", publicKey.ID))
  522. assert.Contains(t, string(authorizedKeys), publicKey.Content)
  523. // TODO: Use Issues.GetByID to replace SQL hack when the method is available.
  524. err = db.DB.First(issue, issue.ID).Error
  525. require.NoError(t, err)
  526. assert.Equal(t, testUser.ID, issue.AssigneeID)
  527. relatedTables := []any{
  528. &Watch{UserID: testUser.ID},
  529. &Star{UserID: testUser.ID},
  530. &Follow{UserID: testUser.ID},
  531. &PublicKey{OwnerID: testUser.ID},
  532. &AccessToken{UserID: testUser.ID},
  533. &Collaboration{UserID: testUser.ID},
  534. &Access{UserID: testUser.ID},
  535. &Action{UserID: testUser.ID},
  536. &IssueUser{UserID: testUser.ID},
  537. &EmailAddress{UserID: testUser.ID},
  538. }
  539. for _, table := range relatedTables {
  540. var count int64
  541. err = db.DB.Model(table).Where(table).Count(&count).Error
  542. require.NoError(t, err, "table for %T", table)
  543. assert.NotZero(t, count, "table for %T", table)
  544. }
  545. assert.True(t, osutil.IsExist(tempUserPath))
  546. assert.True(t, osutil.IsExist(tempCustomAvatarPath))
  547. // Pull the trigger
  548. err = db.DeleteByID(ctx, testUser.ID, false)
  549. require.NoError(t, err)
  550. // Verify after-the-fact data
  551. repo2, err = reposStore.GetByID(ctx, repo2.ID)
  552. require.NoError(t, err)
  553. assert.Equal(t, 1, repo2.NumWatches) // The owner is watching the repo by default.
  554. assert.Equal(t, 0, repo2.NumStars)
  555. cindy, err = db.GetByID(ctx, cindy.ID)
  556. require.NoError(t, err)
  557. assert.Equal(t, 0, cindy.NumFollowers)
  558. frank, err = db.GetByID(ctx, frank.ID)
  559. require.NoError(t, err)
  560. assert.Equal(t, 0, frank.NumFollowing)
  561. authorizedKeys, err = os.ReadFile(authorizedKeysPath())
  562. require.NoError(t, err)
  563. assert.Empty(t, authorizedKeys)
  564. // TODO: Use Issues.GetByID to replace SQL hack when the method is available.
  565. err = db.DB.First(issue, issue.ID).Error
  566. require.NoError(t, err)
  567. assert.Equal(t, int64(0), issue.AssigneeID)
  568. for _, table := range []any{
  569. &Watch{UserID: testUser.ID},
  570. &Star{UserID: testUser.ID},
  571. &Follow{UserID: testUser.ID},
  572. &PublicKey{OwnerID: testUser.ID},
  573. &AccessToken{UserID: testUser.ID},
  574. &Collaboration{UserID: testUser.ID},
  575. &Access{UserID: testUser.ID},
  576. &Action{UserID: testUser.ID},
  577. &IssueUser{UserID: testUser.ID},
  578. &EmailAddress{UserID: testUser.ID},
  579. } {
  580. var count int64
  581. err = db.DB.Model(table).Where(table).Count(&count).Error
  582. require.NoError(t, err, "table for %T", table)
  583. assert.Equal(t, int64(0), count, "table for %T", table)
  584. }
  585. assert.False(t, osutil.IsExist(tempUserPath))
  586. assert.False(t, osutil.IsExist(tempCustomAvatarPath))
  587. _, err = db.GetByID(ctx, testUser.ID)
  588. wantErr := ErrUserNotExist{errutil.Args{"userID": testUser.ID}}
  589. assert.Equal(t, wantErr, err)
  590. }
  591. func usersDeleteInactivated(t *testing.T, ctx context.Context, db *users) {
  592. // User with repository ownership should be skipped
  593. alice, err := db.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
  594. require.NoError(t, err)
  595. reposStore := NewRepositoriesStore(db.DB)
  596. _, err = reposStore.Create(ctx, alice.ID, CreateRepoOptions{Name: "repo1"})
  597. require.NoError(t, err)
  598. // User with organization membership should be skipped
  599. bob, err := db.Create(ctx, "bob", "bob@exmaple.com", CreateUserOptions{})
  600. require.NoError(t, err)
  601. tempPictureAvatarUploadPath := filepath.Join(os.TempDir(), "usersDeleteInactivated-tempPictureAvatarUploadPath")
  602. conf.SetMockPicture(t, conf.PictureOpts{AvatarUploadPath: tempPictureAvatarUploadPath})
  603. _, err = NewOrganizationsStore(db.DB).Create(ctx, "org1", bob.ID, CreateOrganizationOptions{})
  604. require.NoError(t, err)
  605. // User activated state should be skipped
  606. _, err = db.Create(ctx, "cindy", "cindy@exmaple.com", CreateUserOptions{Activated: true})
  607. require.NoError(t, err)
  608. // User meant to be deleted
  609. david, err := db.Create(ctx, "david", "david@exmaple.com", CreateUserOptions{})
  610. require.NoError(t, err)
  611. tempSSHRootPath := filepath.Join(os.TempDir(), "usersDeleteInactivated-tempSSHRootPath")
  612. conf.SetMockSSH(t, conf.SSHOpts{RootPath: tempSSHRootPath})
  613. err = db.DeleteInactivated()
  614. require.NoError(t, err)
  615. _, err = db.GetByID(ctx, david.ID)
  616. wantErr := ErrUserNotExist{errutil.Args{"userID": david.ID}}
  617. assert.Equal(t, wantErr, err)
  618. users, err := db.List(ctx, 1, 10)
  619. require.NoError(t, err)
  620. require.Len(t, users, 3)
  621. }
  622. func usersGetByEmail(t *testing.T, ctx context.Context, db *users) {
  623. t.Run("empty email", func(t *testing.T) {
  624. _, err := db.GetByEmail(ctx, "")
  625. wantErr := ErrUserNotExist{args: errutil.Args{"email": ""}}
  626. assert.Equal(t, wantErr, err)
  627. })
  628. t.Run("ignore organization", func(t *testing.T) {
  629. tempPictureAvatarUploadPath := filepath.Join(os.TempDir(), "usersGetByEmail-tempPictureAvatarUploadPath")
  630. conf.SetMockPicture(t, conf.PictureOpts{AvatarUploadPath: tempPictureAvatarUploadPath})
  631. org, err := NewOrganizationsStore(db.DB).Create(ctx, "gogs", 1, CreateOrganizationOptions{Email: "gogs@example.com"})
  632. require.NoError(t, err)
  633. _, err = db.GetByEmail(ctx, org.Email)
  634. wantErr := ErrUserNotExist{args: errutil.Args{"email": org.Email}}
  635. assert.Equal(t, wantErr, err)
  636. })
  637. t.Run("by primary email", func(t *testing.T) {
  638. alice, err := db.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
  639. require.NoError(t, err)
  640. _, err = db.GetByEmail(ctx, alice.Email)
  641. wantErr := ErrUserNotExist{args: errutil.Args{"email": alice.Email}}
  642. assert.Equal(t, wantErr, err)
  643. // Mark user as activated
  644. // TODO: Use UserEmails.Verify to replace SQL hack when the method is available.
  645. err = db.Model(&User{}).Where("id", alice.ID).UpdateColumn("is_active", true).Error
  646. require.NoError(t, err)
  647. user, err := db.GetByEmail(ctx, alice.Email)
  648. require.NoError(t, err)
  649. assert.Equal(t, alice.Name, user.Name)
  650. })
  651. t.Run("by secondary email", func(t *testing.T) {
  652. bob, err := db.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
  653. require.NoError(t, err)
  654. // TODO: Use UserEmails.Create to replace SQL hack when the method is available.
  655. email2 := "bob2@exmaple.com"
  656. err = db.Exec(`INSERT INTO email_address (uid, email) VALUES (?, ?)`, bob.ID, email2).Error
  657. require.NoError(t, err)
  658. _, err = db.GetByEmail(ctx, email2)
  659. wantErr := ErrUserNotExist{args: errutil.Args{"email": email2}}
  660. assert.Equal(t, wantErr, err)
  661. // TODO: Use UserEmails.Verify to replace SQL hack when the method is available.
  662. err = db.Exec(`UPDATE email_address SET is_activated = ? WHERE email = ?`, true, email2).Error
  663. require.NoError(t, err)
  664. user, err := db.GetByEmail(ctx, email2)
  665. require.NoError(t, err)
  666. assert.Equal(t, bob.Name, user.Name)
  667. })
  668. }
  669. func usersGetByID(t *testing.T, ctx context.Context, db *users) {
  670. alice, err := db.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
  671. require.NoError(t, err)
  672. user, err := db.GetByID(ctx, alice.ID)
  673. require.NoError(t, err)
  674. assert.Equal(t, alice.Name, user.Name)
  675. _, err = db.GetByID(ctx, 404)
  676. wantErr := ErrUserNotExist{args: errutil.Args{"userID": int64(404)}}
  677. assert.Equal(t, wantErr, err)
  678. }
  679. func usersGetByUsername(t *testing.T, ctx context.Context, db *users) {
  680. t.Run("correct user type", func(t *testing.T) {
  681. alice, err := db.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
  682. require.NoError(t, err)
  683. got, err := db.GetByUsername(ctx, alice.Name)
  684. require.NoError(t, err)
  685. assert.Equal(t, alice.Name, got.Name)
  686. _, err = db.GetByUsername(ctx, "bad_username")
  687. wantErr := ErrUserNotExist{args: errutil.Args{"name": "bad_username"}}
  688. assert.Equal(t, wantErr, err)
  689. })
  690. t.Run("wrong user type", func(t *testing.T) {
  691. tempPictureAvatarUploadPath := filepath.Join(os.TempDir(), "usersGetByUsername-tempPictureAvatarUploadPath")
  692. conf.SetMockPicture(t, conf.PictureOpts{AvatarUploadPath: tempPictureAvatarUploadPath})
  693. org1, err := NewOrganizationsStore(db.DB).Create(ctx, "org1", 1, CreateOrganizationOptions{})
  694. require.NoError(t, err)
  695. _, err = db.GetByUsername(ctx, org1.Name)
  696. wantErr := ErrUserNotExist{args: errutil.Args{"name": org1.Name}}
  697. assert.Equal(t, wantErr, err)
  698. })
  699. }
  700. func usersGetByKeyID(t *testing.T, ctx context.Context, db *users) {
  701. alice, err := db.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
  702. require.NoError(t, err)
  703. // TODO: Use PublicKeys.Create to replace SQL hack when the method is available.
  704. publicKey := &PublicKey{
  705. OwnerID: alice.ID,
  706. Name: "test-key",
  707. Fingerprint: "12:f8:7e:78:61:b4:bf:e2:de:24:15:96:4e:d4:72:53",
  708. Content: "test-key-content",
  709. CreatedUnix: db.NowFunc().Unix(),
  710. UpdatedUnix: db.NowFunc().Unix(),
  711. }
  712. err = db.WithContext(ctx).Create(publicKey).Error
  713. require.NoError(t, err)
  714. user, err := db.GetByKeyID(ctx, publicKey.ID)
  715. require.NoError(t, err)
  716. assert.Equal(t, alice.Name, user.Name)
  717. _, err = db.GetByKeyID(ctx, publicKey.ID+1)
  718. wantErr := ErrUserNotExist{args: errutil.Args{"keyID": publicKey.ID + 1}}
  719. assert.Equal(t, wantErr, err)
  720. }
  721. func usersGetMailableEmailsByUsernames(t *testing.T, ctx context.Context, db *users) {
  722. alice, err := db.Create(ctx, "alice", "alice@exmaple.com", CreateUserOptions{})
  723. require.NoError(t, err)
  724. bob, err := db.Create(ctx, "bob", "bob@exmaple.com", CreateUserOptions{Activated: true})
  725. require.NoError(t, err)
  726. _, err = db.Create(ctx, "cindy", "cindy@exmaple.com", CreateUserOptions{Activated: true})
  727. require.NoError(t, err)
  728. got, err := db.GetMailableEmailsByUsernames(ctx, []string{alice.Name, bob.Name, "ignore-non-exist"})
  729. require.NoError(t, err)
  730. want := []string{bob.Email}
  731. assert.Equal(t, want, got)
  732. }
  733. func usersIsUsernameUsed(t *testing.T, ctx context.Context, db *users) {
  734. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  735. require.NoError(t, err)
  736. tests := []struct {
  737. name string
  738. username string
  739. excludeUserID int64
  740. want bool
  741. }{
  742. {
  743. name: "no change",
  744. username: alice.Name,
  745. excludeUserID: alice.ID,
  746. want: false,
  747. },
  748. {
  749. name: "change case",
  750. username: strings.ToUpper(alice.Name),
  751. excludeUserID: alice.ID,
  752. want: false,
  753. },
  754. {
  755. name: "not used",
  756. username: "bob",
  757. excludeUserID: alice.ID,
  758. want: false,
  759. },
  760. {
  761. name: "not used when not excluded",
  762. username: "bob",
  763. excludeUserID: 0,
  764. want: false,
  765. },
  766. {
  767. name: "used when not excluded",
  768. username: alice.Name,
  769. excludeUserID: 0,
  770. want: true,
  771. },
  772. }
  773. for _, test := range tests {
  774. t.Run(test.name, func(t *testing.T) {
  775. got := db.IsUsernameUsed(ctx, test.username, test.excludeUserID)
  776. assert.Equal(t, test.want, got)
  777. })
  778. }
  779. }
  780. func usersList(t *testing.T, ctx context.Context, db *users) {
  781. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  782. require.NoError(t, err)
  783. bob, err := db.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
  784. require.NoError(t, err)
  785. // Create an organization shouldn't count
  786. tempPictureAvatarUploadPath := filepath.Join(os.TempDir(), "usersList-tempPictureAvatarUploadPath")
  787. conf.SetMockPicture(t, conf.PictureOpts{AvatarUploadPath: tempPictureAvatarUploadPath})
  788. _, err = NewOrganizationsStore(db.DB).Create(ctx, "org1", bob.ID, CreateOrganizationOptions{})
  789. require.NoError(t, err)
  790. got, err := db.List(ctx, 1, 1)
  791. require.NoError(t, err)
  792. require.Len(t, got, 1)
  793. assert.Equal(t, alice.ID, got[0].ID)
  794. got, err = db.List(ctx, 2, 1)
  795. require.NoError(t, err)
  796. require.Len(t, got, 1)
  797. assert.Equal(t, bob.ID, got[0].ID)
  798. got, err = db.List(ctx, 1, 3)
  799. require.NoError(t, err)
  800. require.Len(t, got, 2)
  801. assert.Equal(t, alice.ID, got[0].ID)
  802. assert.Equal(t, bob.ID, got[1].ID)
  803. }
  804. func usersListFollowers(t *testing.T, ctx context.Context, db *users) {
  805. john, err := db.Create(ctx, "john", "john@example.com", CreateUserOptions{})
  806. require.NoError(t, err)
  807. got, err := db.ListFollowers(ctx, john.ID, 1, 1)
  808. require.NoError(t, err)
  809. assert.Empty(t, got)
  810. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  811. require.NoError(t, err)
  812. bob, err := db.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
  813. require.NoError(t, err)
  814. err = db.Follow(ctx, alice.ID, john.ID)
  815. require.NoError(t, err)
  816. err = db.Follow(ctx, bob.ID, john.ID)
  817. require.NoError(t, err)
  818. // First page only has bob
  819. got, err = db.ListFollowers(ctx, john.ID, 1, 1)
  820. require.NoError(t, err)
  821. require.Len(t, got, 1)
  822. assert.Equal(t, bob.ID, got[0].ID)
  823. // Second page only has alice
  824. got, err = db.ListFollowers(ctx, john.ID, 2, 1)
  825. require.NoError(t, err)
  826. require.Len(t, got, 1)
  827. assert.Equal(t, alice.ID, got[0].ID)
  828. }
  829. func usersListFollowings(t *testing.T, ctx context.Context, db *users) {
  830. john, err := db.Create(ctx, "john", "john@example.com", CreateUserOptions{})
  831. require.NoError(t, err)
  832. got, err := db.ListFollowers(ctx, john.ID, 1, 1)
  833. require.NoError(t, err)
  834. assert.Empty(t, got)
  835. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  836. require.NoError(t, err)
  837. bob, err := db.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
  838. require.NoError(t, err)
  839. err = db.Follow(ctx, john.ID, alice.ID)
  840. require.NoError(t, err)
  841. err = db.Follow(ctx, john.ID, bob.ID)
  842. require.NoError(t, err)
  843. // First page only has bob
  844. got, err = db.ListFollowings(ctx, john.ID, 1, 1)
  845. require.NoError(t, err)
  846. require.Len(t, got, 1)
  847. assert.Equal(t, bob.ID, got[0].ID)
  848. // Second page only has alice
  849. got, err = db.ListFollowings(ctx, john.ID, 2, 1)
  850. require.NoError(t, err)
  851. require.Len(t, got, 1)
  852. assert.Equal(t, alice.ID, got[0].ID)
  853. }
  854. func usersSearchByName(t *testing.T, ctx context.Context, db *users) {
  855. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{FullName: "Alice Jordan"})
  856. require.NoError(t, err)
  857. bob, err := db.Create(ctx, "bob", "bob@example.com", CreateUserOptions{FullName: "Bob Jordan"})
  858. require.NoError(t, err)
  859. t.Run("search for username alice", func(t *testing.T) {
  860. users, count, err := db.SearchByName(ctx, "Li", 1, 1, "")
  861. require.NoError(t, err)
  862. require.Len(t, users, int(count))
  863. assert.Equal(t, int64(1), count)
  864. assert.Equal(t, alice.ID, users[0].ID)
  865. })
  866. t.Run("search for username bob", func(t *testing.T) {
  867. users, count, err := db.SearchByName(ctx, "oB", 1, 1, "")
  868. require.NoError(t, err)
  869. require.Len(t, users, int(count))
  870. assert.Equal(t, int64(1), count)
  871. assert.Equal(t, bob.ID, users[0].ID)
  872. })
  873. t.Run("search for full name jordan", func(t *testing.T) {
  874. users, count, err := db.SearchByName(ctx, "Jo", 1, 10, "")
  875. require.NoError(t, err)
  876. require.Len(t, users, int(count))
  877. assert.Equal(t, int64(2), count)
  878. })
  879. t.Run("search for full name jordan ORDER BY id DESC LIMIT 1", func(t *testing.T) {
  880. users, count, err := db.SearchByName(ctx, "Jo", 1, 1, "id DESC")
  881. require.NoError(t, err)
  882. require.Len(t, users, 1)
  883. assert.Equal(t, int64(2), count)
  884. assert.Equal(t, bob.ID, users[0].ID)
  885. })
  886. }
  887. func usersUpdate(t *testing.T, ctx context.Context, db *users) {
  888. const oldPassword = "Password"
  889. alice, err := db.Create(
  890. ctx,
  891. "alice",
  892. "alice@example.com",
  893. CreateUserOptions{
  894. FullName: "FullName",
  895. Password: oldPassword,
  896. LoginSource: 9,
  897. LoginName: "LoginName",
  898. Location: "Location",
  899. Website: "Website",
  900. Activated: false,
  901. Admin: false,
  902. },
  903. )
  904. require.NoError(t, err)
  905. t.Run("update password", func(t *testing.T) {
  906. got := userutil.ValidatePassword(alice.Password, alice.Salt, oldPassword)
  907. require.True(t, got)
  908. newPassword := "NewPassword"
  909. err = db.Update(ctx, alice.ID, UpdateUserOptions{Password: &newPassword})
  910. require.NoError(t, err)
  911. alice, err = db.GetByID(ctx, alice.ID)
  912. require.NoError(t, err)
  913. got = userutil.ValidatePassword(alice.Password, alice.Salt, oldPassword)
  914. assert.False(t, got, "Old password should stop working")
  915. got = userutil.ValidatePassword(alice.Password, alice.Salt, newPassword)
  916. assert.True(t, got, "New password should work")
  917. })
  918. t.Run("update email but already used", func(t *testing.T) {
  919. bob, err := db.Create(
  920. ctx,
  921. "bob",
  922. "bob@example.com",
  923. CreateUserOptions{
  924. Activated: true,
  925. },
  926. )
  927. require.NoError(t, err)
  928. got := db.Update(ctx, alice.ID, UpdateUserOptions{Email: &bob.Email})
  929. want := ErrEmailAlreadyUsed{args: errutil.Args{"email": bob.Email}}
  930. assert.Equal(t, want, got)
  931. })
  932. loginSource := int64(1)
  933. maxRepoCreation := 99
  934. lastRepoVisibility := true
  935. overLimitStr := strings.Repeat("a", 2050)
  936. opts := UpdateUserOptions{
  937. LoginSource: &loginSource,
  938. LoginName: &alice.Name,
  939. FullName: &overLimitStr,
  940. Website: &overLimitStr,
  941. Location: &overLimitStr,
  942. Description: &overLimitStr,
  943. MaxRepoCreation: &maxRepoCreation,
  944. LastRepoVisibility: &lastRepoVisibility,
  945. IsActivated: &lastRepoVisibility,
  946. IsAdmin: &lastRepoVisibility,
  947. AllowGitHook: &lastRepoVisibility,
  948. AllowImportLocal: &lastRepoVisibility,
  949. ProhibitLogin: &lastRepoVisibility,
  950. Avatar: &overLimitStr,
  951. AvatarEmail: &overLimitStr,
  952. }
  953. err = db.Update(ctx, alice.ID, opts)
  954. require.NoError(t, err)
  955. alice, err = db.GetByID(ctx, alice.ID)
  956. require.NoError(t, err)
  957. assertValues := func() {
  958. assert.Equal(t, loginSource, alice.LoginSource)
  959. assert.Equal(t, alice.Name, alice.LoginName)
  960. wantStr255 := strings.Repeat("a", 255)
  961. assert.Equal(t, wantStr255, alice.FullName)
  962. assert.Equal(t, wantStr255, alice.Website)
  963. assert.Equal(t, wantStr255, alice.Location)
  964. assert.Equal(t, wantStr255, alice.Description)
  965. assert.Equal(t, maxRepoCreation, alice.MaxRepoCreation)
  966. assert.Equal(t, lastRepoVisibility, alice.LastRepoVisibility)
  967. assert.Equal(t, lastRepoVisibility, alice.IsActive)
  968. assert.Equal(t, lastRepoVisibility, alice.IsAdmin)
  969. assert.Equal(t, lastRepoVisibility, alice.AllowGitHook)
  970. assert.Equal(t, lastRepoVisibility, alice.AllowImportLocal)
  971. assert.Equal(t, lastRepoVisibility, alice.ProhibitLogin)
  972. wantStr2048 := strings.Repeat("a", 2048)
  973. assert.Equal(t, wantStr2048, alice.Avatar)
  974. assert.Equal(t, wantStr255, alice.AvatarEmail)
  975. }
  976. assertValues()
  977. // Test ignored values
  978. err = db.Update(ctx, alice.ID, UpdateUserOptions{})
  979. require.NoError(t, err)
  980. alice, err = db.GetByID(ctx, alice.ID)
  981. require.NoError(t, err)
  982. assertValues()
  983. }
  984. func usersUseCustomAvatar(t *testing.T, ctx context.Context, db *users) {
  985. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  986. require.NoError(t, err)
  987. avatar, err := public.Files.ReadFile("img/avatar_default.png")
  988. require.NoError(t, err)
  989. avatarPath := userutil.CustomAvatarPath(alice.ID)
  990. _ = os.Remove(avatarPath)
  991. defer func() { _ = os.Remove(avatarPath) }()
  992. err = db.UseCustomAvatar(ctx, alice.ID, avatar)
  993. require.NoError(t, err)
  994. // Make sure avatar is saved and the user flag is updated.
  995. got := osutil.IsFile(avatarPath)
  996. assert.True(t, got)
  997. alice, err = db.GetByID(ctx, alice.ID)
  998. require.NoError(t, err)
  999. assert.True(t, alice.UseCustomAvatar)
  1000. }
  1001. func TestIsUsernameAllowed(t *testing.T) {
  1002. for name := range reservedUsernames {
  1003. t.Run(name, func(t *testing.T) {
  1004. assert.True(t, IsErrNameNotAllowed(isUsernameAllowed(name)))
  1005. })
  1006. }
  1007. for _, pattern := range reservedUsernamePatterns {
  1008. t.Run(pattern, func(t *testing.T) {
  1009. username := strings.ReplaceAll(pattern, "*", "alice")
  1010. assert.True(t, IsErrNameNotAllowed(isUsernameAllowed(username)))
  1011. })
  1012. }
  1013. }
  1014. func usersAddEmail(t *testing.T, ctx context.Context, db *users) {
  1015. t.Run("multiple users can add the same unverified email", func(t *testing.T) {
  1016. alice, err := db.Create(ctx, "alice", "unverified@example.com", CreateUserOptions{})
  1017. require.NoError(t, err)
  1018. err = db.AddEmail(ctx, alice.ID+1, "unverified@example.com", false)
  1019. require.NoError(t, err)
  1020. })
  1021. t.Run("only one user can add the same verified email", func(t *testing.T) {
  1022. bob, err := db.Create(ctx, "bob", "verified@example.com", CreateUserOptions{Activated: true})
  1023. require.NoError(t, err)
  1024. got := db.AddEmail(ctx, bob.ID+1, "verified@example.com", true)
  1025. want := ErrEmailAlreadyUsed{args: errutil.Args{"email": "verified@example.com"}}
  1026. require.Equal(t, want, got)
  1027. })
  1028. }
  1029. func usersGetEmail(t *testing.T, ctx context.Context, db *users) {
  1030. const testUserID = 1
  1031. const testEmail = "alice@example.com"
  1032. _, err := db.GetEmail(ctx, testUserID, testEmail, false)
  1033. wantErr := ErrEmailNotExist{
  1034. args: errutil.Args{
  1035. "email": testEmail,
  1036. },
  1037. }
  1038. assert.Equal(t, wantErr, err)
  1039. err = db.AddEmail(ctx, testUserID, testEmail, false)
  1040. require.NoError(t, err)
  1041. got, err := db.GetEmail(ctx, testUserID, testEmail, false)
  1042. require.NoError(t, err)
  1043. assert.Equal(t, testEmail, got.Email)
  1044. // Should not return if we ask for a different user
  1045. _, err = db.GetEmail(ctx, testUserID+1, testEmail, false)
  1046. assert.Equal(t, wantErr, err)
  1047. // Should not return if we only want activated emails
  1048. _, err = db.GetEmail(ctx, testUserID, testEmail, true)
  1049. assert.Equal(t, wantErr, err)
  1050. err = db.MarkEmailActivated(ctx, testUserID, testEmail)
  1051. require.NoError(t, err)
  1052. got, err = db.GetEmail(ctx, testUserID, testEmail, true)
  1053. require.NoError(t, err)
  1054. assert.Equal(t, testEmail, got.Email)
  1055. }
  1056. func usersListEmails(t *testing.T, ctx context.Context, db *users) {
  1057. t.Run("list emails with primary email", func(t *testing.T) {
  1058. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  1059. require.NoError(t, err)
  1060. err = db.AddEmail(ctx, alice.ID, "alice2@example.com", true)
  1061. require.NoError(t, err)
  1062. err = db.MarkEmailPrimary(ctx, alice.ID, "alice2@example.com")
  1063. require.NoError(t, err)
  1064. emails, err := db.ListEmails(ctx, alice.ID)
  1065. require.NoError(t, err)
  1066. got := make([]string, 0, len(emails))
  1067. for _, email := range emails {
  1068. got = append(got, email.Email)
  1069. }
  1070. want := []string{"alice2@example.com", "alice@example.com"}
  1071. assert.Equal(t, want, got)
  1072. })
  1073. t.Run("list emails without primary email", func(t *testing.T) {
  1074. bob, err := db.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
  1075. require.NoError(t, err)
  1076. err = db.AddEmail(ctx, bob.ID, "bob2@example.com", false)
  1077. require.NoError(t, err)
  1078. emails, err := db.ListEmails(ctx, bob.ID)
  1079. require.NoError(t, err)
  1080. got := make([]string, 0, len(emails))
  1081. for _, email := range emails {
  1082. got = append(got, email.Email)
  1083. }
  1084. want := []string{"bob2@example.com", "bob@example.com"}
  1085. assert.Equal(t, want, got)
  1086. })
  1087. }
  1088. func usersMarkEmailActivated(t *testing.T, ctx context.Context, db *users) {
  1089. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  1090. require.NoError(t, err)
  1091. err = db.AddEmail(ctx, alice.ID, "alice2@example.com", false)
  1092. require.NoError(t, err)
  1093. err = db.MarkEmailActivated(ctx, alice.ID, "alice2@example.com")
  1094. require.NoError(t, err)
  1095. gotEmail, err := db.GetEmail(ctx, alice.ID, "alice2@example.com", true)
  1096. require.NoError(t, err)
  1097. assert.True(t, gotEmail.IsActivated)
  1098. gotAlice, err := db.GetByID(ctx, alice.ID)
  1099. require.NoError(t, err)
  1100. assert.NotEqual(t, alice.Rands, gotAlice.Rands)
  1101. }
  1102. func usersMarkEmailPrimary(t *testing.T, ctx context.Context, db *users) {
  1103. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  1104. require.NoError(t, err)
  1105. err = db.AddEmail(ctx, alice.ID, "alice2@example.com", false)
  1106. require.NoError(t, err)
  1107. // Should fail because email not verified
  1108. gotError := db.MarkEmailPrimary(ctx, alice.ID, "alice2@example.com")
  1109. wantError := ErrEmailNotVerified{args: errutil.Args{"email": "alice2@example.com"}}
  1110. assert.Equal(t, wantError, gotError)
  1111. // Mark email as verified and should succeed
  1112. err = db.MarkEmailActivated(ctx, alice.ID, "alice2@example.com")
  1113. require.NoError(t, err)
  1114. err = db.MarkEmailPrimary(ctx, alice.ID, "alice2@example.com")
  1115. require.NoError(t, err)
  1116. gotAlice, err := db.GetByID(ctx, alice.ID)
  1117. require.NoError(t, err)
  1118. assert.Equal(t, "alice2@example.com", gotAlice.Email)
  1119. // Former primary email should be preserved
  1120. gotEmail, err := db.GetEmail(ctx, alice.ID, "alice@example.com", false)
  1121. require.NoError(t, err)
  1122. assert.False(t, gotEmail.IsActivated)
  1123. }
  1124. func usersDeleteEmail(t *testing.T, ctx context.Context, db *users) {
  1125. alice, err := db.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  1126. require.NoError(t, err)
  1127. err = db.AddEmail(ctx, alice.ID, "alice2@example.com", false)
  1128. require.NoError(t, err)
  1129. _, err = db.GetEmail(ctx, alice.ID, "alice2@example.com", false)
  1130. require.NoError(t, err)
  1131. err = db.DeleteEmail(ctx, alice.ID, "alice2@example.com")
  1132. require.NoError(t, err)
  1133. _, got := db.GetEmail(ctx, alice.ID, "alice2@example.com", false)
  1134. want := ErrEmailNotExist{args: errutil.Args{"email": "alice2@example.com"}}
  1135. require.Equal(t, want, got)
  1136. }
  1137. func usersFollow(t *testing.T, ctx context.Context, db *users) {
  1138. usersStore := NewUsersStore(db.DB)
  1139. alice, err := usersStore.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  1140. require.NoError(t, err)
  1141. bob, err := usersStore.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
  1142. require.NoError(t, err)
  1143. err = db.Follow(ctx, alice.ID, bob.ID)
  1144. require.NoError(t, err)
  1145. // It is OK to follow multiple times and just be noop.
  1146. err = db.Follow(ctx, alice.ID, bob.ID)
  1147. require.NoError(t, err)
  1148. alice, err = usersStore.GetByID(ctx, alice.ID)
  1149. require.NoError(t, err)
  1150. assert.Equal(t, 1, alice.NumFollowing)
  1151. bob, err = usersStore.GetByID(ctx, bob.ID)
  1152. require.NoError(t, err)
  1153. assert.Equal(t, 1, bob.NumFollowers)
  1154. }
  1155. func usersIsFollowing(t *testing.T, ctx context.Context, db *users) {
  1156. usersStore := NewUsersStore(db.DB)
  1157. alice, err := usersStore.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  1158. require.NoError(t, err)
  1159. bob, err := usersStore.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
  1160. require.NoError(t, err)
  1161. got := db.IsFollowing(ctx, alice.ID, bob.ID)
  1162. assert.False(t, got)
  1163. err = db.Follow(ctx, alice.ID, bob.ID)
  1164. require.NoError(t, err)
  1165. got = db.IsFollowing(ctx, alice.ID, bob.ID)
  1166. assert.True(t, got)
  1167. err = db.Unfollow(ctx, alice.ID, bob.ID)
  1168. require.NoError(t, err)
  1169. got = db.IsFollowing(ctx, alice.ID, bob.ID)
  1170. assert.False(t, got)
  1171. }
  1172. func usersUnfollow(t *testing.T, ctx context.Context, db *users) {
  1173. usersStore := NewUsersStore(db.DB)
  1174. alice, err := usersStore.Create(ctx, "alice", "alice@example.com", CreateUserOptions{})
  1175. require.NoError(t, err)
  1176. bob, err := usersStore.Create(ctx, "bob", "bob@example.com", CreateUserOptions{})
  1177. require.NoError(t, err)
  1178. err = db.Follow(ctx, alice.ID, bob.ID)
  1179. require.NoError(t, err)
  1180. // It is OK to unfollow multiple times and just be noop.
  1181. err = db.Unfollow(ctx, alice.ID, bob.ID)
  1182. require.NoError(t, err)
  1183. err = db.Unfollow(ctx, alice.ID, bob.ID)
  1184. require.NoError(t, err)
  1185. alice, err = usersStore.GetByID(ctx, alice.ID)
  1186. require.NoError(t, err)
  1187. assert.Equal(t, 0, alice.NumFollowing)
  1188. bob, err = usersStore.GetByID(ctx, bob.ID)
  1189. require.NoError(t, err)
  1190. assert.Equal(t, 0, bob.NumFollowers)
  1191. }