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