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.

user_test.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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. }