vague unfucking, work on db, test stubs and imp for user-register

trunk
vilmibm 2022-06-14 17:03:46 -05:00
parent 98f6d67eca
commit 7fd2547cd1
6 changed files with 373 additions and 323 deletions

7
go.mod
View File

@ -4,6 +4,7 @@ go 1.18
require gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b require gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b
require github.com/mattn/go-sqlite3 v1.14.12 require (
github.com/google/uuid v1.3.0
require github.com/google/uuid v1.3.0 // indirect github.com/mattn/go-sqlite3 v1.14.12
)

View File

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"strings" "strings"
"time"
"git.tilde.town/tildetown/bbj2/server/cmd/config" "git.tilde.town/tildetown/bbj2/server/cmd/config"
"git.tilde.town/tildetown/bbj2/server/cmd/db" "git.tilde.town/tildetown/bbj2/server/cmd/db"
@ -20,6 +21,14 @@ func (e *HTTPError) Error() string {
return fmt.Sprintf("%d %s", e.Code, e.Msg) return fmt.Sprintf("%d %s", e.Code, e.Msg)
} }
func badMethod() error {
return &HTTPError{Code: 400, Msg: "bad method"}
}
func invalidArgs(msg string) error {
return &HTTPError{Code: 400, Msg: fmt.Sprintf("invalid args: %s", msg)}
}
type BBJResponse struct { type BBJResponse struct {
Error bool `json:"error"` Error bool `json:"error"`
Data interface{} `json:"data"` Data interface{} `json:"data"`
@ -66,6 +75,7 @@ func Invoke(w http.ResponseWriter, apiFn APIHandler) {
} }
func getUserFromReq(opts config.Options, req *http.Request) (u *db.User, err error) { func getUserFromReq(opts config.Options, req *http.Request) (u *db.User, err error) {
// TODO abstract sql stuff into db
u = &db.User{} u = &db.User{}
u.Username = req.Header.Get("User") u.Username = req.Header.Get("User")
u.Hash = req.Header.Get("Auth") u.Hash = req.Header.Get("Auth")
@ -113,22 +123,74 @@ func (a *API) IsPost() bool {
return a.Req.Method == "POST" return a.Req.Method == "POST"
} }
func (a *API) InstanceInfo() (*BBJResponse, error) { func (a *API) InstanceInfo() (resp *BBJResponse, err error) {
if !a.IsGet() { if !a.IsGet() {
return nil, &HTTPError{Msg: "bad method", Code: 400} err = badMethod()
return
} }
return &BBJResponse{
resp = &BBJResponse{
Data: instanceInfo{ Data: instanceInfo{
InstanceName: a.Opts.Config.InstanceName, InstanceName: a.Opts.Config.InstanceName,
AllowAnon: a.Opts.Config.AllowAnon, AllowAnon: a.Opts.Config.AllowAnon,
Admins: a.Opts.Config.Admins, Admins: a.Opts.Config.Admins,
}, },
}, nil }
return
} }
func (a *API) UserRegister() (*BBJResponse, error) { func (a *API) UserRegister() (resp *BBJResponse, err error) {
if !a.IsPost() { if !a.IsPost() {
return nil, &HTTPError{Msg: "bad method", Code: 400} err = badMethod()
return
} }
return nil, nil type AuthArgs struct {
Username string `json:"user_name"`
Hash string `json:"auth_hash"`
}
var args AuthArgs
if err = json.NewDecoder(a.Req.Body).Decode(&args); err != nil {
err = invalidArgs(err.Error())
return
}
if args.Hash == "" || args.Username == "" {
err = invalidArgs(err.Error())
return
}
if err = checkAuth(a.Opts, args.Username, args.Hash); err == nil {
a.Opts.Logger.Printf("user %s already registered", args.Username)
err = &HTTPError{Code: 403, Msg: "user already exists"}
return
} else if err.Error() != "no such user" {
err = &HTTPError{Code: 500, Msg: err.Error()}
return
}
u := db.User{
Username: args.Username,
Hash: args.Hash,
Created: time.Now(), // TODO inject time
}
err = db.CreateUser(a.Opts.DB, u)
return
}
func checkAuth(opts config.Options, username, hash string) (err error) {
opts.Logger.Printf("querying for %s", username)
var user *db.User
if user, err = db.GetUserByName(opts.DB, username); err != nil {
return
}
if user.Hash != hash {
err = errors.New("bad credentials")
}
return
} }

View File

@ -1,8 +1,6 @@
package api package api
import ( import (
"bufio"
"bytes"
"log" "log"
"net/http" "net/http"
"os" "os"
@ -14,22 +12,14 @@ import (
"git.tilde.town/tildetown/bbj2/server/cmd/db" "git.tilde.town/tildetown/bbj2/server/cmd/db"
) )
func TestInstanceInfo(t *testing.T) { func createTestState() (opts *config.Options, err error) {
// TODO a lot of this needs to be cleaned up and generalized etc var dbFile *os.File
stderr := []byte{} if dbFile, err = os.CreateTemp("", "bbj2-test"); err != nil {
stdout := []byte{} return
testIO := config.IOStreams{
Err: bufio.NewWriter(bytes.NewBuffer(stderr)),
Out: bufio.NewWriter(bytes.NewBuffer(stdout)),
} }
dbFile, err := os.CreateTemp("", "bbj2-test")
if err != nil { opts = &config.Options{
t.Fatalf("failed to make test db: %s", err.Error()) Logger: log.New(os.Stdout, "bbj2 test", log.Lshortfile),
}
logger := log.New(os.Stdout, "bbj test", log.Lshortfile)
opts := config.Options{
IO: testIO,
Logger: logger,
Config: config.Config{ Config: config.Config{
Admins: []string{"jillValentine", "rebeccaChambers"}, Admins: []string{"jillValentine", "rebeccaChambers"},
Port: 666, Port: 666,
@ -40,7 +30,61 @@ func TestInstanceInfo(t *testing.T) {
}, },
} }
teardown, err := db.Setup(opts) return
}
func TestUserRegister(t *testing.T) {
opts, err := createTestState()
if err != nil {
t.Fatalf("failed to create test state: %s", err.Error())
return
}
ts := []struct {
name string
opts config.Options
setup func(opts *config.Options) error
assert func(t *testing.T) error
wantErr *HTTPError
}{
{
name: "user already exists",
opts: *opts,
setup: func(opts *config.Options) error {
// TODO
return nil
},
assert: func(t *testing.T) error {
// TODO
return nil
},
wantErr: &HTTPError{Code: 403, Msg: "user already exists"},
},
}
for _, tt := range ts {
t.Run(tt.name, func(t *testing.T) {
teardown, err := db.Setup(*opts)
if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error())
return
}
defer teardown()
// TODO
})
}
}
func TestInstanceInfo(t *testing.T) {
opts, err := createTestState()
if err != nil {
t.Fatalf("failed to create test state: %s", err.Error())
return
}
teardown, err := db.Setup(*opts)
if err != nil { if err != nil {
t.Fatalf("could not initialize DB: %s", err.Error()) t.Fatalf("could not initialize DB: %s", err.Error())
return return
@ -55,7 +99,7 @@ func TestInstanceInfo(t *testing.T) {
}{ }{
{ {
name: "basic", name: "basic",
opts: opts, opts: *opts,
wantData: instanceInfo{ wantData: instanceInfo{
InstanceName: "cool test zone", InstanceName: "cool test zone",
AllowAnon: true, AllowAnon: true,

View File

@ -3,7 +3,6 @@ package config
import ( import (
"database/sql" "database/sql"
"fmt" "fmt"
"io"
"log" "log"
"os" "os"
@ -17,11 +16,6 @@ const (
defaultDBPath = "db.sqlite3" defaultDBPath = "db.sqlite3"
) )
type IOStreams struct {
Err io.Writer
Out io.Writer
}
type Config struct { type Config struct {
Admins []string Admins []string
Port int Port int
@ -34,7 +28,6 @@ type Config struct {
type Options struct { type Options struct {
ConfigPath string ConfigPath string
IO IOStreams
Logger *log.Logger Logger *log.Logger
Log func(string) Log func(string)
Logf func(string, ...interface{}) Logf func(string, ...interface{})

View File

@ -10,6 +10,7 @@ import (
"time" "time"
"git.tilde.town/tildetown/bbj2/server/cmd/config" "git.tilde.town/tildetown/bbj2/server/cmd/config"
"github.com/google/uuid"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
) )
@ -25,6 +26,7 @@ type User struct {
ID string ID string
Username string Username string
Hash string Hash string
Created time.Time
} }
type Thread struct { type Thread struct {
@ -89,3 +91,36 @@ func EnsureSchema(opts config.Options) error {
return nil return nil
} }
func GetUserByName(db *sql.DB, username string) (u *User, err error) {
var stmt *sql.Stmt
stmt, err = db.Prepare("select auth_hash from users where user_name = ?")
if err != nil {
return
}
defer stmt.Close()
if err = stmt.QueryRow(username).Scan(&u); err != nil {
if strings.Contains(err.Error(), "no rows in result") {
err = errors.New("no such user")
}
}
return
}
func CreateUser(db *sql.DB, u User) (err error) {
var id uuid.UUID
if id, err = uuid.NewRandom(); err != nil {
return
}
var stmt *sql.Stmt
if stmt, err = db.Prepare(`INSERT INTO users VALUES(?, ?, ?, "", "", 0, 0, ?)`); err != nil {
return
}
defer stmt.Close()
_, err = stmt.Exec(id, u.Username, u.Hash, u.Created)
return
}

View File

@ -20,15 +20,10 @@ func main() {
var configFlag = flag.String("config", "config.yml", "A path to a config file.") var configFlag = flag.String("config", "config.yml", "A path to a config file.")
var resetFlag = flag.Bool("reset", false, "reset the database. WARNING this wipes everything.") var resetFlag = flag.Bool("reset", false, "reset the database. WARNING this wipes everything.")
flag.Parse() flag.Parse()
io := config.IOStreams{ logger := log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile)
Err: os.Stderr,
Out: os.Stdout,
}
logger := log.New(io.Out, "", log.Ldate|log.Ltime|log.Lshortfile)
opts := &config.Options{ opts := &config.Options{
ConfigPath: *configFlag, ConfigPath: *configFlag,
Reset: *resetFlag, Reset: *resetFlag,
IO: io,
Logger: logger, Logger: logger,
} }
@ -56,8 +51,7 @@ is wild; the error handling is really out of control. I need to think of abstrac
func _main(opts *config.Options) error { func _main(opts *config.Options) error {
cfg, err := config.ParseConfig(opts.ConfigPath) cfg, err := config.ParseConfig(opts.ConfigPath)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "could not read config file '%s'", opts.ConfigPath) return fmt.Errorf("could not read config file '%s'", opts.ConfigPath)
os.Exit(1)
} }
opts.Config = *cfg opts.Config = *cfg
@ -124,87 +118,9 @@ func setupAPI(opts config.Options) {
api.Invoke(w, a.UserRegister) api.Invoke(w, a.UserRegister)
})) }))
/* }
func checkAuth(opts config.Options, username, hash string) error {
db := opts.DB
stmt, err := db.Prepare("select auth_hash from users where user_name = ?")
if err != nil {
return fmt.Errorf("db error: %w", err)
}
defer stmt.Close()
opts.Logger.Printf("querying for %s", username)
var authHash string
if err = stmt.QueryRow(username).Scan(&authHash); err != nil {
if strings.Contains(err.Error(), "no rows in result") {
return errors.New("no such user")
}
return fmt.Errorf("db error: %w", err)
}
if authHash != hash {
return errors.New("bad credentials")
}
return nil
}
http.HandleFunc("/user_register", handler(opts, func(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
badMethod(w)
return
}
type AuthArgs struct {
Username string `json:"user_name"`
Hash string `json:"auth_hash"`
}
var args AuthArgs
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
}
if args.Hash == "" || args.Username == "" {
invalidArgs(w)
return
}
opts.Logf("querying for %s", args.Username)
if err := checkAuth(opts, args.Username, args.Hash); err == nil {
opts.Logf("found %s", args.Username)
// code 4 apparently
writeErrorResponse(w, 403, BBJResponse{
Error: true,
Data: "user already exists",
})
} else if err.Error() != "no such user" {
serverErr(w, err)
return
}
db := opts.DB
stmt, err := db.Prepare(`INSERT INTO users VALUES (?, ?, ?, "", "", 0, 0, ?)`)
id, err := uuid.NewRandom()
if err != nil {
serverErr(w, err)
return
}
_, err = stmt.Exec(id, args.Username, args.Hash, time.Now())
if err != nil {
serverErr(w, err)
}
writeResponse(w, BBJResponse{
Data: true, // TODO probably something else
// TODO prob usermap
})
}))
/*
http.HandleFunc("/check_auth", handler(opts, func(w http.ResponseWriter, req *http.Request) { http.HandleFunc("/check_auth", handler(opts, func(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" { if req.Method != "POST" {
badMethod(w) badMethod(w)
@ -432,5 +348,4 @@ func setupAPI(opts config.Options) {
writeResponse(w, BBJResponse{Data: t}) writeResponse(w, BBJResponse{Data: t})
})) }))
*/ */
}