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.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. // Copyright 2015 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  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. "errors"
  8. "fmt"
  9. "net/http"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/context"
  12. "code.gitea.io/gitea/modules/convert"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/password"
  15. api "code.gitea.io/gitea/modules/structs"
  16. "code.gitea.io/gitea/modules/web"
  17. "code.gitea.io/gitea/routers/api/v1/user"
  18. "code.gitea.io/gitea/routers/api/v1/utils"
  19. "code.gitea.io/gitea/services/mailer"
  20. )
  21. func parseLoginSource(ctx *context.APIContext, u *models.User, sourceID int64, loginName string) {
  22. if sourceID == 0 {
  23. return
  24. }
  25. source, err := models.GetLoginSourceByID(sourceID)
  26. if err != nil {
  27. if models.IsErrLoginSourceNotExist(err) {
  28. ctx.Error(http.StatusUnprocessableEntity, "", err)
  29. } else {
  30. ctx.Error(http.StatusInternalServerError, "GetLoginSourceByID", err)
  31. }
  32. return
  33. }
  34. u.LoginType = source.Type
  35. u.LoginSource = source.ID
  36. u.LoginName = loginName
  37. }
  38. // CreateUser create a user
  39. func CreateUser(ctx *context.APIContext) {
  40. // swagger:operation POST /admin/users admin adminCreateUser
  41. // ---
  42. // summary: Create a user
  43. // consumes:
  44. // - application/json
  45. // produces:
  46. // - application/json
  47. // parameters:
  48. // - name: body
  49. // in: body
  50. // schema:
  51. // "$ref": "#/definitions/CreateUserOption"
  52. // responses:
  53. // "201":
  54. // "$ref": "#/responses/User"
  55. // "400":
  56. // "$ref": "#/responses/error"
  57. // "403":
  58. // "$ref": "#/responses/forbidden"
  59. // "422":
  60. // "$ref": "#/responses/validationError"
  61. form := web.GetForm(ctx).(*api.CreateUserOption)
  62. u := &models.User{
  63. Name: form.Username,
  64. FullName: form.FullName,
  65. Email: form.Email,
  66. Passwd: form.Password,
  67. MustChangePassword: true,
  68. IsActive: true,
  69. LoginType: models.LoginPlain,
  70. }
  71. if form.MustChangePassword != nil {
  72. u.MustChangePassword = *form.MustChangePassword
  73. }
  74. parseLoginSource(ctx, u, form.SourceID, form.LoginName)
  75. if ctx.Written() {
  76. return
  77. }
  78. if !password.IsComplexEnough(form.Password) {
  79. err := errors.New("PasswordComplexity")
  80. ctx.Error(http.StatusBadRequest, "PasswordComplexity", err)
  81. return
  82. }
  83. pwned, err := password.IsPwned(ctx, form.Password)
  84. if pwned {
  85. if err != nil {
  86. log.Error(err.Error())
  87. }
  88. ctx.Data["Err_Password"] = true
  89. ctx.Error(http.StatusBadRequest, "PasswordPwned", errors.New("PasswordPwned"))
  90. return
  91. }
  92. var overwriteDefault *models.CreateUserOverwriteOptions
  93. if form.Visibility != "" {
  94. overwriteDefault = &models.CreateUserOverwriteOptions{
  95. Visibility: api.VisibilityModes[form.Visibility],
  96. }
  97. }
  98. if err := models.CreateUser(u, overwriteDefault); err != nil {
  99. if models.IsErrUserAlreadyExist(err) ||
  100. models.IsErrEmailAlreadyUsed(err) ||
  101. models.IsErrNameReserved(err) ||
  102. models.IsErrNameCharsNotAllowed(err) ||
  103. models.IsErrEmailInvalid(err) ||
  104. models.IsErrNamePatternNotAllowed(err) {
  105. ctx.Error(http.StatusUnprocessableEntity, "", err)
  106. } else {
  107. ctx.Error(http.StatusInternalServerError, "CreateUser", err)
  108. }
  109. return
  110. }
  111. log.Trace("Account created by admin (%s): %s", ctx.User.Name, u.Name)
  112. // Send email notification.
  113. if form.SendNotify {
  114. mailer.SendRegisterNotifyMail(u)
  115. }
  116. ctx.JSON(http.StatusCreated, convert.ToUser(u, ctx.User))
  117. }
  118. // EditUser api for modifying a user's information
  119. func EditUser(ctx *context.APIContext) {
  120. // swagger:operation PATCH /admin/users/{username} admin adminEditUser
  121. // ---
  122. // summary: Edit an existing user
  123. // consumes:
  124. // - application/json
  125. // produces:
  126. // - application/json
  127. // parameters:
  128. // - name: username
  129. // in: path
  130. // description: username of user to edit
  131. // type: string
  132. // required: true
  133. // - name: body
  134. // in: body
  135. // schema:
  136. // "$ref": "#/definitions/EditUserOption"
  137. // responses:
  138. // "200":
  139. // "$ref": "#/responses/User"
  140. // "403":
  141. // "$ref": "#/responses/forbidden"
  142. // "422":
  143. // "$ref": "#/responses/validationError"
  144. form := web.GetForm(ctx).(*api.EditUserOption)
  145. u := user.GetUserByParams(ctx)
  146. if ctx.Written() {
  147. return
  148. }
  149. parseLoginSource(ctx, u, form.SourceID, form.LoginName)
  150. if ctx.Written() {
  151. return
  152. }
  153. if len(form.Password) != 0 {
  154. if !password.IsComplexEnough(form.Password) {
  155. err := errors.New("PasswordComplexity")
  156. ctx.Error(http.StatusBadRequest, "PasswordComplexity", err)
  157. return
  158. }
  159. pwned, err := password.IsPwned(ctx, form.Password)
  160. if pwned {
  161. if err != nil {
  162. log.Error(err.Error())
  163. }
  164. ctx.Data["Err_Password"] = true
  165. ctx.Error(http.StatusBadRequest, "PasswordPwned", errors.New("PasswordPwned"))
  166. return
  167. }
  168. if u.Salt, err = models.GetUserSalt(); err != nil {
  169. ctx.Error(http.StatusInternalServerError, "UpdateUser", err)
  170. return
  171. }
  172. if err = u.SetPassword(form.Password); err != nil {
  173. ctx.InternalServerError(err)
  174. return
  175. }
  176. }
  177. if form.MustChangePassword != nil {
  178. u.MustChangePassword = *form.MustChangePassword
  179. }
  180. u.LoginName = form.LoginName
  181. if form.FullName != nil {
  182. u.FullName = *form.FullName
  183. }
  184. if form.Email != nil {
  185. u.Email = *form.Email
  186. if len(u.Email) == 0 {
  187. ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("email is not allowed to be empty string"))
  188. return
  189. }
  190. }
  191. if form.Website != nil {
  192. u.Website = *form.Website
  193. }
  194. if form.Location != nil {
  195. u.Location = *form.Location
  196. }
  197. if form.Description != nil {
  198. u.Description = *form.Description
  199. }
  200. if form.Active != nil {
  201. u.IsActive = *form.Active
  202. }
  203. if len(form.Visibility) != 0 {
  204. u.Visibility = api.VisibilityModes[form.Visibility]
  205. }
  206. if form.Admin != nil {
  207. u.IsAdmin = *form.Admin
  208. }
  209. if form.AllowGitHook != nil {
  210. u.AllowGitHook = *form.AllowGitHook
  211. }
  212. if form.AllowImportLocal != nil {
  213. u.AllowImportLocal = *form.AllowImportLocal
  214. }
  215. if form.MaxRepoCreation != nil {
  216. u.MaxRepoCreation = *form.MaxRepoCreation
  217. }
  218. if form.AllowCreateOrganization != nil {
  219. u.AllowCreateOrganization = *form.AllowCreateOrganization
  220. }
  221. if form.ProhibitLogin != nil {
  222. u.ProhibitLogin = *form.ProhibitLogin
  223. }
  224. if form.Restricted != nil {
  225. u.IsRestricted = *form.Restricted
  226. }
  227. if err := models.UpdateUser(u); err != nil {
  228. if models.IsErrEmailAlreadyUsed(err) || models.IsErrEmailInvalid(err) {
  229. ctx.Error(http.StatusUnprocessableEntity, "", err)
  230. } else {
  231. ctx.Error(http.StatusInternalServerError, "UpdateUser", err)
  232. }
  233. return
  234. }
  235. log.Trace("Account profile updated by admin (%s): %s", ctx.User.Name, u.Name)
  236. ctx.JSON(http.StatusOK, convert.ToUser(u, ctx.User))
  237. }
  238. // DeleteUser api for deleting a user
  239. func DeleteUser(ctx *context.APIContext) {
  240. // swagger:operation DELETE /admin/users/{username} admin adminDeleteUser
  241. // ---
  242. // summary: Delete a user
  243. // produces:
  244. // - application/json
  245. // parameters:
  246. // - name: username
  247. // in: path
  248. // description: username of user to delete
  249. // type: string
  250. // required: true
  251. // responses:
  252. // "204":
  253. // "$ref": "#/responses/empty"
  254. // "403":
  255. // "$ref": "#/responses/forbidden"
  256. // "422":
  257. // "$ref": "#/responses/validationError"
  258. u := user.GetUserByParams(ctx)
  259. if ctx.Written() {
  260. return
  261. }
  262. if u.IsOrganization() {
  263. ctx.Error(http.StatusUnprocessableEntity, "", fmt.Errorf("%s is an organization not a user", u.Name))
  264. return
  265. }
  266. if err := models.DeleteUser(u); err != nil {
  267. if models.IsErrUserOwnRepos(err) ||
  268. models.IsErrUserHasOrgs(err) {
  269. ctx.Error(http.StatusUnprocessableEntity, "", err)
  270. } else {
  271. ctx.Error(http.StatusInternalServerError, "DeleteUser", err)
  272. }
  273. return
  274. }
  275. log.Trace("Account deleted by admin(%s): %s", ctx.User.Name, u.Name)
  276. ctx.Status(http.StatusNoContent)
  277. }
  278. // CreatePublicKey api for creating a public key to a user
  279. func CreatePublicKey(ctx *context.APIContext) {
  280. // swagger:operation POST /admin/users/{username}/keys admin adminCreatePublicKey
  281. // ---
  282. // summary: Add a public key on behalf of a user
  283. // consumes:
  284. // - application/json
  285. // produces:
  286. // - application/json
  287. // parameters:
  288. // - name: username
  289. // in: path
  290. // description: username of the user
  291. // type: string
  292. // required: true
  293. // - name: key
  294. // in: body
  295. // schema:
  296. // "$ref": "#/definitions/CreateKeyOption"
  297. // responses:
  298. // "201":
  299. // "$ref": "#/responses/PublicKey"
  300. // "403":
  301. // "$ref": "#/responses/forbidden"
  302. // "422":
  303. // "$ref": "#/responses/validationError"
  304. form := web.GetForm(ctx).(*api.CreateKeyOption)
  305. u := user.GetUserByParams(ctx)
  306. if ctx.Written() {
  307. return
  308. }
  309. user.CreateUserPublicKey(ctx, *form, u.ID)
  310. }
  311. // DeleteUserPublicKey api for deleting a user's public key
  312. func DeleteUserPublicKey(ctx *context.APIContext) {
  313. // swagger:operation DELETE /admin/users/{username}/keys/{id} admin adminDeleteUserPublicKey
  314. // ---
  315. // summary: Delete a user's public key
  316. // produces:
  317. // - application/json
  318. // parameters:
  319. // - name: username
  320. // in: path
  321. // description: username of user
  322. // type: string
  323. // required: true
  324. // - name: id
  325. // in: path
  326. // description: id of the key to delete
  327. // type: integer
  328. // format: int64
  329. // required: true
  330. // responses:
  331. // "204":
  332. // "$ref": "#/responses/empty"
  333. // "403":
  334. // "$ref": "#/responses/forbidden"
  335. // "404":
  336. // "$ref": "#/responses/notFound"
  337. u := user.GetUserByParams(ctx)
  338. if ctx.Written() {
  339. return
  340. }
  341. if err := models.DeletePublicKey(u, ctx.ParamsInt64(":id")); err != nil {
  342. if models.IsErrKeyNotExist(err) {
  343. ctx.NotFound()
  344. } else if models.IsErrKeyAccessDenied(err) {
  345. ctx.Error(http.StatusForbidden, "", "You do not have access to this key")
  346. } else {
  347. ctx.Error(http.StatusInternalServerError, "DeleteUserPublicKey", err)
  348. }
  349. return
  350. }
  351. log.Trace("Key deleted by admin(%s): %s", ctx.User.Name, u.Name)
  352. ctx.Status(http.StatusNoContent)
  353. }
  354. //GetAllUsers API for getting information of all the users
  355. func GetAllUsers(ctx *context.APIContext) {
  356. // swagger:operation GET /admin/users admin adminGetAllUsers
  357. // ---
  358. // summary: List all users
  359. // produces:
  360. // - application/json
  361. // parameters:
  362. // - name: page
  363. // in: query
  364. // description: page number of results to return (1-based)
  365. // type: integer
  366. // - name: limit
  367. // in: query
  368. // description: page size of results
  369. // type: integer
  370. // responses:
  371. // "200":
  372. // "$ref": "#/responses/UserList"
  373. // "403":
  374. // "$ref": "#/responses/forbidden"
  375. listOptions := utils.GetListOptions(ctx)
  376. users, maxResults, err := models.SearchUsers(&models.SearchUserOptions{
  377. Actor: ctx.User,
  378. Type: models.UserTypeIndividual,
  379. OrderBy: models.SearchOrderByAlphabetically,
  380. ListOptions: listOptions,
  381. })
  382. if err != nil {
  383. ctx.Error(http.StatusInternalServerError, "GetAllUsers", err)
  384. return
  385. }
  386. results := make([]*api.User, len(users))
  387. for i := range users {
  388. results[i] = convert.ToUser(users[i], ctx.User)
  389. }
  390. ctx.SetLinkHeader(int(maxResults), listOptions.PageSize)
  391. ctx.SetTotalCountHeader(maxResults)
  392. ctx.JSON(http.StatusOK, &results)
  393. }