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 2.0KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // Copyright 2022 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package context
  4. import (
  5. "fmt"
  6. "net/http"
  7. "strings"
  8. org_model "code.gitea.io/gitea/models/organization"
  9. user_model "code.gitea.io/gitea/models/user"
  10. "code.gitea.io/gitea/modules/context"
  11. )
  12. // UserAssignmentWeb returns a middleware to handle context-user assignment for web routes
  13. func UserAssignmentWeb() func(ctx *context.Context) {
  14. return func(ctx *context.Context) {
  15. userAssignment(ctx, func(status int, title string, obj interface{}) {
  16. err, ok := obj.(error)
  17. if !ok {
  18. err = fmt.Errorf("%s", obj)
  19. }
  20. if status == http.StatusNotFound {
  21. ctx.NotFound(title, err)
  22. } else {
  23. ctx.ServerError(title, err)
  24. }
  25. })
  26. }
  27. }
  28. // UserAssignmentAPI returns a middleware to handle context-user assignment for api routes
  29. func UserAssignmentAPI() func(ctx *context.APIContext) {
  30. return func(ctx *context.APIContext) {
  31. userAssignment(ctx.Context, ctx.Error)
  32. }
  33. }
  34. func userAssignment(ctx *context.Context, errCb func(int, string, interface{})) {
  35. username := ctx.Params(":username")
  36. if ctx.IsSigned && ctx.Doer.LowerName == strings.ToLower(username) {
  37. ctx.ContextUser = ctx.Doer
  38. } else {
  39. var err error
  40. ctx.ContextUser, err = user_model.GetUserByName(ctx, username)
  41. if err != nil {
  42. if user_model.IsErrUserNotExist(err) {
  43. if redirectUserID, err := user_model.LookupUserRedirect(username); err == nil {
  44. context.RedirectToUser(ctx, username, redirectUserID)
  45. } else if user_model.IsErrUserRedirectNotExist(err) {
  46. errCb(http.StatusNotFound, "GetUserByName", err)
  47. } else {
  48. errCb(http.StatusInternalServerError, "LookupUserRedirect", err)
  49. }
  50. } else {
  51. errCb(http.StatusInternalServerError, "GetUserByName", err)
  52. }
  53. } else {
  54. if ctx.ContextUser.IsOrganization() {
  55. if ctx.Org == nil {
  56. ctx.Org = &context.Organization{}
  57. }
  58. ctx.Org.Organization = (*org_model.Organization)(ctx.ContextUser)
  59. ctx.Data["Org"] = ctx.Org.Organization
  60. }
  61. }
  62. }
  63. }