gitea源码

admin_user_delete.go 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright 2023 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package cmd
  4. import (
  5. "context"
  6. "errors"
  7. "fmt"
  8. "strings"
  9. user_model "code.gitea.io/gitea/models/user"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/storage"
  12. user_service "code.gitea.io/gitea/services/user"
  13. "github.com/urfave/cli/v3"
  14. )
  15. func microcmdUserDelete() *cli.Command {
  16. return &cli.Command{
  17. Name: "delete",
  18. Usage: "Delete specific user by id, name or email",
  19. Flags: []cli.Flag{
  20. &cli.Int64Flag{
  21. Name: "id",
  22. Usage: "ID of user of the user to delete",
  23. },
  24. &cli.StringFlag{
  25. Name: "username",
  26. Aliases: []string{"u"},
  27. Usage: "Username of the user to delete",
  28. },
  29. &cli.StringFlag{
  30. Name: "email",
  31. Aliases: []string{"e"},
  32. Usage: "Email of the user to delete",
  33. },
  34. &cli.BoolFlag{
  35. Name: "purge",
  36. Usage: "Purge user, all their repositories, organizations and comments",
  37. },
  38. },
  39. Action: runDeleteUser,
  40. }
  41. }
  42. func runDeleteUser(ctx context.Context, c *cli.Command) error {
  43. if !c.IsSet("id") && !c.IsSet("username") && !c.IsSet("email") {
  44. return errors.New("You must provide the id, username or email of a user to delete")
  45. }
  46. if !setting.IsInTesting {
  47. if err := initDB(ctx); err != nil {
  48. return err
  49. }
  50. }
  51. if err := storage.Init(); err != nil {
  52. return err
  53. }
  54. var err error
  55. var user *user_model.User
  56. if c.IsSet("email") {
  57. user, err = user_model.GetUserByEmail(ctx, c.String("email"))
  58. } else if c.IsSet("username") {
  59. user, err = user_model.GetUserByName(ctx, c.String("username"))
  60. } else {
  61. user, err = user_model.GetUserByID(ctx, c.Int64("id"))
  62. }
  63. if err != nil {
  64. return err
  65. }
  66. if c.IsSet("username") && user.LowerName != strings.ToLower(strings.TrimSpace(c.String("username"))) {
  67. return fmt.Errorf("the user %s who has email %s does not match the provided username %s", user.Name, c.String("email"), c.String("username"))
  68. }
  69. if c.IsSet("id") && user.ID != c.Int64("id") {
  70. return fmt.Errorf("the user %s does not match the provided id %d", user.Name, c.Int64("id"))
  71. }
  72. return user_service.DeleteUser(ctx, user, c.Bool("purge"))
  73. }