town/cmd/registeruser/main.go

80 lines
1.5 KiB
Go
Raw Permalink Normal View History

2023-03-04 01:15:09 +00:00
package main
2023-03-04 22:19:27 +00:00
import (
2023-03-06 18:18:24 +00:00
"encoding/json"
"errors"
2023-03-04 22:19:27 +00:00
"fmt"
"os"
2023-03-06 20:34:29 +00:00
// _ "github.com/mattn/go-sqlite3"
2023-03-04 22:19:27 +00:00
"git.tilde.town/tildetown/town/towndb"
)
2023-03-04 01:15:09 +00:00
2023-03-06 18:18:24 +00:00
// this command adds a new user to /town/var/town.db. it's meant to be invoked
// by the welcome binary upon successfully creating a new user account
2023-03-04 22:19:27 +00:00
2023-03-06 20:34:29 +00:00
func main() {
tdb, err := towndb.ConnectDB()
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(1)
}
userData, err := parseInput(os.Stdin)
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(2)
}
if err = validateInput(userData); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(3)
}
if err = userData.Insert(tdb); err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(4)
}
}
func validateInput(userData towndb.TownUser) error {
2023-03-06 18:18:24 +00:00
if userData.Username == "" {
return errors.New("no username")
}
if len(userData.Emails) == 0 {
return errors.New("no email set")
}
for _, e := range userData.Emails {
if e == "" {
return errors.New("blank email in email list")
}
}
if userData.IsAdmin {
return errors.New("please stop")
}
if userData.State != towndb.StateActive {
return errors.New("bad state")
}
2023-03-06 20:34:29 +00:00
return nil
2023-03-06 18:18:24 +00:00
}
func parseInput(stdin *os.File) (u towndb.TownUser, err error) {
var n int
input := make([]byte, 3000) // arbitrary
if n, err = stdin.Read(input); err != nil {
return
}
if n == 0 {
err = errors.New("nothing passed on input")
return
}
err = json.Unmarshal(input[0:n], &u)
return
2023-03-04 22:19:27 +00:00
}