Compare commits

..

No commits in common. "3ed669f5606e81adbf4713b108aa1fb8a428075b" and "75c3e67f4199866728af346ec4e2da12c9f3da0e" have entirely different histories.

5 changed files with 20 additions and 196 deletions

2
.gitignore vendored
View File

@ -1,5 +1,3 @@
*.sqlite3
*.swp *.swp
# #
# ---> Go # ---> Go

2
go.mod
View File

@ -5,5 +5,3 @@ 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/mattn/go-sqlite3 v1.14.12
require github.com/google/uuid v1.3.0 // indirect

2
go.sum
View File

@ -1,5 +1,3 @@
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/mattn/go-sqlite3 v1.14.12 h1:TJ1bhYJPV44phC+IMu1u2K/i5RriLTPe+yc68XDJ1Z0= github.com/mattn/go-sqlite3 v1.14.12 h1:TJ1bhYJPV44phC+IMu1u2K/i5RriLTPe+yc68XDJ1Z0=
github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=

View File

@ -4,16 +4,12 @@ import (
"database/sql" "database/sql"
_ "embed" _ "embed"
"encoding/json" "encoding/json"
"errors"
"flag" "flag"
"fmt" "fmt"
"io" "io"
"net/http" "net/http"
"os" "os"
"strings"
"time"
"github.com/google/uuid"
_ "github.com/mattn/go-sqlite3" _ "github.com/mattn/go-sqlite3"
) )
@ -42,12 +38,10 @@ type Opts struct {
Logf func(string, ...interface{}) Logf func(string, ...interface{})
Config Config Config Config
DB *sql.DB DB *sql.DB
Reset bool
} }
func main() { 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.")
flag.Parse() flag.Parse()
io := iostreams{ io := iostreams{
Err: os.Stderr, Err: os.Stderr,
@ -55,7 +49,6 @@ func main() {
} }
opts := &Opts{ opts := &Opts{
ConfigPath: *configFlag, ConfigPath: *configFlag,
Reset: *resetFlag,
IO: io, IO: io,
// TODO use real logger // TODO use real logger
Log: func(s string) { Log: func(s string) {
@ -99,7 +92,7 @@ func _main(opts *Opts) error {
} }
defer teardown() defer teardown()
err = ensureSchema(*opts) err = ensureSchema(*opts, "1.0.0")
if err != nil { if err != nil {
return err return err
} }
@ -115,34 +108,10 @@ func _main(opts *Opts) error {
return nil return nil
} }
func ensureSchema(opts Opts) error { func ensureSchema(opts Opts, version string) error {
db := opts.DB // TODO make idempotent
// TODO actually respect version
if opts.Reset { _, err := opts.DB.Exec(schemaSQL)
err := os.Remove(opts.Config.DBPath)
if err != nil {
return fmt.Errorf("failed to delete database: %w", err)
}
}
rows, err := db.Query("select version from meta")
if err == nil {
defer rows.Close()
rows.Next()
var version string
err = rows.Scan(&version)
if err != nil {
return fmt.Errorf("failed to check database schema version: %w", err)
} else if version == "" {
return errors.New("database is in unknown state")
}
return nil
}
if !strings.Contains(err.Error(), "no such table") {
return fmt.Errorf("got error checking database state: %w", err)
}
_, err = db.Exec(schemaSQL)
if err != nil { if err != nil {
return fmt.Errorf("failed to initialize database schema: %w", err) return fmt.Errorf("failed to initialize database schema: %w", err)
} }
@ -174,171 +143,47 @@ type BBJResponse struct {
} }
func writeResponse(w http.ResponseWriter, resp BBJResponse) { func writeResponse(w http.ResponseWriter, resp BBJResponse) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp) json.NewEncoder(w).Encode(resp)
} }
func writeErrorResponse(w http.ResponseWriter, code int, resp BBJResponse) {
w.WriteHeader(code)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
// NB breaking: i'm not just returning 200 always but using http status codes
func setupAPI(opts Opts) { func setupAPI(opts Opts) {
http.HandleFunc("/instance", handler(opts, func(w http.ResponseWriter, req *http.Request) { http.HandleFunc("/instance", handler(opts, func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
writeResponse(w, BBJResponse{ writeResponse(w, BBJResponse{
Data: opts.Config.InstanceName, Data: opts.Config.InstanceName,
}) })
})) }))
serverErr := func(w http.ResponseWriter, err error) {
opts.Logf(err.Error())
writeErrorResponse(w, 500, BBJResponse{
Error: true,
Data: "server error",
})
}
badMethod := func(w http.ResponseWriter) {
writeErrorResponse(w, 400, BBJResponse{
Error: true,
Data: "bad method",
})
}
invalidArgs := func(w http.ResponseWriter) {
writeErrorResponse(w, 400, BBJResponse{
Error: true,
Data: "invalid args",
})
}
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"`
AuthHash string `json:"auth_hash"`
}
var args AuthArgs
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
}
if args.AuthHash == "" || args.Username == "" {
invalidArgs(w)
return
}
db := opts.DB
stmt, err := db.Prepare("select auth_hash from users where user_name = ?")
if err != nil {
serverErr(w, err)
return
}
defer stmt.Close()
opts.Logf("querying for %s", args.Username)
var authHash string
err = stmt.QueryRow(args.Username).Scan(&authHash)
if err == nil {
opts.Logf("found %s", args.Username)
// code 4 apparently
writeErrorResponse(w, 403, BBJResponse{
Error: true,
Data: "user already exists",
})
return
} else if err != nil && !strings.Contains(err.Error(), "no rows in result") {
serverErr(w, err)
return
}
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.AuthHash, 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) http.Error(w, "bad method", 400)
return return
} }
type AuthArgs struct { type args struct {
Username string `json:"target_user"` TargetUser string `json:"target_user"`
AuthHash string `json:"target_hash"` TargetHash string `json:"target_hash"`
} }
var args AuthArgs var a args
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
}
opts.Logf("got %s %s", args.Username, args.AuthHash) err := json.NewDecoder(req.Body).Decode(&a)
db := opts.DB
stmt, err := db.Prepare("select auth_hash from users where user_name = ?")
if err != nil { if err != nil {
serverErr(w, err) http.Error(w, "could not parse arguments", 400)
return
}
defer stmt.Close()
var authHash string
err = stmt.QueryRow(args.Username).Scan(&authHash)
if err != nil {
if strings.Contains(err.Error(), "no rows in result") {
opts.Logf("user not found")
writeErrorResponse(w, 404, BBJResponse{
Error: true,
Data: "user not found",
})
} else {
serverErr(w, err)
}
return
} }
// TODO unique constraint on user_name opts.Logf("got %s %s", a.TargetUser, a.TargetHash)
if authHash != args.AuthHash { // TODO
http.Error(w, "incorrect password", 403) result := false
writeErrorResponse(w, 403, BBJResponse{
Error: true,
Data: "incorrect password",
})
return
}
// TODO include usermap? w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
writeResponse(w, BBJResponse{ writeResponse(w, BBJResponse{
Data: true, Data: result,
}) })
})) }))
} }

View File

@ -2,8 +2,6 @@ create table meta (
version text -- schema version version text -- schema version
); );
insert into meta values ("1.0.0");
create table users ( create table users (
user_id text, -- string (uuid1) user_id text, -- string (uuid1)
user_name text, -- string user_name text, -- string
@ -15,19 +13,6 @@ create table users (
created real -- floating point unix timestamp (when this user registered) created real -- floating point unix timestamp (when this user registered)
); );
insert into users values (
"123", -- TODO replace UUID with incrementing int
"anon",
"8e97c0b197816a652fb489b21e63f664863daa991e2f8fd56e2df71593c2793f",
"",
"",
0,
0,
1650819851
);
-- TODO unique constraint on user_name?
create table threads ( create table threads (
thread_id text, -- uuid string thread_id text, -- uuid string