Add ability to change password

This commit is contained in:
Thorben Günther 2020-04-08 12:59:50 +02:00 committed by Simon Ser
parent 155f35bd84
commit 148bbc8102
No known key found for this signature in database
GPG Key ID: 0FDE7BE0E88F5E48
2 changed files with 42 additions and 2 deletions

View File

@ -15,6 +15,7 @@ import (
const usage = `usage: sojuctl [-config path] <action> [options...] const usage = `usage: sojuctl [-config path] <action> [options...]
create-user <username> Create a new user create-user <username> Create a new user
change-password <username> Change password for a user
help Show this help message help Show this help message
` `
@ -72,6 +73,33 @@ func main() {
if err := db.CreateUser(&user); err != nil { if err := db.CreateUser(&user); err != nil {
log.Fatalf("failed to create user: %v", err) log.Fatalf("failed to create user: %v", err)
} }
case "change-password":
username := flag.Arg(1)
if username == "" {
flag.Usage()
os.Exit(1)
}
fmt.Printf("New password: ")
password, err := terminal.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
log.Fatalf("failed to read new password: %v", err)
}
fmt.Printf("\n")
hashed, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
if err != nil {
log.Fatalf("failed to hash password: %v", err)
}
user := soju.User{
Username: username,
Password: string(hashed),
}
if err := db.UpdatePassword(&user); err != nil {
log.Fatalf("failed to update password: %v", err)
}
default: default:
flag.Usage() flag.Usage()
if cmd != "help" { if cmd != "help" {

12
db.go
View File

@ -132,6 +132,18 @@ func (db *DB) CreateUser(user *User) error {
return err return err
} }
func (db *DB) UpdatePassword(user *User) error {
db.lock.Lock()
defer db.lock.Unlock()
password := toStringPtr(user.Password)
_, err := db.db.Exec(`UPDATE User
SET password = ?
WHERE username = ?`,
password, user.Username)
return err
}
func (db *DB) ListNetworks(username string) ([]Network, error) { func (db *DB) ListNetworks(username string) ([]Network, error) {
db.lock.RLock() db.lock.RLock()
defer db.lock.RUnlock() defer db.lock.RUnlock()