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.

322 lines
8.9 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
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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2020 The Gitea Authors.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package admin
  6. import (
  7. "strings"
  8. "code.gitea.io/gitea/models"
  9. "code.gitea.io/gitea/modules/auth"
  10. "code.gitea.io/gitea/modules/base"
  11. "code.gitea.io/gitea/modules/context"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/password"
  14. "code.gitea.io/gitea/modules/setting"
  15. "code.gitea.io/gitea/routers"
  16. "code.gitea.io/gitea/services/mailer"
  17. "github.com/unknwon/com"
  18. )
  19. const (
  20. tplUsers base.TplName = "admin/user/list"
  21. tplUserNew base.TplName = "admin/user/new"
  22. tplUserEdit base.TplName = "admin/user/edit"
  23. )
  24. // Users show all the users
  25. func Users(ctx *context.Context) {
  26. ctx.Data["Title"] = ctx.Tr("admin.users")
  27. ctx.Data["PageIsAdmin"] = true
  28. ctx.Data["PageIsAdminUsers"] = true
  29. routers.RenderUserSearch(ctx, &models.SearchUserOptions{
  30. Type: models.UserTypeIndividual,
  31. ListOptions: models.ListOptions{
  32. PageSize: setting.UI.Admin.UserPagingNum,
  33. },
  34. SearchByEmail: true,
  35. }, tplUsers)
  36. }
  37. // NewUser render adding a new user page
  38. func NewUser(ctx *context.Context) {
  39. ctx.Data["Title"] = ctx.Tr("admin.users.new_account")
  40. ctx.Data["PageIsAdmin"] = true
  41. ctx.Data["PageIsAdminUsers"] = true
  42. ctx.Data["login_type"] = "0-0"
  43. sources, err := models.LoginSources()
  44. if err != nil {
  45. ctx.ServerError("LoginSources", err)
  46. return
  47. }
  48. ctx.Data["Sources"] = sources
  49. ctx.Data["CanSendEmail"] = setting.MailService != nil
  50. ctx.HTML(200, tplUserNew)
  51. }
  52. // NewUserPost response for adding a new user
  53. func NewUserPost(ctx *context.Context, form auth.AdminCreateUserForm) {
  54. ctx.Data["Title"] = ctx.Tr("admin.users.new_account")
  55. ctx.Data["PageIsAdmin"] = true
  56. ctx.Data["PageIsAdminUsers"] = true
  57. sources, err := models.LoginSources()
  58. if err != nil {
  59. ctx.ServerError("LoginSources", err)
  60. return
  61. }
  62. ctx.Data["Sources"] = sources
  63. ctx.Data["CanSendEmail"] = setting.MailService != nil
  64. if ctx.HasError() {
  65. ctx.HTML(200, tplUserNew)
  66. return
  67. }
  68. u := &models.User{
  69. Name: form.UserName,
  70. Email: form.Email,
  71. Passwd: form.Password,
  72. IsActive: true,
  73. LoginType: models.LoginPlain,
  74. }
  75. if len(form.LoginType) > 0 {
  76. fields := strings.Split(form.LoginType, "-")
  77. if len(fields) == 2 {
  78. u.LoginType = models.LoginType(com.StrTo(fields[0]).MustInt())
  79. u.LoginSource = com.StrTo(fields[1]).MustInt64()
  80. u.LoginName = form.LoginName
  81. }
  82. }
  83. if u.LoginType == models.LoginNoType || u.LoginType == models.LoginPlain {
  84. if len(form.Password) < setting.MinPasswordLength {
  85. ctx.Data["Err_Password"] = true
  86. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplUserNew, &form)
  87. return
  88. }
  89. if !password.IsComplexEnough(form.Password) {
  90. ctx.Data["Err_Password"] = true
  91. ctx.RenderWithErr(password.BuildComplexityError(ctx), tplUserNew, &form)
  92. return
  93. }
  94. pwned, err := password.IsPwned(ctx.Req.Context(), form.Password)
  95. if pwned {
  96. ctx.Data["Err_Password"] = true
  97. errMsg := ctx.Tr("auth.password_pwned")
  98. if err != nil {
  99. log.Error(err.Error())
  100. errMsg = ctx.Tr("auth.password_pwned_err")
  101. }
  102. ctx.RenderWithErr(errMsg, tplUserNew, &form)
  103. return
  104. }
  105. u.MustChangePassword = form.MustChangePassword
  106. }
  107. if err := models.CreateUser(u); err != nil {
  108. switch {
  109. case models.IsErrUserAlreadyExist(err):
  110. ctx.Data["Err_UserName"] = true
  111. ctx.RenderWithErr(ctx.Tr("form.username_been_taken"), tplUserNew, &form)
  112. case models.IsErrEmailAlreadyUsed(err):
  113. ctx.Data["Err_Email"] = true
  114. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplUserNew, &form)
  115. case models.IsErrNameReserved(err):
  116. ctx.Data["Err_UserName"] = true
  117. ctx.RenderWithErr(ctx.Tr("user.form.name_reserved", err.(models.ErrNameReserved).Name), tplUserNew, &form)
  118. case models.IsErrNamePatternNotAllowed(err):
  119. ctx.Data["Err_UserName"] = true
  120. ctx.RenderWithErr(ctx.Tr("user.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplUserNew, &form)
  121. case models.IsErrNameCharsNotAllowed(err):
  122. ctx.Data["Err_UserName"] = true
  123. ctx.RenderWithErr(ctx.Tr("user.form.name_chars_not_allowed", err.(models.ErrNameCharsNotAllowed).Name), tplUserNew, &form)
  124. default:
  125. ctx.ServerError("CreateUser", err)
  126. }
  127. return
  128. }
  129. log.Trace("Account created by admin (%s): %s", ctx.User.Name, u.Name)
  130. // Send email notification.
  131. if form.SendNotify {
  132. mailer.SendRegisterNotifyMail(ctx.Locale, u)
  133. }
  134. ctx.Flash.Success(ctx.Tr("admin.users.new_success", u.Name))
  135. ctx.Redirect(setting.AppSubURL + "/admin/users/" + com.ToStr(u.ID))
  136. }
  137. func prepareUserInfo(ctx *context.Context) *models.User {
  138. u, err := models.GetUserByID(ctx.ParamsInt64(":userid"))
  139. if err != nil {
  140. ctx.ServerError("GetUserByID", err)
  141. return nil
  142. }
  143. ctx.Data["User"] = u
  144. if u.LoginSource > 0 {
  145. ctx.Data["LoginSource"], err = models.GetLoginSourceByID(u.LoginSource)
  146. if err != nil {
  147. ctx.ServerError("GetLoginSourceByID", err)
  148. return nil
  149. }
  150. } else {
  151. ctx.Data["LoginSource"] = &models.LoginSource{}
  152. }
  153. sources, err := models.LoginSources()
  154. if err != nil {
  155. ctx.ServerError("LoginSources", err)
  156. return nil
  157. }
  158. ctx.Data["Sources"] = sources
  159. return u
  160. }
  161. // EditUser show editting user page
  162. func EditUser(ctx *context.Context) {
  163. ctx.Data["Title"] = ctx.Tr("admin.users.edit_account")
  164. ctx.Data["PageIsAdmin"] = true
  165. ctx.Data["PageIsAdminUsers"] = true
  166. ctx.Data["DisableRegularOrgCreation"] = setting.Admin.DisableRegularOrgCreation
  167. prepareUserInfo(ctx)
  168. if ctx.Written() {
  169. return
  170. }
  171. ctx.HTML(200, tplUserEdit)
  172. }
  173. // EditUserPost response for editting user
  174. func EditUserPost(ctx *context.Context, form auth.AdminEditUserForm) {
  175. ctx.Data["Title"] = ctx.Tr("admin.users.edit_account")
  176. ctx.Data["PageIsAdmin"] = true
  177. ctx.Data["PageIsAdminUsers"] = true
  178. u := prepareUserInfo(ctx)
  179. if ctx.Written() {
  180. return
  181. }
  182. if ctx.HasError() {
  183. ctx.HTML(200, tplUserEdit)
  184. return
  185. }
  186. fields := strings.Split(form.LoginType, "-")
  187. if len(fields) == 2 {
  188. loginType := models.LoginType(com.StrTo(fields[0]).MustInt())
  189. loginSource := com.StrTo(fields[1]).MustInt64()
  190. if u.LoginSource != loginSource {
  191. u.LoginSource = loginSource
  192. u.LoginType = loginType
  193. }
  194. }
  195. if len(form.Password) > 0 {
  196. var err error
  197. if len(form.Password) < setting.MinPasswordLength {
  198. ctx.Data["Err_Password"] = true
  199. ctx.RenderWithErr(ctx.Tr("auth.password_too_short", setting.MinPasswordLength), tplUserEdit, &form)
  200. return
  201. }
  202. if !password.IsComplexEnough(form.Password) {
  203. ctx.RenderWithErr(password.BuildComplexityError(ctx), tplUserEdit, &form)
  204. return
  205. }
  206. pwned, err := password.IsPwned(ctx.Req.Context(), form.Password)
  207. if pwned {
  208. ctx.Data["Err_Password"] = true
  209. errMsg := ctx.Tr("auth.password_pwned")
  210. if err != nil {
  211. log.Error(err.Error())
  212. errMsg = ctx.Tr("auth.password_pwned_err")
  213. }
  214. ctx.RenderWithErr(errMsg, tplUserNew, &form)
  215. return
  216. }
  217. if u.Salt, err = models.GetUserSalt(); err != nil {
  218. ctx.ServerError("UpdateUser", err)
  219. return
  220. }
  221. u.HashPassword(form.Password)
  222. }
  223. u.LoginName = form.LoginName
  224. u.FullName = form.FullName
  225. u.Email = form.Email
  226. u.Website = form.Website
  227. u.Location = form.Location
  228. u.MaxRepoCreation = form.MaxRepoCreation
  229. u.IsActive = form.Active
  230. u.IsAdmin = form.Admin
  231. u.IsRestricted = form.Restricted
  232. u.AllowGitHook = form.AllowGitHook
  233. u.AllowImportLocal = form.AllowImportLocal
  234. u.AllowCreateOrganization = form.AllowCreateOrganization
  235. // skip self Prohibit Login
  236. if ctx.User.ID == u.ID {
  237. u.ProhibitLogin = false
  238. } else {
  239. u.ProhibitLogin = form.ProhibitLogin
  240. }
  241. if err := models.UpdateUser(u); err != nil {
  242. if models.IsErrEmailAlreadyUsed(err) {
  243. ctx.Data["Err_Email"] = true
  244. ctx.RenderWithErr(ctx.Tr("form.email_been_used"), tplUserEdit, &form)
  245. } else {
  246. ctx.ServerError("UpdateUser", err)
  247. }
  248. return
  249. }
  250. log.Trace("Account profile updated by admin (%s): %s", ctx.User.Name, u.Name)
  251. ctx.Flash.Success(ctx.Tr("admin.users.update_profile_success"))
  252. ctx.Redirect(setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"))
  253. }
  254. // DeleteUser response for deleting a user
  255. func DeleteUser(ctx *context.Context) {
  256. u, err := models.GetUserByID(ctx.ParamsInt64(":userid"))
  257. if err != nil {
  258. ctx.ServerError("GetUserByID", err)
  259. return
  260. }
  261. if err = models.DeleteUser(u); err != nil {
  262. switch {
  263. case models.IsErrUserOwnRepos(err):
  264. ctx.Flash.Error(ctx.Tr("admin.users.still_own_repo"))
  265. ctx.JSON(200, map[string]interface{}{
  266. "redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"),
  267. })
  268. case models.IsErrUserHasOrgs(err):
  269. ctx.Flash.Error(ctx.Tr("admin.users.still_has_org"))
  270. ctx.JSON(200, map[string]interface{}{
  271. "redirect": setting.AppSubURL + "/admin/users/" + ctx.Params(":userid"),
  272. })
  273. default:
  274. ctx.ServerError("DeleteUser", err)
  275. }
  276. return
  277. }
  278. log.Trace("Account deleted by admin (%s): %s", ctx.User.Name, u.Name)
  279. ctx.Flash.Success(ctx.Tr("admin.users.deletion_success"))
  280. ctx.JSON(200, map[string]interface{}{
  281. "redirect": setting.AppSubURL + "/admin/users",
  282. })
  283. }