Compare commits

...

6 Commits

Author SHA1 Message Date
vilmibm 3ed669f560 user registration 2022-04-28 14:08:05 -05:00
vilmibm 9703d88c66 WIP user reg 2022-04-28 13:40:48 -05:00
vilmibm 44343a429e some golfing, start on registration 2022-04-24 12:33:19 -05:00
vilmibm c2b26da9fc finish check_auth 2022-04-24 12:09:56 -05:00
vilmibm 12feb93428 WIP making check_auth real 2022-04-22 15:23:12 -05:00
vilmibm a7b7670d5f db initialization 2022-04-22 14:49:36 -05:00
5 changed files with 197 additions and 21 deletions

2
.gitignore vendored
View File

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

2
go.mod
View File

@ -5,3 +5,5 @@ go 1.18
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 // indirect

2
go.sum
View File

@ -1,3 +1,5 @@
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/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=

View File

@ -4,12 +4,16 @@ import (
"database/sql"
_ "embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/google/uuid"
_ "github.com/mattn/go-sqlite3"
)
@ -38,10 +42,12 @@ type Opts struct {
Logf func(string, ...interface{})
Config Config
DB *sql.DB
Reset bool
}
func main() {
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()
io := iostreams{
Err: os.Stderr,
@ -49,6 +55,7 @@ func main() {
}
opts := &Opts{
ConfigPath: *configFlag,
Reset: *resetFlag,
IO: io,
// TODO use real logger
Log: func(s string) {
@ -92,7 +99,7 @@ func _main(opts *Opts) error {
}
defer teardown()
err = ensureSchema(*opts, "1.0.0")
err = ensureSchema(*opts)
if err != nil {
return err
}
@ -108,10 +115,34 @@ func _main(opts *Opts) error {
return nil
}
func ensureSchema(opts Opts, version string) error {
// TODO make idempotent
// TODO actually respect version
_, err := opts.DB.Exec(schemaSQL)
func ensureSchema(opts Opts) error {
db := opts.DB
if opts.Reset {
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 {
return fmt.Errorf("failed to initialize database schema: %w", err)
}
@ -143,47 +174,171 @@ type BBJResponse struct {
}
func writeResponse(w http.ResponseWriter, resp BBJResponse) {
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
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) {
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{
Data: opts.Config.InstanceName,
})
}))
http.HandleFunc("/check_auth", handler(opts, func(w http.ResponseWriter, req *http.Request) {
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" {
http.Error(w, "bad method", 400)
badMethod(w)
return
}
type args struct {
TargetUser string `json:"target_user"`
TargetHash string `json:"target_hash"`
type AuthArgs struct {
Username string `json:"user_name"`
AuthHash string `json:"auth_hash"`
}
var a args
var args AuthArgs
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
}
err := json.NewDecoder(req.Body).Decode(&a)
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 {
http.Error(w, "could not parse arguments", 400)
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
}
opts.Logf("got %s %s", a.TargetUser, a.TargetHash)
stmt, err = db.Prepare(`INSERT INTO users VALUES (?, ?, ?, "", "", 0, 0, ?)`)
id, err := uuid.NewRandom()
if err != nil {
serverErr(w, err)
return
}
// TODO
result := false
_, err = stmt.Exec(id, args.Username, args.AuthHash, time.Now())
if err != nil {
serverErr(w, err)
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
writeResponse(w, BBJResponse{
Data: result,
Data: true, // TODO probably something else
// TODO prob usermap
})
}))
http.HandleFunc("/check_auth", handler(opts, func(w http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
badMethod(w)
return
}
type AuthArgs struct {
Username string `json:"target_user"`
AuthHash string `json:"target_hash"`
}
var args AuthArgs
if err := json.NewDecoder(req.Body).Decode(&args); err != nil {
invalidArgs(w)
return
}
opts.Logf("got %s %s", args.Username, args.AuthHash)
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()
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
if authHash != args.AuthHash {
http.Error(w, "incorrect password", 403)
writeErrorResponse(w, 403, BBJResponse{
Error: true,
Data: "incorrect password",
})
return
}
// TODO include usermap?
writeResponse(w, BBJResponse{
Data: true,
})
}))
}

View File

@ -2,6 +2,8 @@ create table meta (
version text -- schema version
);
insert into meta values ("1.0.0");
create table users (
user_id text, -- string (uuid1)
user_name text, -- string
@ -13,6 +15,19 @@ create table users (
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 (
thread_id text, -- uuid string