gitea源码

avatar.go 1.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package user
  4. import (
  5. "time"
  6. "code.gitea.io/gitea/models/avatars"
  7. user_model "code.gitea.io/gitea/models/user"
  8. "code.gitea.io/gitea/modules/httpcache"
  9. "code.gitea.io/gitea/services/context"
  10. )
  11. func cacheableRedirect(ctx *context.Context, location string) {
  12. // here we should not use `setting.StaticCacheTime`, it is pretty long (default: 6 hours)
  13. // we must make sure the redirection cache time is short enough, otherwise a user won't see the updated avatar in 6 hours
  14. // it's OK to make the cache time short, it is only a redirection, and doesn't cost much to make a new request
  15. httpcache.SetCacheControlInHeader(ctx.Resp.Header(), &httpcache.CacheControlOptions{MaxAge: 5 * time.Minute})
  16. ctx.Redirect(location)
  17. }
  18. // AvatarByUsernameSize redirect browser to user avatar of requested size
  19. func AvatarByUsernameSize(ctx *context.Context) {
  20. username := ctx.PathParam("username")
  21. user := user_model.GetSystemUserByName(username)
  22. if user == nil {
  23. var err error
  24. if user, err = user_model.GetUserByName(ctx, username); err != nil {
  25. ctx.NotFoundOrServerError("GetUserByName", user_model.IsErrUserNotExist, err)
  26. return
  27. }
  28. }
  29. cacheableRedirect(ctx, user.AvatarLinkWithSize(ctx, int(ctx.PathParamInt64("size"))))
  30. }
  31. // AvatarByEmailHash redirects the browser to the email avatar link
  32. func AvatarByEmailHash(ctx *context.Context) {
  33. hash := ctx.PathParam("hash")
  34. email, err := avatars.GetEmailForHash(ctx, hash)
  35. if err != nil {
  36. ctx.ServerError("invalid avatar hash: "+hash, err)
  37. return
  38. }
  39. size := ctx.FormInt("size")
  40. cacheableRedirect(ctx, avatars.GenerateEmailAvatarFinalLink(ctx, email, size))
  41. }