diff options
Diffstat (limited to 'app/cmd/user.go')
-rw-r--r-- | app/cmd/user.go | 80 |
1 files changed, 80 insertions, 0 deletions
diff --git a/app/cmd/user.go b/app/cmd/user.go new file mode 100644 index 0000000..673c7b8 --- /dev/null +++ b/app/cmd/user.go @@ -0,0 +1,80 @@ +package cmd + +import ( + "bufio" + "fmt" + "os" + + "github.com/spf13/cobra" + "gitrepo.ru/neonxp/gorum/db" + "gitrepo.ru/neonxp/gorum/models" + "gitrepo.ru/neonxp/gorum/repository" +) + +var userCmd = &cobra.Command{ + Use: "user", + Short: "User managment", +} + +var createUserCmd = &cobra.Command{ + Use: "add", + Args: cobra.ExactArgs(3), + ArgAliases: []string{"username", "email", "role"}, + RunE: func(cmd *cobra.Command, args []string) error { + orm, err := db.GetDB(dbFile) + if err != nil { + return fmt.Errorf("failed init db: %w", err) + } + username := args[0] + email := args[1] + role := args[2] + iRole := models.RoleUser + switch role { + case "admin": + iRole = models.RoleAdmin + case "moderator": + iRole = models.RoleModerator + } + reader := bufio.NewReader(os.Stdin) + fmt.Printf("Enter password for user %s: ", username) + password, _ := reader.ReadString('\n') + + ur := repository.NewUser(orm) + id, err := ur.Create(cmd.Context(), email, password, username, iRole) + if err != nil { + return fmt.Errorf("failed create user: %w", err) + } + + fmt.Printf("Created user %s (id=%d, email=%s, role_id=%d)\n", username, id, email, iRole) + + return nil + }, +} + +var listUserCmd = &cobra.Command{ + Use: "list", + RunE: func(cmd *cobra.Command, args []string) error { + orm, err := db.GetDB(dbFile) + if err != nil { + return fmt.Errorf("failed init db: %w", err) + } + + ur := repository.NewUser(orm) + users, err := ur.List(cmd.Context()) + if err != nil { + return err + } + + fmt.Printf("ID\tUsername\tEmail\tRole\n") + for _, u := range users { + fmt.Printf("%d\t%s\t%s\t%d\n", u.ID, u.Username, u.Email, u.Role) + } + + return nil + }, +} + +func init() { + userCmd.AddCommand(createUserCmd) + userCmd.AddCommand(listUserCmd) +} |