Add command to update the password

This commit is contained in:
Andreas Schneider 2020-11-01 12:07:55 +01:00
parent 756f6c5f29
commit 652e3086d5
1 changed files with 27 additions and 16 deletions

View File

@ -27,15 +27,14 @@ package main
import (
"fmt"
"os"
"golang.org/x/crypto/bcrypt"
)
type CmdUser struct {
CmdList CmdUserList `cmd:"" name:"list" help:"List all users."`
CmdAdd CmdUserAdd `cmd:"" name:"add" help:"Add a user."`
CmdUpdate CmdUserUpdate `cmd:"" name:"update" help:"Update a user."`
CmdDelete CmdUserDelete `cmd:"" name:"delete" help:"Delete a user."`
CmdList CmdUserList `cmd:"" name:"list" help:"List all users."`
CmdAdd CmdUserAdd `cmd:"" name:"add" help:"Add a user."`
CmdUpdate CmdUserUpdate `cmd:"" name:"update" help:"Update a user."`
CmdPassword CmdUserPassword `cmd:"" name:"password" help:"Change the password of a user."`
CmdDelete CmdUserDelete `cmd:"" name:"delete" help:"Delete a user."`
}
type CmdUserList struct{}
@ -82,7 +81,6 @@ func (cmd CmdUserAdd) Run(app *app) error {
type CmdUserUpdate struct {
Username string `arg:"" name:"username" help:"The username of the user to be updated."`
Password string `name:"password" help:"Update the password, if set."`
Role GlobalRole `name:"role" default:"user" help:"Update the role, if set. 'admin' or ' user'"`
}
@ -106,15 +104,6 @@ func (cmd CmdUserUpdate) Run(app *app) error {
changed = true
}
if cmd.Password != "" {
hash, err := bcrypt.GenerateFromPassword([]byte(cmd.Password), 0)
if err != nil {
return fmt.Errorf("cannot hash password: %w", err)
}
user.Password = string(hash)
changed = true
}
if !changed {
// Nothing changed. Nothing to write. Not different from a successful write to the user.
return nil
@ -123,6 +112,28 @@ func (cmd CmdUserUpdate) Run(app *app) error {
return app.userStore.UpdateUser(user)
}
type CmdUserPassword struct {
Username string `arg:"" name:"username" help:"The username of the user to be updated."`
PasswordParam
}
func (cmd CmdUserPassword) Run(app *app) error {
user, err := app.userStore.GetUser(cmd.Username)
if err != nil {
return err
}
password, err := cmd.acquirePassword()
if err != nil {
return fmt.Errorf("cannot acquire password for user: %w", err)
}
return app.userStore.UpdateUser(User{
Username: user.Username,
Password: password,
})
}
type CmdUserDelete struct {
Username string `arg:"" name:"username" help:"The username of the user to be deleted."`
}