Files
huso/ober.go
2022-04-14 21:27:18 +02:00

128 lines
2.9 KiB
Go

package main
import (
"crypto/sha512"
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"github.com/fasthttp/router"
"github.com/valyala/fasthttp"
)
func RunWebserv() {
r := router.New()
r.GET("/", Start)
r.GET("/api/season", Season)
r.POST("/api/register", Register)
log.Fatal(fasthttp.ListenAndServe(":"+strconv.Itoa(*webServerPort), r.Handler))
}
func Start(ctx *fasthttp.RequestCtx) {
data, err := cache.Get(seasonApiJikan)
if err != nil {
addErrorToCtx(ctx, err)
return
}
var seasonData SeasonJikan
err = json.Unmarshal(data, &seasonData)
if err != nil {
addErrorToCtx(ctx, err)
return
}
WriteIndex(ctx, &seasonData)
ctx.SetContentType("text/html; charset=utf-8")
ctx.SetStatusCode(fasthttp.StatusOK)
}
func Season(ctx *fasthttp.RequestCtx) {
data, err := cache.Get(seasonApiJikan)
if err != nil {
addErrorToCtx(ctx, err)
return
}
var seasonData SeasonJikan
err = json.Unmarshal(data, &seasonData)
if err != nil {
addErrorToCtx(ctx, err)
return
}
_, err = ctx.Write(data)
if err != nil {
addErrorToCtx(ctx, err)
return
}
ctx.SetContentType("application/json; charset=utf-8")
ctx.SetStatusCode(fasthttp.StatusOK)
}
func Register(ctx *fasthttp.RequestCtx) {
if string(ctx.Request.Header.ContentType()) != "application/json" {
ctx.SetStatusCode(fasthttp.StatusBadRequest)
return
}
body := ctx.PostBody()
var register RegisterData
err := json.Unmarshal(body, &register)
if err != nil {
ctx.WriteString(err.Error())
ctx.SetStatusCode(fasthttp.StatusBadRequest)
return
}
if register.MalId == 0 || register.Username == "" || register.Secret == "" || register.Sauce == "" {
ctx.WriteString("Sprich JSON du Hurensohn")
ctx.SetStatusCode(fasthttp.StatusBadRequest)
return
}
calcSauce := fmt.Sprintf("%x", sha512.Sum512([]byte(registerSecret+strconv.Itoa(register.MalId)+register.Username)))
if calcSauce != strings.ToLower(register.Sauce) {
ctx.WriteString("Möge die Sauce mit dir sein")
ctx.SetStatusCode(fasthttp.StatusBadRequest)
return
}
// check user exists
_, err = ReadUser(register.Username)
if err == nil {
ctx.WriteString("Nicht drängeln")
ctx.SetStatusCode(fasthttp.StatusConflict)
return
}
// check user legit
userData, _, err := GetUserData(register.Username)
if err != nil {
ctx.WriteString(err.Error())
ctx.SetStatusCode(fasthttp.StatusExpectationFailed)
return
}
if userData.Data.MalID != register.MalId {
ctx.WriteString("Dich gibts net auf MAL")
ctx.SetStatusCode(fasthttp.StatusExpectationFailed)
return
}
// REGISTER
user := UserData{
Username: register.Username,
MalId: register.MalId,
Secret: register.Secret,
}
err = SaveUser(&user)
if err != nil {
addErrorToCtx(ctx, err)
return
}
ctx.SetBody(body)
ctx.SetStatusCode(fasthttp.StatusOK)
}
func addErrorToCtx(ctx *fasthttp.RequestCtx, err error) {
ctx.WriteString(err.Error())
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
}