userutil.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright 2022 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 userutil
  5. import (
  6. "encoding/hex"
  7. "fmt"
  8. "image/png"
  9. "os"
  10. "path/filepath"
  11. "strconv"
  12. "strings"
  13. "github.com/pkg/errors"
  14. "gogs.io/gogs/internal/avatar"
  15. "gogs.io/gogs/internal/conf"
  16. "gogs.io/gogs/internal/tool"
  17. )
  18. // DashboardURLPath returns the URL path to the user or organization dashboard.
  19. func DashboardURLPath(name string, isOrganization bool) string {
  20. if isOrganization {
  21. return conf.Server.Subpath + "/org/" + name + "/dashboard/"
  22. }
  23. return conf.Server.Subpath + "/"
  24. }
  25. // GenerateActivateCode generates an activate code based on user information and
  26. // the given email.
  27. func GenerateActivateCode(userID int64, email, name, password, rands string) string {
  28. code := tool.CreateTimeLimitCode(
  29. fmt.Sprintf("%d%s%s%s%s", userID, email, strings.ToLower(name), password, rands),
  30. conf.Auth.ActivateCodeLives,
  31. nil,
  32. )
  33. // Add tailing hex username
  34. code += hex.EncodeToString([]byte(strings.ToLower(name)))
  35. return code
  36. }
  37. // CustomAvatarPath returns the absolute path of the user custom avatar file.
  38. func CustomAvatarPath(userID int64) string {
  39. return filepath.Join(conf.Picture.AvatarUploadPath, strconv.FormatInt(userID, 10))
  40. }
  41. // GenerateRandomAvatar generates a random avatar and stores to local file
  42. // system using given user information.
  43. func GenerateRandomAvatar(userID int64, name, email string) error {
  44. seed := email
  45. if seed == "" {
  46. seed = name
  47. }
  48. img, err := avatar.RandomImage([]byte(seed))
  49. if err != nil {
  50. return errors.Wrap(err, "generate random image")
  51. }
  52. avatarPath := CustomAvatarPath(userID)
  53. err = os.MkdirAll(filepath.Dir(avatarPath), os.ModePerm)
  54. if err != nil {
  55. return errors.Wrap(err, "create avatar directory")
  56. }
  57. f, err := os.Create(avatarPath)
  58. if err != nil {
  59. return errors.Wrap(err, "create avatar file")
  60. }
  61. defer func() { _ = f.Close() }()
  62. if err = png.Encode(f, img); err != nil {
  63. return errors.Wrap(err, "encode avatar image to file")
  64. }
  65. return nil
  66. }