1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
package cmd
import (
"bufio"
"fmt"
"os"
"github.com/spf13/cobra"
"gitrepo.ru/neonxp/gorum/models"
"gitrepo.ru/neonxp/gorum/repository"
"go.etcd.io/bbolt"
)
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 := bbolt.Open(dbFile, 0600, nil)
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)
if err := ur.Create(email, password, username, iRole); err != nil {
return fmt.Errorf("failed create user: %w", err)
}
fmt.Printf("Created user %s (email=%s, role_id=%d)\n", username, email, iRole)
return nil
},
}
var listUserCmd = &cobra.Command{
Use: "list",
RunE: func(cmd *cobra.Command, args []string) error {
orm, err := bbolt.Open(dbFile, 0600, nil)
if err != nil {
return fmt.Errorf("failed init db: %w", err)
}
ur := repository.NewUser(orm)
users, err := ur.List()
if err != nil {
return err
}
fmt.Printf("Username\tEmail\tRole\n")
for _, u := range users {
fmt.Printf("%s\t%s\t%d\n", u.Username, u.Email, u.Role)
}
return nil
},
}
func init() {
userCmd.AddCommand(createUserCmd)
userCmd.AddCommand(listUserCmd)
}
|