feat: removed non svelte front page

This commit is contained in:
2024-03-09 10:52:08 +00:00
parent 0d37ba8d59
commit 274d7d22aa
32 changed files with 614 additions and 3695 deletions

View File

@@ -13,194 +13,28 @@ import (
"time"
dbtypes "git.andr3h3nriqu3s.com/andr3/fyp/logic/db_types"
. "git.andr3h3nriqu3s.com/andr3/fyp/logic/models/utils"
"github.com/charmbracelet/log"
"github.com/goccy/go-json"
)
func Mul(n1 int, n2 int) int {
return n1 * n2
}
func Add(n1 int, n2 int) int {
return n1 + n2
}
func baseLoadTemplate(base string, path string) (*template.Template, any) {
funcs := map[string]any{
"startsWith": strings.HasPrefix,
"replace": strings.Replace,
"mul": Mul,
"add": Add,
}
return template.New(base).Funcs(funcs).ParseFiles(
"./views/"+base,
"./views/"+path,
"./views/partials/header.html",
)
}
func loadTemplate(path string) (*template.Template, any) {
return baseLoadTemplate("layout.html", path)
}
func LoadView(writer http.ResponseWriter, path string, data interface{}) {
tmpl, err := loadTemplate(path)
if err != nil {
fmt.Printf("Failed to load view %s\n", path)
fmt.Println(err)
if path == "500.html" {
writer.Write([]byte("<h1>Failed to load 500.html check console for more info</h1>"))
} else {
LoadView(writer, "500.html", nil)
}
return
}
if err := tmpl.Execute(writer, data); err != nil {
fmt.Printf("Failed to load view %s\n", path)
fmt.Println(err)
writer.WriteHeader(http.StatusInternalServerError)
if path == "500.html" {
writer.Write([]byte("<h1>Failed to load 500.html check console for more info</h1>"))
} else {
LoadView(writer, "500.html", nil)
}
return
}
}
/** Only returns the html without template */
func LoadHtml(writer http.ResponseWriter, path string, data interface{}) {
tmpl, err := baseLoadTemplate("html.html", path)
if err != nil {
fmt.Printf("Failed to load template %s\n", path)
fmt.Println(err)
writer.WriteHeader(http.StatusInternalServerError)
if path == "500.html" {
writer.Write([]byte("<h1>Failed to load 500.html check console for more info</h1>"))
} else {
LoadHtml(writer, "500.html", nil)
}
return
}
if err := tmpl.Execute(writer, data); err != nil {
fmt.Printf("Failed to execute template %s\n", path)
fmt.Println(err)
writer.WriteHeader(http.StatusInternalServerError)
if path == "500.html" {
writer.Write([]byte("<h1>Failed to load 500.html check console for more info</h1>"))
} else {
LoadHtml(writer, "500.html", nil)
}
return
}
}
func LoadDefineTemplate(writer http.ResponseWriter, path string, base string, data AnyMap) {
if data == nil {
data = map[string]interface{}{
"Error": true,
}
} else {
data["Error"] = true
}
funcs := map[string]any{
"startsWith": strings.HasPrefix,
"mul": Mul,
"replace": strings.Replace,
"add": Add,
}
tmpl, err := template.New("").Funcs(funcs).Parse("{{template \"" + base + "\" . }}")
if err != nil {
panic("Lol")
}
tmpl, err = tmpl.ParseFiles(
"./views/"+path,
"./views/partials/header.html",
)
if err != nil {
fmt.Printf("Failed to load template %s\n", path)
fmt.Println(err)
writer.WriteHeader(http.StatusInternalServerError)
if path == "500.html" {
writer.Write([]byte("<h1>Failed to load 500.html check console for more info</h1>"))
} else {
LoadHtml(writer, "500.html", nil)
}
return
}
if err := tmpl.Execute(writer, data); err != nil {
fmt.Printf("Failed to execute template %s\n", path)
fmt.Println(err)
writer.WriteHeader(http.StatusInternalServerError)
if path == "500.html" {
writer.Write([]byte("<h1>Failed to load 500.html check console for more info</h1>"))
} else {
LoadHtml(writer, "500.html", nil)
}
return
}
}
type AnyMap = map[string]interface{}
type Error struct {
Code int
Msg *string
data AnyMap
}
type AnswerType int
const (
NORMAL AnswerType = 1 << iota
HTML
JSON
HTMLFULL
)
func LoadBasedOnAnswer(ans AnswerType, w http.ResponseWriter, path string, data map[string]interface{}) {
if ans == NORMAL {
LoadView(w, path, data)
return
} else if ans == HTML {
LoadHtml(w, path, data)
return
} else if ans == HTMLFULL {
if data == nil {
LoadHtml(w, path, map[string]interface{}{
"App": true,
})
} else {
data["App"] = true
LoadHtml(w, path, data)
}
return
} else if ans == JSON {
panic("TODO JSON!")
} else {
panic("unreachable")
}
data any
}
type HandleFunc struct {
path string
mode AnswerType
fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error
fn func(c *Context) *Error
}
type Handler interface {
New()
Startup()
Get(fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error)
Post(fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error)
Get(fn func(c *Context) *Error)
Post(fn func(c *Context) *Error)
}
type Handle struct {
@@ -219,202 +53,162 @@ func decodeBody(r *http.Request) (string, *Error) {
return string(body[:]), nil
}
func handleError(err *Error, w http.ResponseWriter, context *Context) {
func handleError(err *Error, c *Context) {
if err != nil {
data := context.AddMap(err.data)
if err.Code == http.StatusNotFound {
if context.Mode == HTML {
w.WriteHeader(309)
context.Mode = HTMLFULL
}
LoadBasedOnAnswer(context.Mode, w, "404.html", data)
return
c.Logger.Warn("Responded with error", "code", err.Code, "data", err.data)
c.Writer.WriteHeader(err.Code)
var e *Error
if err.data != nil {
e = c.SendJSON(err.data)
} else {
e = c.SendJSON(500)
}
w.WriteHeader(err.Code)
if err.Code == http.StatusBadRequest {
LoadBasedOnAnswer(context.Mode, w, "400.html", data)
return
}
if err.Msg != nil {
w.Write([]byte(*err.Msg))
if e != nil {
c.Logger.Error("Something went very wront while trying to send and error message")
c.Writer.Write([]byte("505"))
}
}
}
func (x *Handle) Get(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
x.gets = append(x.gets, HandleFunc{path, NORMAL | HTML | HTMLFULL | JSON, fn})
func (x *Handle) Get(path string, fn func(c *Context) *Error) {
x.gets = append(x.gets, HandleFunc{path, fn})
}
func (x *Handle) GetHTML(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
x.gets = append(x.gets, HandleFunc{path, NORMAL | HTML | HTMLFULL, fn})
func (x *Handle) Post(path string, fn func(c *Context) *Error) {
x.posts = append(x.posts, HandleFunc{path, fn})
}
func (x *Handle) GetJSON(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
x.gets = append(x.gets, HandleFunc{path, JSON, fn})
func (x *Handle) Delete(path string, fn func(c *Context) *Error) {
x.deletes = append(x.deletes, HandleFunc{path, fn})
}
func (x *Handle) Post(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
x.posts = append(x.posts, HandleFunc{path, NORMAL | HTML | HTMLFULL | JSON, fn})
}
func (x *Handle) PostHTML(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
x.posts = append(x.posts, HandleFunc{path, NORMAL | HTML | HTMLFULL, fn})
}
func (x *Handle) PostJSON(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
x.posts = append(x.posts, HandleFunc{path, JSON, fn})
}
func (x *Handle) Delete(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
x.deletes = append(x.deletes, HandleFunc{path, NORMAL | HTML | HTMLFULL | JSON, fn})
}
func (x *Handle) DeleteHTML(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
x.deletes = append(x.deletes, HandleFunc{path, NORMAL | HTML | HTMLFULL, fn})
}
func (x *Handle) DeleteJSON(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
x.deletes = append(x.deletes, HandleFunc{path, JSON, fn})
}
func (x *Handle) handleGets(w http.ResponseWriter, r *http.Request, context *Context) {
func (x *Handle) handleGets(context *Context) {
for _, s := range x.gets {
if s.path == r.URL.Path && context.Mode&s.mode != 0 {
handleError(s.fn(w, r, context), w, context)
if s.path == context.R.URL.Path {
handleError(s.fn(context), context)
return
}
}
if context.Mode != HTMLFULL {
w.WriteHeader(http.StatusNotFound)
}
LoadBasedOnAnswer(context.Mode, w, "404.html", context.AddMap(nil))
handleError(&Error{404, "Endpoint not found"}, context)
}
func (x *Handle) handlePosts(w http.ResponseWriter, r *http.Request, context *Context) {
func (x *Handle) handlePosts(context *Context) {
for _, s := range x.posts {
if s.path == r.URL.Path && context.Mode&s.mode != 0 {
handleError(s.fn(w, r, context), w, context)
if s.path == context.R.URL.Path {
handleError(s.fn(context), context)
return
}
}
if context.Mode != HTMLFULL {
w.WriteHeader(http.StatusNotFound)
}
LoadBasedOnAnswer(context.Mode, w, "404.html", context.AddMap(nil))
handleError(&Error{404, "Endpoint not found"}, context)
}
func (x *Handle) handleDeletes(w http.ResponseWriter, r *http.Request, context *Context) {
func (x *Handle) handleDeletes(context *Context) {
for _, s := range x.deletes {
if s.path == r.URL.Path && context.Mode&s.mode != 0 {
handleError(s.fn(w, r, context), w, context)
if s.path == context.R.URL.Path {
handleError(s.fn(context), context)
return
}
}
if context.Mode != HTMLFULL {
w.WriteHeader(http.StatusNotFound)
}
LoadBasedOnAnswer(context.Mode, w, "404.html", context.AddMap(nil))
handleError(&Error{404, "Endpoint not found"}, context)
}
func CheckAuthLevel(authLevel int, w http.ResponseWriter, r *http.Request, c *Context) bool {
func (c *Context) CheckAuthLevel(authLevel int) bool {
if authLevel > 0 {
if c.requireAuth(w, r) {
Logoff(c.Mode, w, r)
if c.requireAuth() {
c.Logoff()
return false
}
if c.User.UserType < authLevel {
notAuth(c.Mode, w, r)
c.NotAuth()
return false
}
}
return true
}
func AnswerTemplate(path string, data AnyMap, authLevel int) func(w http.ResponseWriter, r *http.Request, c *Context) *Error {
return func(w http.ResponseWriter, r *http.Request, c *Context) *Error {
if !CheckAuthLevel(authLevel, w, r, c) {
return nil
}
LoadBasedOnAnswer(c.Mode, w, path, c.AddMap(data))
return nil
}
}
type Context struct {
Token *string
User *dbtypes.User
Mode AnswerType
Logger *log.Logger
Db *sql.DB
Writer http.ResponseWriter
Writer http.ResponseWriter
R *http.Request
}
func (c Context) ToJSON(r *http.Request, dat any) *Error {
decoder := json.NewDecoder(r.Body)
func (c Context) ToJSON(dat any) *Error {
err := decoder.Decode(dat)
if err != nil {
return c.Error500(err)
}
decoder := json.NewDecoder(c.R.Body)
return nil
err := decoder.Decode(dat)
if err != nil {
return c.Error500(err)
}
return nil
}
func (c Context) SendJSON(dat any) *Error {
c.Writer.Header().Add("content-type", "application/json")
text, err := json.Marshal(dat)
if err != nil {
return c.Error500(err)
}
if _, err = c.Writer.Write(text); err != nil {
return c.Error500(err)
}
return nil
c.Writer.Header().Add("content-type", "application/json")
text, err := json.Marshal(dat)
if err != nil {
return c.Error500(err)
}
if _, err = c.Writer.Write(text); err != nil {
return c.Error500(err)
}
return nil
}
func (c Context) SendJSONStatus(status int, dat any) *Error {
c.Writer.Header().Add("content-type", "application/json")
c.Writer.WriteHeader(status)
text, err := json.Marshal(dat)
if err != nil {
return c.Error500(err)
}
if _, err = c.Writer.Write(text); err != nil {
return c.Error500(err)
}
return nil
c.Writer.Header().Add("content-type", "application/json")
c.Writer.WriteHeader(status)
text, err := json.Marshal(dat)
if err != nil {
return c.Error500(err)
}
if _, err = c.Writer.Write(text); err != nil {
return c.Error500(err)
}
return nil
}
func (c Context) JsonBadRequest(dat any) *Error {
c.SetReportCaller(true)
c.Logger.Warn("Request failed with a bad request", "dat", dat)
c.SetReportCaller(false)
return c.SendJSONStatus(http.StatusBadRequest, dat)
c.SetReportCaller(true)
c.Logger.Warn("Request failed with a bad request", "dat", dat)
c.SetReportCaller(false)
return c.SendJSONStatus(http.StatusBadRequest, dat)
}
func (c Context) JsonErrorBadRequest(err error, dat any) *Error {
c.SetReportCaller(true)
c.Logger.Error("Error while processing request", "err", err, "dat", dat)
c.SetReportCaller(false)
return c.SendJSONStatus(http.StatusBadRequest, dat)
c.SetReportCaller(true)
c.Logger.Error("Error while processing request", "err", err, "dat", dat)
c.SetReportCaller(false)
return c.SendJSONStatus(http.StatusBadRequest, dat)
}
func (c Context) Error400(err error, message string, w http.ResponseWriter, path string, base string, data AnyMap) *Error {
c.SetReportCaller(true)
c.Logger.Error(message)
c.SetReportCaller(false)
func (c *Context) GetModelFromId(id_path string) (*BaseModel, *Error) {
id, err := GetIdFromUrl(c, id_path)
if err != nil {
c.Logger.Errorf("Something went wrong returning with: %d\n.Err:\n", http.StatusBadRequest)
c.Logger.Error(err)
return nil, c.SendJSONStatus(http.StatusNotFound, "Model not found")
}
if c.Mode == JSON {
return &Error{http.StatusBadRequest, nil, c.AddMap(data)}
model, err := GetBaseModel(c.Db, id)
if err == ModelNotFoundError {
return nil, c.SendJSONStatus(http.StatusNotFound, "Model not found")
} else if err != nil {
return nil, c.Error500(err)
}
LoadDefineTemplate(w, path, base, c.AddMap(data))
return nil
return model, nil
}
func ModelUpdateStatus(c *Context, id string, status int) {
_, err := c.Db.Exec("update models set status=$1 where id=$2;", status, id)
if err != nil {
c.Logger.Error("Failed to update model status", "err", err)
c.Logger.Warn("TODO Maybe handle better")
}
}
func (c Context) SetReportCaller(report bool) {
@@ -427,7 +221,7 @@ func (c Context) SetReportCaller(report bool) {
}
}
func (c Context) ErrorCode(err error, code int, data AnyMap) *Error {
func (c Context) ErrorCode(err error, code int, data any) *Error {
if code == 400 {
c.SetReportCaller(true)
c.Logger.Warn("When returning BadRequest(400) please use context.Error400\n")
@@ -437,32 +231,14 @@ func (c Context) ErrorCode(err error, code int, data AnyMap) *Error {
c.Logger.Errorf("Something went wrong returning with: %d\n.Err:\n", code)
c.Logger.Error(err)
}
return &Error{code, nil, c.AddMap(data)}
}
func (c Context) UnsafeErrorCode(err error, code int, data AnyMap) *Error {
if err != nil {
c.Logger.Errorf("Something went wrong returning with: %d\n.Err:\n", code)
c.Logger.Error(err)
}
return &Error{code, nil, c.AddMap(data)}
return &Error{code, data}
}
func (c Context) Error500(err error) *Error {
return c.ErrorCode(err, http.StatusInternalServerError, nil)
}
func (c Context) AddMap(m AnyMap) AnyMap {
if m == nil {
return map[string]interface{}{
"Context": c,
}
}
m["Context"] = c
return m
}
func (c *Context) requireAuth(w http.ResponseWriter, r *http.Request) bool {
func (c *Context) requireAuth() bool {
if c.User == nil {
return true
}
@@ -471,7 +247,7 @@ func (c *Context) requireAuth(w http.ResponseWriter, r *http.Request) bool {
var LogoffError = errors.New("Invalid token!")
func (x Handle) createContext(handler *Handle, mode AnswerType, r *http.Request, w http.ResponseWriter) (*Context, error) {
func (x Handle) createContext(handler *Handle, r *http.Request, w http.ResponseWriter) (*Context, error) {
var token *string
@@ -482,27 +258,18 @@ func (x Handle) createContext(handler *Handle, mode AnswerType, r *http.Request,
Prefix: r.URL.Path,
})
if mode != JSON {
for _, r := range r.Cookies() {
if r.Name == "auth" {
token = &r.Value
}
}
} else {
t := r.Header.Get("token")
if t != "" {
token = &t
}
}
t := r.Header.Get("token")
if t != "" {
token = &t
}
// TODO check that the token is still valid
if token == nil {
return &Context{
Mode: mode,
Logger: logger,
Db: handler.Db,
Writer: w,
Writer: w,
R: r,
}, nil
}
@@ -511,52 +278,22 @@ func (x Handle) createContext(handler *Handle, mode AnswerType, r *http.Request,
return nil, errors.Join(err, LogoffError)
}
return &Context{token, user, mode, logger, handler.Db, w}, nil
return &Context{token, user, logger, handler.Db, w, r}, nil
}
// TODO check if I can use http.Redirect
func Redirect(path string, mode AnswerType, w http.ResponseWriter, r *http.Request) {
w.Header().Set("Location", path)
if mode == JSON {
w.WriteHeader(http.StatusSeeOther)
w.Write([]byte(path))
return
}
if mode&(HTMLFULL|HTML) != 0 {
w.Header().Add("HX-Redirect", path)
w.WriteHeader(204)
} else {
w.WriteHeader(http.StatusSeeOther)
}
func contextlessLogoff(w http.ResponseWriter) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("\"Not Authorized\""))
}
func Logoff(mode AnswerType, w http.ResponseWriter, r *http.Request) {
if (mode == JSON) {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("\"Not Authorized\""))
} else {
// Delete cookie
cookie := &http.Cookie{
Name: "auth",
Value: "",
Expires: time.Unix(0, 0),
}
http.SetCookie(w, cookie)
Redirect("/login", mode, w, r)
}
}
func (c *Context) Logoff() { contextlessLogoff(c.Writer) }
func notAuth(mode AnswerType, w http.ResponseWriter, r *http.Request) {
if mode == JSON {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("\"You can not access this resource!\""))
return
}
if mode&(HTMLFULL|HTML) != 0 {
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("You can not access this resource!"))
} else {
w.WriteHeader(http.StatusForbidden)
func (c *Context) NotAuth() {
c.Writer.WriteHeader(http.StatusUnauthorized)
e := c.SendJSON("Not Authorized")
if e != nil {
c.Writer.WriteHeader(http.StatusInternalServerError)
c.Writer.Write([]byte("You can not access this resource!"))
}
}
@@ -583,21 +320,6 @@ func (x Handle) StaticFiles(pathTest string, fileType string, contentType string
})
}
func ErrorCode(err error, code int, data AnyMap) *Error {
log.Warn("This function is deprecated please use the one provided by context")
// TODO Improve Logging
if err != nil {
fmt.Printf("Something went wrong returning with: %d\n.Err:\n", code)
fmt.Println(err)
}
return &Error{code, nil, data}
}
func Error500(err error) *Error {
log.Warn("This function is deprecated please use the one provided by context")
return ErrorCode(err, http.StatusInternalServerError, nil)
}
func (x Handle) ReadFiles(pathTest string, baseFilePath string, fileType string, contentType string) {
http.HandleFunc(pathTest, func(w http.ResponseWriter, r *http.Request) {
user_path := r.URL.Path[len(pathTest):]
@@ -661,9 +383,9 @@ func (x Handle) ReadTypesFiles(pathTest string, baseFilePath string, fileTypes [
}
func (x Handle) ReadTypesFilesApi(pathTest string, baseFilePath string, fileTypes []string, contentTypes []string) {
http.HandleFunc("/api" + pathTest, func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = strings.Replace(r.URL.Path, "/api", "", 1)
http.HandleFunc("/api"+pathTest, func(w http.ResponseWriter, r *http.Request) {
r.URL.Path = strings.Replace(r.URL.Path, "/api", "", 1)
user_path := r.URL.Path[len(pathTest):]
found := false
@@ -704,52 +426,50 @@ func NewHandler(db *sql.DB) *Handle {
x := &Handle{db, gets, posts, deletes}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Headers", "*")
w.Header().Add("Access-Control-Allow-Methods", "*")
// Decide answertype
ans := NORMAL
if r.Header.Get("HX-Request") == "true" || r.Header.Get("Request-Type") == "html" {
ans = HTML
}
if r.Header.Get("Request-Type") == "htmlfull" {
ans = HTMLFULL
}
if r.Header.Get("content-type") == "application/json" || r.Header.Get("response-type") == "application/json" {
ans = JSON
}
if !strings.HasPrefix(r.URL.Path, "/api") {
return
}
r.URL.Path = strings.Replace(r.URL.Path, "/api", "", 1)
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Headers", "*")
w.Header().Add("Access-Control-Allow-Methods", "*")
//Login state
context, err := x.createContext(x, ans, r, w)
if err != nil {
Logoff(ans, w, r)
if !(r.Header.Get("content-type") == "application/json" || r.Header.Get("response-type") == "application/json") {
w.WriteHeader(500)
w.Write([]byte("Please set content-type to application/json or set response-type to application/json\n"))
return
}
// context.Logger.Info("Parsing", "path", r.URL.Path)
if !strings.HasPrefix(r.URL.Path, "/api") {
w.WriteHeader(404)
w.Write([]byte("Path not found"))
return
}
r.URL.Path = strings.Replace(r.URL.Path, "/api", "", 1)
//Login state
context, err := x.createContext(x, r, w)
if err != nil {
contextlessLogoff(w)
return
}
// context.Logger.Info("Parsing", "path", r.URL.Path)
if r.Method == "GET" {
x.handleGets(w, r, context)
x.handleGets(context)
return
}
if r.Method == "POST" {
x.handlePosts(w, r, context)
x.handlePosts(context)
return
}
if r.Method == "DELETE" {
x.handleDeletes(w, r, context)
x.handleDeletes(context)
return
}
if r.Method == "OPTIONS" {
return
}
if r.Method == "OPTIONS" {
return
}
panic("TODO handle method: " + r.Method)
})

View File

@@ -58,12 +58,12 @@ func IsValidUUID(u string) bool {
return err == nil
}
func GetIdFromUrl(r *http.Request, target string) (string, error) {
if !r.URL.Query().Has(target) {
func GetIdFromUrl(c *Context, target string) (string, error) {
if !c.R.URL.Query().Has(target) {
return "", errors.New("Query does not have " + target)
}
id := r.URL.Query().Get("id")
id := c.R.URL.Query().Get("id")
if len(id) == 0 {
return "", errors.New("Query is empty for " + target)
}