bbj2/server/cmd/api/api.go

220 lines
4.5 KiB
Go
Raw Normal View History

2022-06-01 03:27:55 +00:00
package api
import (
2022-06-14 17:44:03 +00:00
"encoding/json"
"errors"
2022-06-01 03:27:55 +00:00
"fmt"
2022-06-14 17:44:03 +00:00
"net/http"
"time"
2022-06-01 03:27:55 +00:00
"git.tilde.town/tildetown/bbj2/server/cmd/config"
"git.tilde.town/tildetown/bbj2/server/cmd/db"
)
type HTTPError struct {
Msg string
Code int
}
func (e *HTTPError) Error() string {
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)}
}
2022-06-01 03:27:55 +00:00
type BBJResponse struct {
Error bool `json:"error"`
Data interface{} `json:"data"`
Usermap map[string]db.User `json:"usermap"`
}
2022-06-17 21:01:25 +00:00
type APIHandler func(*ReqCtx) (*BBJResponse, error)
2022-06-14 17:44:03 +00:00
2022-06-01 03:27:55 +00:00
type API struct {
Opts config.Options
2022-06-17 21:01:25 +00:00
}
func NewAPI(opts config.Options) *API {
return &API{Opts: opts}
}
type ReqCtx struct {
User db.User
2022-06-14 17:44:03 +00:00
Req *http.Request
}
2022-06-17 21:01:25 +00:00
func (c *ReqCtx) IsGet() bool {
return c.Req.Method == "GET"
}
func (c *ReqCtx) IsPost() bool {
return c.Req.Method == "POST"
}
func (a *API) Invoke(w http.ResponseWriter, req *http.Request, apiFn APIHandler) {
a.Opts.Logger.Printf("<- %s", req.URL.Path)
user, err := getUserFromReq(a.Opts, req)
2022-06-14 17:44:03 +00:00
if err != nil {
2022-06-17 21:01:25 +00:00
a.Opts.Logger.Printf("failed to get user from req: %s", err.Error())
w.WriteHeader(500)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(BBJResponse{
Error: true,
Data: "server error check logs",
})
2022-06-14 17:44:03 +00:00
}
2022-06-17 21:01:25 +00:00
2022-06-17 21:12:05 +00:00
resp, err := apiFn(&ReqCtx{*user, req})
2022-06-14 17:44:03 +00:00
if err != nil {
he := &HTTPError{}
_ = errors.As(err, &he)
resp := BBJResponse{
Error: true,
Data: he.Msg,
}
w.WriteHeader(he.Code)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
return
}
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
func getUserFromReq(opts config.Options, req *http.Request) (u *db.User, err error) {
2022-06-21 18:35:34 +00:00
username := req.Header.Get("User")
hash := req.Header.Get("Auth")
if username == "" || username == "anon" {
2022-06-14 17:44:03 +00:00
return
}
2022-06-21 18:35:34 +00:00
opts.Logger.Printf("checking auth for %s", username)
2022-06-14 17:44:03 +00:00
2022-07-01 01:44:58 +00:00
u, err = checkAuth(opts, username, hash)
2022-06-14 17:44:03 +00:00
return
2022-06-01 03:27:55 +00:00
}
2022-06-14 16:33:27 +00:00
type instanceInfo struct {
InstanceName string `json:"instance_name"`
AllowAnon bool `json:"allow_anon"`
Admins []string
}
2022-06-17 21:01:25 +00:00
func (a *API) InstanceInfo(ctx *ReqCtx) (resp *BBJResponse, err error) {
if !ctx.IsGet() {
err = badMethod()
return
2022-06-14 17:44:03 +00:00
}
resp = &BBJResponse{
2022-06-01 03:27:55 +00:00
Data: instanceInfo{
InstanceName: a.Opts.Config.InstanceName,
AllowAnon: a.Opts.Config.AllowAnon,
Admins: a.Opts.Config.Admins,
},
}
return
2022-06-01 03:27:55 +00:00
}
2022-07-01 01:44:58 +00:00
func (a *API) CheckAuth(ctx *ReqCtx) (resp *BBJResponse, err error) {
if !ctx.IsPost() {
err = badMethod()
return
}
type AuthArgs struct {
Username string `json:"target_user"`
Hash string `json:"target_hash"`
}
var args AuthArgs
if err = json.NewDecoder(ctx.Req.Body).Decode(&args); err != nil {
err = invalidArgs(err.Error())
return
}
if args.Hash == "" || args.Username == "" {
2022-07-01 02:49:59 +00:00
err = invalidArgs("missing either username or auth hash")
2022-07-01 01:44:58 +00:00
return
}
_, err = checkAuth(a.Opts, args.Username, args.Hash)
if err != nil {
2022-07-01 02:49:59 +00:00
if err.Error() != "bad credentials" {
return
}
err = &HTTPError{Code: 403, Msg: err.Error()}
2022-07-01 01:44:58 +00:00
return
}
// TODO usermap
resp = &BBJResponse{
Data: true,
}
return
}
2022-06-17 21:01:25 +00:00
func (a *API) UserRegister(ctx *ReqCtx) (resp *BBJResponse, err error) {
if !ctx.IsPost() {
err = badMethod()
return
}
type AuthArgs struct {
Username string `json:"user_name"`
Hash string `json:"auth_hash"`
}
var args AuthArgs
2022-06-17 21:01:25 +00:00
if err = json.NewDecoder(ctx.Req.Body).Decode(&args); err != nil {
err = invalidArgs(err.Error())
return
}
if args.Hash == "" || args.Username == "" {
err = invalidArgs(err.Error())
return
2022-06-14 17:44:03 +00:00
}
2022-07-01 01:44:58 +00:00
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
}
2022-07-01 01:44:58 +00:00
// checkAuth returns an error if username is not associated with hash
func checkAuth(opts config.Options, username, hash string) (user *db.User, err error) {
opts.Logger.Printf("querying for %s", username)
if user, err = db.GetUserByName(opts.DB, username); err != nil {
return
}
if user.Hash != hash {
err = errors.New("bad credentials")
}
return
2022-06-14 17:44:03 +00:00
}