33 lines
837 B
Go
33 lines
837 B
Go
package runcmd
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/kanootoko/codevault/internal/auth"
|
|
"github.com/kanootoko/codevault/internal/db"
|
|
)
|
|
|
|
// AddUser opens (creating if necessary) the database at dbPath and upserts a
|
|
// user with the given login/password. It intentionally does not depend on the
|
|
// application config.
|
|
func AddUser(dbPath, login, password string) error {
|
|
database, err := db.Open(dbPath)
|
|
if err != nil {
|
|
return fmt.Errorf("error on opening database: %w", err)
|
|
}
|
|
defer func() { _ = database.Close() }()
|
|
|
|
hash, err := auth.Hash(login, password)
|
|
if err != nil {
|
|
return fmt.Errorf("error on hashing password: %w", err)
|
|
}
|
|
|
|
users := db.NewUsersRepository(database)
|
|
if err := users.Upsert(context.Background(), login, hash); err != nil {
|
|
return fmt.Errorf("error on upserting user: %w", err)
|
|
}
|
|
|
|
return nil
|
|
}
|