You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

391 lines
11 KiB

API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
API add/generalize pagination (#9452) * paginate results * fixed deadlock * prevented breaking change * updated swagger * go fmt * fixed find topic * go mod tidy * go mod vendor with go1.13.5 * fixed repo find topics * fixed unit test * added Limit method to Engine struct; use engine variable when provided; fixed gitignore * use ItemsPerPage for default pagesize; fix GetWatchers, getOrgUsersByOrgID and GetStargazers; fix GetAllCommits headers; reverted some changed behaviors * set Page value on Home route * improved memory allocations * fixed response headers * removed logfiles * fixed import order * import order * improved swagger * added function to get models.ListOptions from context * removed pagesize diff on unit test * fixed imports * removed unnecessary struct field * fixed go fmt * scoped PR * code improvements * code improvements * go mod tidy * fixed import order * fixed commit statuses session * fixed files headers * fixed headers; added pagination for notifications * go mod tidy * go fmt * removed Private from user search options; added setting.UI.IssuePagingNum as default valeu on repo's issues list * Apply suggestions from code review Co-Authored-By: 6543 <6543@obermui.de> Co-Authored-By: zeripath <art27@cantab.net> * fixed build error * CI.restart() * fixed merge conflicts resolve * fixed conflicts resolve * improved FindTrackedTimesOptions.ToOptions() method * added backwards compatibility on ListReleases request; fixed issue tracked time ToSession * fixed build error; fixed swagger template * fixed swagger template * fixed ListReleases backwards compatibility * added page to user search route Co-authored-by: techknowlogick <matti@mdranta.net> Co-authored-by: 6543 <6543@obermui.de> Co-authored-by: zeripath <art27@cantab.net>
4 years ago
  1. // Copyright 2017 The Gitea 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 models
  5. import (
  6. "fmt"
  7. "math/rand"
  8. "strings"
  9. "testing"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/util"
  12. "github.com/stretchr/testify/assert"
  13. )
  14. func TestUserIsPublicMember(t *testing.T) {
  15. assert.NoError(t, PrepareTestDatabase())
  16. tt := []struct {
  17. uid int64
  18. orgid int64
  19. expected bool
  20. }{
  21. {2, 3, true},
  22. {4, 3, false},
  23. {5, 6, true},
  24. {5, 7, false},
  25. }
  26. for _, v := range tt {
  27. t.Run(fmt.Sprintf("UserId%dIsPublicMemberOf%d", v.uid, v.orgid), func(t *testing.T) {
  28. testUserIsPublicMember(t, v.uid, v.orgid, v.expected)
  29. })
  30. }
  31. }
  32. func testUserIsPublicMember(t *testing.T, uid int64, orgID int64, expected bool) {
  33. user, err := GetUserByID(uid)
  34. assert.NoError(t, err)
  35. assert.Equal(t, expected, user.IsPublicMember(orgID))
  36. }
  37. func TestIsUserOrgOwner(t *testing.T) {
  38. assert.NoError(t, PrepareTestDatabase())
  39. tt := []struct {
  40. uid int64
  41. orgid int64
  42. expected bool
  43. }{
  44. {2, 3, true},
  45. {4, 3, false},
  46. {5, 6, true},
  47. {5, 7, true},
  48. }
  49. for _, v := range tt {
  50. t.Run(fmt.Sprintf("UserId%dIsOrgOwnerOf%d", v.uid, v.orgid), func(t *testing.T) {
  51. testIsUserOrgOwner(t, v.uid, v.orgid, v.expected)
  52. })
  53. }
  54. }
  55. func testIsUserOrgOwner(t *testing.T, uid int64, orgID int64, expected bool) {
  56. user, err := GetUserByID(uid)
  57. assert.NoError(t, err)
  58. assert.Equal(t, expected, user.IsUserOrgOwner(orgID))
  59. }
  60. func TestGetUserEmailsByNames(t *testing.T) {
  61. assert.NoError(t, PrepareTestDatabase())
  62. // ignore none active user email
  63. assert.Equal(t, []string{"user8@example.com"}, GetUserEmailsByNames([]string{"user8", "user9"}))
  64. assert.Equal(t, []string{"user8@example.com", "user5@example.com"}, GetUserEmailsByNames([]string{"user8", "user5"}))
  65. assert.Equal(t, []string{"user8@example.com"}, GetUserEmailsByNames([]string{"user8", "user7"}))
  66. }
  67. func TestUser_APIFormat(t *testing.T) {
  68. user, err := GetUserByID(1)
  69. assert.NoError(t, err)
  70. assert.True(t, user.IsAdmin)
  71. apiUser := user.APIFormat()
  72. assert.True(t, apiUser.IsAdmin)
  73. user, err = GetUserByID(2)
  74. assert.NoError(t, err)
  75. assert.False(t, user.IsAdmin)
  76. apiUser = user.APIFormat()
  77. assert.False(t, apiUser.IsAdmin)
  78. }
  79. func TestCanCreateOrganization(t *testing.T) {
  80. assert.NoError(t, PrepareTestDatabase())
  81. admin := AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
  82. assert.True(t, admin.CanCreateOrganization())
  83. user := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
  84. assert.True(t, user.CanCreateOrganization())
  85. // Disable user create organization permission.
  86. user.AllowCreateOrganization = false
  87. assert.False(t, user.CanCreateOrganization())
  88. setting.Admin.DisableRegularOrgCreation = true
  89. user.AllowCreateOrganization = true
  90. assert.True(t, admin.CanCreateOrganization())
  91. assert.False(t, user.CanCreateOrganization())
  92. }
  93. func TestSearchUsers(t *testing.T) {
  94. assert.NoError(t, PrepareTestDatabase())
  95. testSuccess := func(opts *SearchUserOptions, expectedUserOrOrgIDs []int64) {
  96. users, _, err := SearchUsers(opts)
  97. assert.NoError(t, err)
  98. if assert.Len(t, users, len(expectedUserOrOrgIDs)) {
  99. for i, expectedID := range expectedUserOrOrgIDs {
  100. assert.EqualValues(t, expectedID, users[i].ID)
  101. }
  102. }
  103. }
  104. // test orgs
  105. testOrgSuccess := func(opts *SearchUserOptions, expectedOrgIDs []int64) {
  106. opts.Type = UserTypeOrganization
  107. testSuccess(opts, expectedOrgIDs)
  108. }
  109. testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 1, PageSize: 2}},
  110. []int64{3, 6})
  111. testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 2, PageSize: 2}},
  112. []int64{7, 17})
  113. testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 3, PageSize: 2}},
  114. []int64{19, 25})
  115. testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 4, PageSize: 2}},
  116. []int64{26})
  117. testOrgSuccess(&SearchUserOptions{ListOptions: ListOptions{Page: 5, PageSize: 2}},
  118. []int64{})
  119. // test users
  120. testUserSuccess := func(opts *SearchUserOptions, expectedUserIDs []int64) {
  121. opts.Type = UserTypeIndividual
  122. testSuccess(opts, expectedUserIDs)
  123. }
  124. testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 1}},
  125. []int64{1, 2, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 24, 27, 28, 29})
  126. testUserSuccess(&SearchUserOptions{ListOptions: ListOptions{Page: 1}, IsActive: util.OptionalBoolFalse},
  127. []int64{9})
  128. testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", ListOptions: ListOptions{Page: 1}, IsActive: util.OptionalBoolTrue},
  129. []int64{1, 2, 4, 5, 8, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 24, 28, 29})
  130. testUserSuccess(&SearchUserOptions{Keyword: "user1", OrderBy: "id ASC", ListOptions: ListOptions{Page: 1}, IsActive: util.OptionalBoolTrue},
  131. []int64{1, 10, 11, 12, 13, 14, 15, 16, 18})
  132. // order by name asc default
  133. testUserSuccess(&SearchUserOptions{Keyword: "user1", ListOptions: ListOptions{Page: 1}, IsActive: util.OptionalBoolTrue},
  134. []int64{1, 10, 11, 12, 13, 14, 15, 16, 18})
  135. }
  136. func TestDeleteUser(t *testing.T) {
  137. test := func(userID int64) {
  138. assert.NoError(t, PrepareTestDatabase())
  139. user := AssertExistsAndLoadBean(t, &User{ID: userID}).(*User)
  140. ownedRepos := make([]*Repository, 0, 10)
  141. assert.NoError(t, x.Find(&ownedRepos, &Repository{OwnerID: userID}))
  142. if len(ownedRepos) > 0 {
  143. err := DeleteUser(user)
  144. assert.Error(t, err)
  145. assert.True(t, IsErrUserOwnRepos(err))
  146. return
  147. }
  148. orgUsers := make([]*OrgUser, 0, 10)
  149. assert.NoError(t, x.Find(&orgUsers, &OrgUser{UID: userID}))
  150. for _, orgUser := range orgUsers {
  151. if err := RemoveOrgUser(orgUser.OrgID, orgUser.UID); err != nil {
  152. assert.True(t, IsErrLastOrgOwner(err))
  153. return
  154. }
  155. }
  156. assert.NoError(t, DeleteUser(user))
  157. AssertNotExistsBean(t, &User{ID: userID})
  158. CheckConsistencyFor(t, &User{}, &Repository{})
  159. }
  160. test(2)
  161. test(4)
  162. test(8)
  163. test(11)
  164. org := AssertExistsAndLoadBean(t, &User{ID: 3}).(*User)
  165. assert.Error(t, DeleteUser(org))
  166. }
  167. func TestEmailNotificationPreferences(t *testing.T) {
  168. assert.NoError(t, PrepareTestDatabase())
  169. for _, test := range []struct {
  170. expected string
  171. userID int64
  172. }{
  173. {EmailNotificationsEnabled, 1},
  174. {EmailNotificationsEnabled, 2},
  175. {EmailNotificationsOnMention, 3},
  176. {EmailNotificationsOnMention, 4},
  177. {EmailNotificationsEnabled, 5},
  178. {EmailNotificationsEnabled, 6},
  179. {EmailNotificationsDisabled, 7},
  180. {EmailNotificationsEnabled, 8},
  181. {EmailNotificationsOnMention, 9},
  182. } {
  183. user := AssertExistsAndLoadBean(t, &User{ID: test.userID}).(*User)
  184. assert.Equal(t, test.expected, user.EmailNotifications())
  185. // Try all possible settings
  186. assert.NoError(t, user.SetEmailNotifications(EmailNotificationsEnabled))
  187. assert.Equal(t, EmailNotificationsEnabled, user.EmailNotifications())
  188. assert.NoError(t, user.SetEmailNotifications(EmailNotificationsOnMention))
  189. assert.Equal(t, EmailNotificationsOnMention, user.EmailNotifications())
  190. assert.NoError(t, user.SetEmailNotifications(EmailNotificationsDisabled))
  191. assert.Equal(t, EmailNotificationsDisabled, user.EmailNotifications())
  192. }
  193. }
  194. func TestHashPasswordDeterministic(t *testing.T) {
  195. b := make([]byte, 16)
  196. rand.Read(b)
  197. u := &User{Salt: string(b)}
  198. algos := []string{"pbkdf2", "argon2", "scrypt", "bcrypt"}
  199. for j := 0; j < len(algos); j++ {
  200. u.PasswdHashAlgo = algos[j]
  201. for i := 0; i < 50; i++ {
  202. // generate a random password
  203. rand.Read(b)
  204. pass := string(b)
  205. // save the current password in the user - hash it and store the result
  206. u.HashPassword(pass)
  207. r1 := u.Passwd
  208. // run again
  209. u.HashPassword(pass)
  210. r2 := u.Passwd
  211. // assert equal (given the same salt+pass, the same result is produced) except bcrypt
  212. if u.PasswdHashAlgo == "bcrypt" {
  213. assert.NotEqual(t, r1, r2)
  214. } else {
  215. assert.Equal(t, r1, r2)
  216. }
  217. }
  218. }
  219. }
  220. func BenchmarkHashPassword(b *testing.B) {
  221. // BenchmarkHashPassword ensures that it takes a reasonable amount of time
  222. // to hash a password - in order to protect from brute-force attacks.
  223. pass := "password1337"
  224. bs := make([]byte, 16)
  225. rand.Read(bs)
  226. u := &User{Salt: string(bs), Passwd: pass}
  227. b.ResetTimer()
  228. for i := 0; i < b.N; i++ {
  229. u.HashPassword(pass)
  230. }
  231. }
  232. func TestGetOrgRepositoryIDs(t *testing.T) {
  233. assert.NoError(t, PrepareTestDatabase())
  234. user2 := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
  235. user4 := AssertExistsAndLoadBean(t, &User{ID: 4}).(*User)
  236. user5 := AssertExistsAndLoadBean(t, &User{ID: 5}).(*User)
  237. accessibleRepos, err := user2.GetOrgRepositoryIDs()
  238. assert.NoError(t, err)
  239. // User 2's team has access to private repos 3, 5, repo 32 is a public repo of the organization
  240. assert.Equal(t, []int64{3, 5, 23, 24, 32}, accessibleRepos)
  241. accessibleRepos, err = user4.GetOrgRepositoryIDs()
  242. assert.NoError(t, err)
  243. // User 4's team has access to private repo 3, repo 32 is a public repo of the organization
  244. assert.Equal(t, []int64{3, 32}, accessibleRepos)
  245. accessibleRepos, err = user5.GetOrgRepositoryIDs()
  246. assert.NoError(t, err)
  247. // User 5's team has no access to any repo
  248. assert.Len(t, accessibleRepos, 0)
  249. }
  250. func TestNewGitSig(t *testing.T) {
  251. users := make([]*User, 0, 20)
  252. sess := x.NewSession()
  253. defer sess.Close()
  254. sess.Find(&users)
  255. for _, user := range users {
  256. sig := user.NewGitSig()
  257. assert.NotContains(t, sig.Name, "<")
  258. assert.NotContains(t, sig.Name, ">")
  259. assert.NotContains(t, sig.Name, "\n")
  260. assert.NotEqual(t, len(strings.TrimSpace(sig.Name)), 0)
  261. }
  262. }
  263. func TestDisplayName(t *testing.T) {
  264. users := make([]*User, 0, 20)
  265. sess := x.NewSession()
  266. defer sess.Close()
  267. sess.Find(&users)
  268. for _, user := range users {
  269. displayName := user.DisplayName()
  270. assert.Equal(t, strings.TrimSpace(displayName), displayName)
  271. if len(strings.TrimSpace(user.FullName)) == 0 {
  272. assert.Equal(t, user.Name, displayName)
  273. }
  274. assert.NotEqual(t, len(strings.TrimSpace(displayName)), 0)
  275. }
  276. }
  277. func TestCreateUser(t *testing.T) {
  278. user := &User{
  279. Name: "GiteaBot",
  280. Email: "GiteaBot@gitea.io",
  281. Passwd: ";p['////..-++']",
  282. IsAdmin: false,
  283. Theme: setting.UI.DefaultTheme,
  284. MustChangePassword: false,
  285. }
  286. assert.NoError(t, CreateUser(user))
  287. assert.NoError(t, DeleteUser(user))
  288. }
  289. func TestCreateUser_Issue5882(t *testing.T) {
  290. // Init settings
  291. _ = setting.Admin
  292. passwd := ".//.;1;;//.,-=_"
  293. tt := []struct {
  294. user *User
  295. disableOrgCreation bool
  296. }{
  297. {&User{Name: "GiteaBot", Email: "GiteaBot@gitea.io", Passwd: passwd, MustChangePassword: false}, false},
  298. {&User{Name: "GiteaBot2", Email: "GiteaBot2@gitea.io", Passwd: passwd, MustChangePassword: false}, true},
  299. }
  300. setting.Service.DefaultAllowCreateOrganization = true
  301. for _, v := range tt {
  302. setting.Admin.DisableRegularOrgCreation = v.disableOrgCreation
  303. assert.NoError(t, CreateUser(v.user))
  304. u, err := GetUserByEmail(v.user.Email)
  305. assert.NoError(t, err)
  306. assert.Equal(t, !u.AllowCreateOrganization, v.disableOrgCreation)
  307. assert.NoError(t, DeleteUser(v.user))
  308. }
  309. }
  310. func TestGetUserIDsByNames(t *testing.T) {
  311. //ignore non existing
  312. IDs, err := GetUserIDsByNames([]string{"user1", "user2", "none_existing_user"}, true)
  313. assert.NoError(t, err)
  314. assert.Equal(t, []int64{1, 2}, IDs)
  315. //ignore non existing
  316. IDs, err = GetUserIDsByNames([]string{"user1", "do_not_exist"}, false)
  317. assert.Error(t, err)
  318. assert.Equal(t, []int64(nil), IDs)
  319. }