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,313 +118,234 @@ 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) /*
http.HandleFunc("/check_auth", handler(opts, func(w http.ResponseWriter, req *http.Request) {
var authHash string if req.Method != "POST" {
if err = stmt.QueryRow(username).Scan(&authHash); err != nil { badMethod(w)
if strings.Contains(err.Error(), "no rows in result") { return
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) { type AuthArgs struct {
if req.Method != "POST" { Username string `json:"target_user"`
badMethod(w) AuthHash string `json:"target_hash"`
return }
}
type AuthArgs struct { var args AuthArgs
Username string `json:"user_name"` if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
Hash string `json:"auth_hash"` invalidArgs(w)
} return
}
var args AuthArgs opts.Logf("got %s %s", args.Username, args.AuthHash)
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
}
if args.Hash == "" || args.Username == "" { db := opts.DB
invalidArgs(w)
return
}
opts.Logf("querying for %s", args.Username) stmt, err := db.Prepare("select auth_hash from users where user_name = ?")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
if err := checkAuth(opts, args.Username, args.Hash); err == nil { var authHash string
opts.Logf("found %s", args.Username) err = stmt.QueryRow(args.Username).Scan(&authHash)
// code 4 apparently if err != nil {
writeErrorResponse(w, 403, BBJResponse{ if strings.Contains(err.Error(), "no rows in result") {
Error: true, opts.Logf("user not found")
Data: "user already exists", writeErrorResponse(w, 404, BBJResponse{
}) Error: true,
} else if err.Error() != "no such user" { Data: "user not found",
serverErr(w, err) })
return } else {
} serverErr(w, err)
}
return
}
db := opts.DB // TODO unique constraint on user_name
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 authHash != args.AuthHash {
if err != nil { http.Error(w, "incorrect password", 403)
serverErr(w, err) writeErrorResponse(w, 403, BBJResponse{
} Error: true,
Data: "incorrect password",
})
return
}
writeResponse(w, BBJResponse{ // TODO include usermap?
Data: true, // TODO probably something else writeResponse(w, BBJResponse{
// TODO prob usermap Data: true,
}) })
})) }))
http.HandleFunc("/check_auth", handler(opts, func(w http.ResponseWriter, req *http.Request) { http.HandleFunc("/thread_index", handler(opts, func(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" { db := opts.DB
badMethod(w) rows, err := db.Query("SELECT * FROM threads JOIN messages ON threads.thread_id = messages.thread_id")
return if err != nil {
} serverErr(w, err)
return
}
defer rows.Close()
for rows.Next() {
var id string
err = rows.Scan(&id)
if err != nil {
serverErr(w, err)
return
}
opts.Log(id)
}
writeResponse(w, BBJResponse{Data: "TODO"})
// TODO
}))
type AuthArgs struct { http.HandleFunc("/thread_create", handler(opts, func(w http.ResponseWriter, req *http.Request) {
Username string `json:"target_user"` if req.Method != "POST" {
AuthHash string `json:"target_hash"` badMethod(w)
} return
}
var args AuthArgs // TODO make this getUserInfoFromReq or similar so we can use the user ID later
if err := json.NewDecoder(req.Body).Decode(&args); err != nil { user, err := getUserFromReq(opts, req)
invalidArgs(w) if err != nil {
return writeErrorResponse(w, 403, BBJResponse{
} Error: true,
Data: err.Error(),
})
return
}
opts.Logf("got %s %s", args.Username, args.AuthHash) type threadCreateArgs struct {
Title string
Body string
SendRaw bool `json:"send_raw"`
}
db := opts.DB var args threadCreateArgs
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
}
stmt, err := db.Prepare("select auth_hash from users where user_name = ?") if args.Title == "" || args.Body == "" {
if err != nil { invalidArgs(w)
serverErr(w, err) return
return }
}
defer stmt.Close()
var authHash string db := opts.DB
err = stmt.QueryRow(args.Username).Scan(&authHash) tx, err := db.Begin()
if err != nil { if err != nil {
if strings.Contains(err.Error(), "no rows in result") { serverErr(w, err)
opts.Logf("user not found") return
writeErrorResponse(w, 404, BBJResponse{ }
Error: true,
Data: "user not found",
})
} else {
serverErr(w, err)
}
return
}
// TODO unique constraint on user_name stmt, err := tx.Prepare("insert into threads VALUES ( ?, ?, ?, ?, ?, 0, 0, ? )")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
if authHash != args.AuthHash { threadID, err := uuid.NewRandom()
http.Error(w, "incorrect password", 403) if err != nil {
writeErrorResponse(w, 403, BBJResponse{ serverErr(w, err)
Error: true, return
Data: "incorrect password", }
}) now := time.Now()
return if _, err = stmt.Exec(
} threadID,
user.ID,
args.Title,
now,
now,
user.Username,
); err != nil {
serverErr(w, err)
return
}
// TODO include usermap? stmt, err = tx.Prepare("insert into messages values ( ?, 1, ?, ?, 0, ?, ? )")
writeResponse(w, BBJResponse{ if err != nil {
Data: true, serverErr(w, err)
}) return
})) }
defer stmt.Close()
http.HandleFunc("/thread_index", handler(opts, func(w http.ResponseWriter, req *http.Request) { if _, err = stmt.Exec(
db := opts.DB threadID,
rows, err := db.Query("SELECT * FROM threads JOIN messages ON threads.thread_id = messages.thread_id") user.ID,
if err != nil { now,
serverErr(w, err) args.Body,
return args.SendRaw,
} ); err != nil {
defer rows.Close() serverErr(w, err)
for rows.Next() { return
var id string }
err = rows.Scan(&id)
if err != nil {
serverErr(w, err)
return
}
opts.Log(id)
}
writeResponse(w, BBJResponse{Data: "TODO"})
// TODO
}))
http.HandleFunc("/thread_create", handler(opts, func(w http.ResponseWriter, req *http.Request) { if err = tx.Commit(); err != nil {
if req.Method != "POST" { serverErr(w, err)
badMethod(w) return
return }
}
// TODO make this getUserInfoFromReq or similar so we can use the user ID later stmt, err = db.Prepare("select * from threads where thread_id = ? limit 1")
user, err := getUserFromReq(opts, req) if err != nil {
if err != nil { serverErr(w, err)
writeErrorResponse(w, 403, BBJResponse{ return
Error: true, }
Data: err.Error(), defer stmt.Close()
})
return
}
type threadCreateArgs struct { t := &Thread{}
Title string
Body string
SendRaw bool `json:"send_raw"`
}
var args threadCreateArgs // TODO fill in rest of thread
if err := json.NewDecoder(req.Body).Decode(&args); err != nil { if err = stmt.QueryRow(threadID).Scan(
invalidArgs(w) t.ID,
return t.Author,
} t.Title,
t.LastMod,
t.Created,
t.ReplyCount,
t.Pinned,
t.LastAuthor,
); err != nil {
serverErr(w, err)
return
}
if args.Title == "" || args.Body == "" { stmt, err = db.Prepare("select * from messages where thread_id = ?")
invalidArgs(w) if err != nil {
return serverErr(w, err)
} return
}
defer stmt.Close()
rows, err := stmt.Query(threadID)
if err != nil {
serverErr(w, err)
return
}
db := opts.DB t.Messages = []Message{}
tx, err := db.Begin()
if err != nil {
serverErr(w, err)
return
}
stmt, err := tx.Prepare("insert into threads VALUES ( ?, ?, ?, ?, ?, 0, 0, ? )") for rows.Next() {
if err != nil { m := &Message{}
serverErr(w, err) if err := rows.Scan(
return m.ThreadID,
} m.PostID,
defer stmt.Close() m.Author,
m.Created,
m.Edited,
m.Body,
m.SendRaw,
); err != nil {
serverErr(w, err)
return
}
t.Messages = append(t.Messages, *m)
}
threadID, err := uuid.NewRandom() writeResponse(w, BBJResponse{Data: t})
if err != nil {
serverErr(w, err)
return
}
now := time.Now()
if _, err = stmt.Exec(
threadID,
user.ID,
args.Title,
now,
now,
user.Username,
); err != nil {
serverErr(w, err)
return
}
stmt, err = tx.Prepare("insert into messages values ( ?, 1, ?, ?, 0, ?, ? )") }))
if err != nil { */
serverErr(w, err)
return
}
defer stmt.Close()
if _, err = stmt.Exec(
threadID,
user.ID,
now,
args.Body,
args.SendRaw,
); err != nil {
serverErr(w, err)
return
}
if err = tx.Commit(); err != nil {
serverErr(w, err)
return
}
stmt, err = db.Prepare("select * from threads where thread_id = ? limit 1")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
t := &Thread{}
// TODO fill in rest of thread
if err = stmt.QueryRow(threadID).Scan(
t.ID,
t.Author,
t.Title,
t.LastMod,
t.Created,
t.ReplyCount,
t.Pinned,
t.LastAuthor,
); err != nil {
serverErr(w, err)
return
}
stmt, err = db.Prepare("select * from messages where thread_id = ?")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
rows, err := stmt.Query(threadID)
if err != nil {
serverErr(w, err)
return
}
t.Messages = []Message{}
for rows.Next() {
m := &Message{}
if err := rows.Scan(
m.ThreadID,
m.PostID,
m.Author,
m.Created,
m.Edited,
m.Body,
m.SendRaw,
); err != nil {
serverErr(w, err)
return
}
t.Messages = append(t.Messages, *m)
}
writeResponse(w, BBJResponse{Data: t})
}))
*/
}