forked from boyska/feedpanel
120 lines
2.4 KiB
Go
120 lines
2.4 KiB
Go
package main
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
"os"
|
|
|
|
paneldb "git.lattuga.net/boyska/feedpanel/db"
|
|
"github.com/go-pg/pg"
|
|
"github.com/howeyc/gopass"
|
|
)
|
|
|
|
func getDB() paneldb.DB {
|
|
pgdb := pg.Connect(&pg.Options{
|
|
User: "panel",
|
|
Password: "panelpass",
|
|
Database: "feeds",
|
|
})
|
|
db := paneldb.DB{PgDB: pgdb}
|
|
return db
|
|
}
|
|
|
|
type commandFunc func([]string) error
|
|
|
|
func cmdSetup(_args []string) error {
|
|
db := getDB()
|
|
err := db.Setup()
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Println("All done")
|
|
os.Exit(0)
|
|
return nil
|
|
}
|
|
|
|
func askPassword() (string, error) {
|
|
fmt.Print("New password: ")
|
|
pass, err := gopass.GetPasswd()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
fmt.Print("Retype new password: ")
|
|
pass2, err := gopass.GetPasswd()
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if string(pass) != string(pass2) {
|
|
return "", fmt.Errorf("Passwords differ")
|
|
}
|
|
return string(pass), nil
|
|
}
|
|
|
|
func cmdAddUser(args []string) error {
|
|
flagset := flag.NewFlagSet(args[0], flag.ExitOnError)
|
|
password := flagset.String("password", "", "set password from command line; INSECURE!")
|
|
flagset.Parse(args[1:])
|
|
if len(flagset.Args()) < 2 {
|
|
fmt.Fprintf(os.Stderr, "Usage: %s [options] USER EMAIL\n", args[0])
|
|
flagset.PrintDefaults()
|
|
os.Exit(2)
|
|
}
|
|
user := flagset.Args()[0]
|
|
email := flagset.Args()[1]
|
|
if *password == "" {
|
|
pass, err := askPassword()
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "Error:", err)
|
|
os.Exit(1)
|
|
}
|
|
*password = string(pass)
|
|
}
|
|
db := getDB()
|
|
err := db.UserAdd(user, email, *password)
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
fmt.Printf("Success: user %s added\n", user)
|
|
os.Exit(0)
|
|
return nil
|
|
}
|
|
|
|
var cmdMap = map[string]commandFunc{
|
|
"setup": cmdSetup,
|
|
"adduser": cmdAddUser,
|
|
}
|
|
|
|
func usage(w io.Writer) {
|
|
fmt.Fprintf(w, "Usage: %s SUBCOMMAND [command args...]\n", os.Args[0])
|
|
fmt.Fprintln(w, "\nSubcommands:")
|
|
for cmdName, _ := range cmdMap {
|
|
fmt.Fprintln(w, " -", cmdName)
|
|
}
|
|
}
|
|
|
|
func main() {
|
|
flag.Parse()
|
|
fmt.Println(flag.Args())
|
|
if len(flag.Args()) < 1 {
|
|
fmt.Fprintln(os.Stderr, "Not enough arguments!")
|
|
usage(os.Stderr)
|
|
os.Exit(2)
|
|
}
|
|
cmdName := flag.Args()[0]
|
|
cmdFunc, ok := cmdMap[cmdName]
|
|
if !ok {
|
|
fmt.Fprintf(os.Stderr, "Invalid command `%s`\n", cmdName)
|
|
usage(os.Stderr)
|
|
os.Exit(2)
|
|
}
|
|
err := cmdFunc(flag.Args())
|
|
if err != nil {
|
|
fmt.Fprintln(os.Stderr, "Error")
|
|
fmt.Fprintln(os.Stderr, err)
|
|
os.Exit(1)
|
|
}
|
|
os.Exit(0)
|
|
}
|