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 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  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", Page: 1, PageSize: 2},
  110. []int64{3, 6})
  111. testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 2, PageSize: 2},
  112. []int64{7, 17})
  113. testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 3, PageSize: 2},
  114. []int64{19, 25})
  115. testOrgSuccess(&SearchUserOptions{Page: 4, PageSize: 2},
  116. []int64{})
  117. // test users
  118. testUserSuccess := func(opts *SearchUserOptions, expectedUserIDs []int64) {
  119. opts.Type = UserTypeIndividual
  120. testSuccess(opts, expectedUserIDs)
  121. }
  122. testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 1},
  123. []int64{1, 2, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 24})
  124. testUserSuccess(&SearchUserOptions{Page: 1, IsActive: util.OptionalBoolFalse},
  125. []int64{9})
  126. testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 1, IsActive: util.OptionalBoolTrue},
  127. []int64{1, 2, 4, 5, 8, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 24})
  128. testUserSuccess(&SearchUserOptions{Keyword: "user1", OrderBy: "id ASC", Page: 1, IsActive: util.OptionalBoolTrue},
  129. []int64{1, 10, 11, 12, 13, 14, 15, 16, 18})
  130. // order by name asc default
  131. testUserSuccess(&SearchUserOptions{Keyword: "user1", Page: 1, IsActive: util.OptionalBoolTrue},
  132. []int64{1, 10, 11, 12, 13, 14, 15, 16, 18})
  133. }
  134. func TestDeleteUser(t *testing.T) {
  135. test := func(userID int64) {
  136. assert.NoError(t, PrepareTestDatabase())
  137. user := AssertExistsAndLoadBean(t, &User{ID: userID}).(*User)
  138. ownedRepos := make([]*Repository, 0, 10)
  139. assert.NoError(t, x.Find(&ownedRepos, &Repository{OwnerID: userID}))
  140. if len(ownedRepos) > 0 {
  141. err := DeleteUser(user)
  142. assert.Error(t, err)
  143. assert.True(t, IsErrUserOwnRepos(err))
  144. return
  145. }
  146. orgUsers := make([]*OrgUser, 0, 10)
  147. assert.NoError(t, x.Find(&orgUsers, &OrgUser{UID: userID}))
  148. for _, orgUser := range orgUsers {
  149. if err := RemoveOrgUser(orgUser.OrgID, orgUser.UID); err != nil {
  150. assert.True(t, IsErrLastOrgOwner(err))
  151. return
  152. }
  153. }
  154. assert.NoError(t, DeleteUser(user))
  155. AssertNotExistsBean(t, &User{ID: userID})
  156. CheckConsistencyFor(t, &User{}, &Repository{})
  157. }
  158. test(2)
  159. test(4)
  160. test(8)
  161. test(11)
  162. }
  163. func TestEmailNotificationPreferences(t *testing.T) {
  164. assert.NoError(t, PrepareTestDatabase())
  165. for _, test := range []struct {
  166. expected string
  167. userID int64
  168. }{
  169. {EmailNotificationsEnabled, 1},
  170. {EmailNotificationsEnabled, 2},
  171. {EmailNotificationsOnMention, 3},
  172. {EmailNotificationsOnMention, 4},
  173. {EmailNotificationsEnabled, 5},
  174. {EmailNotificationsEnabled, 6},
  175. {EmailNotificationsDisabled, 7},
  176. {EmailNotificationsEnabled, 8},
  177. {EmailNotificationsOnMention, 9},
  178. } {
  179. user := AssertExistsAndLoadBean(t, &User{ID: test.userID}).(*User)
  180. assert.Equal(t, test.expected, user.EmailNotifications())
  181. // Try all possible settings
  182. assert.NoError(t, user.SetEmailNotifications(EmailNotificationsEnabled))
  183. assert.Equal(t, EmailNotificationsEnabled, user.EmailNotifications())
  184. assert.NoError(t, user.SetEmailNotifications(EmailNotificationsOnMention))
  185. assert.Equal(t, EmailNotificationsOnMention, user.EmailNotifications())
  186. assert.NoError(t, user.SetEmailNotifications(EmailNotificationsDisabled))
  187. assert.Equal(t, EmailNotificationsDisabled, user.EmailNotifications())
  188. }
  189. }
  190. func TestHashPasswordDeterministic(t *testing.T) {
  191. b := make([]byte, 16)
  192. rand.Read(b)
  193. u := &User{Salt: string(b)}
  194. algos := []string{"pbkdf2", "argon2", "scrypt", "bcrypt"}
  195. for j := 0; j < len(algos); j++ {
  196. u.PasswdHashAlgo = algos[j]
  197. for i := 0; i < 50; i++ {
  198. // generate a random password
  199. rand.Read(b)
  200. pass := string(b)
  201. // save the current password in the user - hash it and store the result
  202. u.HashPassword(pass)
  203. r1 := u.Passwd
  204. // run again
  205. u.HashPassword(pass)
  206. r2 := u.Passwd
  207. // assert equal (given the same salt+pass, the same result is produced) except bcrypt
  208. if u.PasswdHashAlgo == "bcrypt" {
  209. assert.NotEqual(t, r1, r2)
  210. } else {
  211. assert.Equal(t, r1, r2)
  212. }
  213. }
  214. }
  215. }
  216. func BenchmarkHashPassword(b *testing.B) {
  217. // BenchmarkHashPassword ensures that it takes a reasonable amount of time
  218. // to hash a password - in order to protect from brute-force attacks.
  219. pass := "password1337"
  220. bs := make([]byte, 16)
  221. rand.Read(bs)
  222. u := &User{Salt: string(bs), Passwd: pass}
  223. b.ResetTimer()
  224. for i := 0; i < b.N; i++ {
  225. u.HashPassword(pass)
  226. }
  227. }
  228. func TestGetOrgRepositoryIDs(t *testing.T) {
  229. assert.NoError(t, PrepareTestDatabase())
  230. user2 := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
  231. user4 := AssertExistsAndLoadBean(t, &User{ID: 4}).(*User)
  232. user5 := AssertExistsAndLoadBean(t, &User{ID: 5}).(*User)
  233. accessibleRepos, err := user2.GetOrgRepositoryIDs()
  234. assert.NoError(t, err)
  235. // User 2's team has access to private repos 3, 5, repo 32 is a public repo of the organization
  236. assert.Equal(t, []int64{3, 5, 23, 24, 32}, accessibleRepos)
  237. accessibleRepos, err = user4.GetOrgRepositoryIDs()
  238. assert.NoError(t, err)
  239. // User 4's team has access to private repo 3, repo 32 is a public repo of the organization
  240. assert.Equal(t, []int64{3, 32}, accessibleRepos)
  241. accessibleRepos, err = user5.GetOrgRepositoryIDs()
  242. assert.NoError(t, err)
  243. // User 5's team has no access to any repo
  244. assert.Len(t, accessibleRepos, 0)
  245. }
  246. func TestNewGitSig(t *testing.T) {
  247. users := make([]*User, 0, 20)
  248. sess := x.NewSession()
  249. defer sess.Close()
  250. sess.Find(&users)
  251. for _, user := range users {
  252. sig := user.NewGitSig()
  253. assert.NotContains(t, sig.Name, "<")
  254. assert.NotContains(t, sig.Name, ">")
  255. assert.NotContains(t, sig.Name, "\n")
  256. assert.NotEqual(t, len(strings.TrimSpace(sig.Name)), 0)
  257. }
  258. }
  259. func TestDisplayName(t *testing.T) {
  260. users := make([]*User, 0, 20)
  261. sess := x.NewSession()
  262. defer sess.Close()
  263. sess.Find(&users)
  264. for _, user := range users {
  265. displayName := user.DisplayName()
  266. assert.Equal(t, strings.TrimSpace(displayName), displayName)
  267. if len(strings.TrimSpace(user.FullName)) == 0 {
  268. assert.Equal(t, user.Name, displayName)
  269. }
  270. assert.NotEqual(t, len(strings.TrimSpace(displayName)), 0)
  271. }
  272. }
  273. func TestCreateUser(t *testing.T) {
  274. user := &User{
  275. Name: "GiteaBot",
  276. Email: "GiteaBot@gitea.io",
  277. Passwd: ";p['////..-++']",
  278. IsAdmin: false,
  279. Theme: setting.UI.DefaultTheme,
  280. MustChangePassword: false,
  281. }
  282. assert.NoError(t, CreateUser(user))
  283. assert.NoError(t, DeleteUser(user))
  284. }
  285. func TestCreateUser_Issue5882(t *testing.T) {
  286. // Init settings
  287. _ = setting.Admin
  288. passwd := ".//.;1;;//.,-=_"
  289. tt := []struct {
  290. user *User
  291. disableOrgCreation bool
  292. }{
  293. {&User{Name: "GiteaBot", Email: "GiteaBot@gitea.io", Passwd: passwd, MustChangePassword: false}, false},
  294. {&User{Name: "GiteaBot2", Email: "GiteaBot2@gitea.io", Passwd: passwd, MustChangePassword: false}, true},
  295. }
  296. setting.Service.DefaultAllowCreateOrganization = true
  297. for _, v := range tt {
  298. setting.Admin.DisableRegularOrgCreation = v.disableOrgCreation
  299. assert.NoError(t, CreateUser(v.user))
  300. u, err := GetUserByEmail(v.user.Email)
  301. assert.NoError(t, err)
  302. assert.Equal(t, !u.AllowCreateOrganization, v.disableOrgCreation)
  303. assert.NoError(t, DeleteUser(v.user))
  304. }
  305. }