package repl import ( "encoding/hex" "fmt" "os" "github.com/spf13/cobra" "gitlink.org.cn/cloudream/jcs-pub/coordinator/internal/db" cortypes "gitlink.org.cn/cloudream/jcs-pub/coordinator/types" "golang.org/x/crypto/bcrypt" "golang.org/x/term" ) func init() { userCmd := &cobra.Command{ Use: "user", Short: "user command", } RootCmd.AddCommand(userCmd) createCmd := &cobra.Command{ Use: "create [account] [nickName]", Short: "create a new user account", Args: cobra.ExactArgs(2), Run: func(cmd *cobra.Command, args []string) { userCreate(GetCmdCtx(cmd), args[0], args[1]) }, } userCmd.AddCommand(createCmd) } func userCreate(ctx *CommandContext, account string, nickName string) { _, err := ctx.repl.db.User().GetByAccount(ctx.repl.db.DefCtx(), account) if err == nil { fmt.Printf("user %s already exists\n", account) return } fmt.Printf("input account password: ") pass, err := term.ReadPassword(int(os.Stdin.Fd())) if err != nil { fmt.Println("error reading password:", err) return } passHash, err := bcrypt.GenerateFromPassword(pass, bcrypt.DefaultCost) if err != nil { fmt.Println("error hashing password:", err) return } user, err := db.DoTx02(ctx.repl.db, func(tx db.SQLContext) (cortypes.User, error) { return ctx.repl.db.User().Create(tx, account, hex.EncodeToString(passHash), nickName) }) if err != nil { fmt.Println("error creating user:", err) return } fmt.Printf("user %s created\n", user.Account) }