aboutsummaryrefslogtreecommitdiff
path: root/app/cmd/user.go
diff options
context:
space:
mode:
authorAlexander NeonXP Kiryukhin <i@neonxp.ru>2024-07-21 19:26:56 +0300
committerAlexander NeonXP Kiryukhin <i@neonxp.ru>2024-07-21 19:28:56 +0300
commitce3111b0efe91e275ce070f9511b5b1b9801a46d (patch)
tree09fa4f10dfb1e17761339c798eefa73c6b18484f /app/cmd/user.go
parente9a64f3b41b5eae47dec7c0ecfd1caae83136abc (diff)
Множество улучшенийv0.0.2
Diffstat (limited to 'app/cmd/user.go')
-rw-r--r--app/cmd/user.go80
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)
+}