user.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. // Copyright 2014 The Gogs 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 v1
  5. import (
  6. "github.com/Unknwon/com"
  7. api "github.com/gogits/go-gogs-client"
  8. "github.com/gogits/gogs/models"
  9. "github.com/gogits/gogs/modules/base"
  10. "github.com/gogits/gogs/modules/middleware"
  11. )
  12. // ToApiUser converts user to API format.
  13. func ToApiUser(u *models.User) *api.User {
  14. return &api.User{
  15. ID: u.Id,
  16. UserName: u.Name,
  17. FullName: u.FullName,
  18. Email: u.Email,
  19. AvatarUrl: u.AvatarLink(),
  20. }
  21. }
  22. func SearchUsers(ctx *middleware.Context) {
  23. opt := models.SearchOption{
  24. Keyword: ctx.Query("q"),
  25. Limit: com.StrTo(ctx.Query("limit")).MustInt(),
  26. }
  27. if opt.Limit == 0 {
  28. opt.Limit = 10
  29. }
  30. us, err := models.SearchUserByName(opt)
  31. if err != nil {
  32. ctx.JSON(500, map[string]interface{}{
  33. "ok": false,
  34. "error": err.Error(),
  35. })
  36. return
  37. }
  38. results := make([]*api.User, len(us))
  39. for i := range us {
  40. results[i] = &api.User{
  41. ID: us[i].Id,
  42. UserName: us[i].Name,
  43. AvatarUrl: us[i].AvatarLink(),
  44. FullName: us[i].FullName,
  45. }
  46. if ctx.IsSigned {
  47. results[i].Email = us[i].Email
  48. }
  49. }
  50. ctx.Render.JSON(200, map[string]interface{}{
  51. "ok": true,
  52. "data": results,
  53. })
  54. }
  55. // GET /users/:username
  56. func GetUserInfo(ctx *middleware.Context) {
  57. u, err := models.GetUserByName(ctx.Params(":username"))
  58. if err != nil {
  59. if models.IsErrUserNotExist(err) {
  60. ctx.Error(404)
  61. } else {
  62. ctx.JSON(500, &base.ApiJsonErr{"GetUserByName: " + err.Error(), base.DOC_URL})
  63. }
  64. return
  65. }
  66. // Hide user e-mail when API caller isn't signed in.
  67. if !ctx.IsSigned {
  68. u.Email = ""
  69. }
  70. ctx.JSON(200, &api.User{u.Id, u.Name, u.FullName, u.Email, u.AvatarLink()})
  71. }