user.go 1.5 KB

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