user.go 1.7 KB

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