intake/cmd/passwd.go

82 lines
1.8 KiB
Go
Raw Normal View History

2025-01-21 16:42:59 +00:00
package cmd
import (
2025-02-05 04:22:50 +00:00
"bufio"
2025-02-02 08:20:51 +00:00
"fmt"
"os"
2025-01-21 16:42:59 +00:00
2025-02-02 08:20:51 +00:00
"github.com/Jaculabilis/intake/core"
2025-01-21 16:42:59 +00:00
"github.com/spf13/cobra"
2025-02-02 08:20:51 +00:00
"golang.org/x/term"
2025-01-21 16:42:59 +00:00
)
var passwdCmd = &cobra.Command{
Use: "passwd",
Short: "Set the password for the web interface",
2025-02-02 08:20:51 +00:00
Long: `Set the password for the web interface.
Access through the command line should be controlled by standard filesystem
permissions.
2025-02-05 04:22:50 +00:00
passwd expects to be run from a tty. If you want to pipe the password in, use
the --stdin flag.
2025-01-21 16:42:59 +00:00
`,
Run: func(cmd *cobra.Command, args []string) {
2025-02-05 04:22:50 +00:00
passwd(boolArg(cmd, "verify"), boolArg(cmd, "stdin"))
2025-01-21 16:42:59 +00:00
},
}
func init() {
rootCmd.AddCommand(passwdCmd)
2025-02-02 08:20:51 +00:00
passwdCmd.Flags().Bool("verify", false, "Compare the input password instead of setting it.")
2025-02-05 04:22:50 +00:00
passwdCmd.Flags().Bool("stdin", false, "Read the password from stdin. Terminal whitespace is stripped.")
2025-02-02 08:20:51 +00:00
}
2025-02-05 04:22:50 +00:00
func passwd(verify bool, stdin bool) {
2025-02-02 08:20:51 +00:00
db := openAndMigrateDb()
2025-02-05 04:22:50 +00:00
var password string
if stdin {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
password = scanner.Text()
break
}
if scanner.Err() != nil {
fmt.Printf("error: failed to read password: %v", scanner.Err())
os.Exit(1)
}
} else {
fmt.Print("Enter your password: ")
bytes, err := term.ReadPassword(int(os.Stdin.Fd()))
if err != nil {
fmt.Printf("error: failed to read password: %v\n", err)
os.Exit(1)
}
password = string(bytes)
fmt.Println()
2025-02-02 08:20:51 +00:00
}
if verify {
match, err := core.CheckPassword(db, password)
if err != nil {
fmt.Printf("error: failed to check password: %v\n", err)
os.Exit(1)
}
if match {
fmt.Println("correct!")
os.Exit(0)
} else {
fmt.Println("incorrect")
os.Exit(1)
}
}
2025-02-05 04:22:50 +00:00
err := core.SetPassword(db, password)
2025-02-02 08:20:51 +00:00
if err != nil {
fmt.Printf("failed to set password: %v\n", err)
}
fmt.Println("password set")
2025-01-21 16:42:59 +00:00
}