chore: added model delete related to #2

This commit is contained in:
2023-09-21 15:38:02 +01:00
parent af62db6ad1
commit b8278bacf6
21 changed files with 1264 additions and 185 deletions

View File

@@ -8,6 +8,8 @@ import (
"io"
"log"
"net/http"
"os"
"path"
"strings"
"time"
)
@@ -78,11 +80,56 @@ func LoadHtml(writer http.ResponseWriter, path string, data interface{}) {
}
}
func LoadError(writer http.ResponseWriter, path string, base string, data AnyMap) {
if data == nil {
data = map[string]interface{} {
"Error": true,
}
} else {
data["Error"] = true
}
tmpl, err := template.New("").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
@@ -133,9 +180,10 @@ type Handler interface {
}
type Handle struct {
db *sql.DB
gets []HandleFunc
posts []HandleFunc
db *sql.DB
gets []HandleFunc
posts []HandleFunc
deletes []HandleFunc
}
func decodeBody(r *http.Request) (string, *Error) {
@@ -149,9 +197,8 @@ func decodeBody(r *http.Request) (string, *Error) {
func handleError(err *Error, w http.ResponseWriter, context *Context) {
data := context.toMap()
if err != nil {
data := context.addMap(err.data)
w.WriteHeader(err.code)
if err.code == http.StatusNotFound {
LoadBasedOnAnswer(context.Mode, w, "404.html", data)
@@ -168,69 +215,39 @@ func handleError(err *Error, w http.ResponseWriter, context *Context) {
}
func (x *Handle) Get(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: NORMAL | HTML | HTMLFULL | JSON,
}
x.gets = append(x.gets, nhandler)
x.gets = append(x.gets, HandleFunc{path, NORMAL | HTML | HTMLFULL | JSON, fn})
}
func (x *Handle) GetHTML(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: NORMAL | HTML | HTMLFULL,
}
x.gets = append(x.gets, nhandler)
x.gets = append(x.gets, HandleFunc{path, NORMAL | HTML | HTMLFULL, fn})
}
func (x *Handle) GetJSON(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: JSON,
}
x.gets = append(x.gets, nhandler)
x.gets = append(x.gets, HandleFunc{path, JSON, fn})
}
func (x *Handle) Post(path string, fn func(w http.ResponseWriter, r *http.Request, c *Context) *Error) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: NORMAL | HTML | HTMLFULL | JSON,
}
x.posts = append(x.posts, nhandler)
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) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: NORMAL | HTML | HTMLFULL,
}
x.posts = append(x.posts, nhandler)
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) {
nhandler :=
HandleFunc{
fn: fn,
path: path,
mode: JSON,
}
x.posts = append(x.posts, HandleFunc{path, JSON, fn})
}
x.posts = append(x.posts, nhandler)
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) {
@@ -243,9 +260,7 @@ func (x *Handle) handleGets(w http.ResponseWriter, r *http.Request, context *Con
if context.Mode != HTMLFULL {
w.WriteHeader(http.StatusNotFound)
}
LoadBasedOnAnswer(context.Mode, w, "404.html", map[string]interface{}{
"context": context,
})
LoadBasedOnAnswer(context.Mode, w, "404.html", context.addMap(nil))
}
func (x *Handle) handlePosts(w http.ResponseWriter, r *http.Request, context *Context) {
@@ -258,18 +273,42 @@ func (x *Handle) handlePosts(w http.ResponseWriter, r *http.Request, context *Co
if context.Mode != HTMLFULL {
w.WriteHeader(http.StatusNotFound)
}
LoadBasedOnAnswer(context.Mode, w, "404.html", map[string]interface{}{
"context": context,
})
LoadBasedOnAnswer(context.Mode, w, "404.html", context.addMap(nil))
}
func AnswerTemplate(path string, data AnyMap) func(w http.ResponseWriter, r *http.Request, c *Context) *Error {
func (x *Handle) handleDeletes(w http.ResponseWriter, r *http.Request, 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)
return
}
}
if context.Mode != HTMLFULL {
w.WriteHeader(http.StatusNotFound)
}
LoadBasedOnAnswer(context.Mode, w, "404.html", context.addMap(nil))
}
func checkAuthLevel(authLevel int, w http.ResponseWriter, r *http.Request, c *Context) bool {
if authLevel > 0 {
if c.requireAuth(w, r) {
logoff(c.Mode, w, r)
return false
}
if c.User.user_type < authLevel {
notAuth(c.Mode, w, r)
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 data == nil {
LoadBasedOnAnswer(c.Mode, w, path, c.toMap())
} else {
LoadBasedOnAnswer(c.Mode, w, path, c.addMap(data))
}
if !checkAuthLevel(authLevel, w, r, c) {
return nil
}
LoadBasedOnAnswer(c.Mode, w, path, c.addMap(data))
return nil
}
}
@@ -277,25 +316,24 @@ func AnswerTemplate(path string, data AnyMap) func(w http.ResponseWriter, r *htt
type Context struct {
Token *string
User *User
Mode AnswerType
Mode AnswerType
}
func (c Context) addMap(m AnyMap) AnyMap {
m["Context"] = c;
return m;
}
func (c *Context) toMap() map[string]interface{} {
return map[string]interface{}{
"Context": c,
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 {
if c.User == nil {
return true;
}
return false;
if c.User == nil {
return true
}
return false
}
var LogoffError = errors.New("Invalid token!")
@@ -310,10 +348,12 @@ func (x Handle) createContext(mode AnswerType, r *http.Request) (*Context, error
}
}
// TODO check that the token is still valid
if token == nil {
return &Context{
Mode: mode,
}, nil
Mode: mode,
}, nil
}
user, err := userFromToken(x.db, *token)
@@ -324,35 +364,114 @@ func (x Handle) createContext(mode AnswerType, r *http.Request) (*Context, error
return &Context{token, user, mode}, nil
}
func logoff(mode AnswerType, w http.ResponseWriter, r *http.Request) {
// Delete cookie
cookie := &http.Cookie{
Name: "auth",
Value: "",
Expires: time.Unix(0, 0),
}
http.SetCookie(w, cookie)
// 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.WriteHeader(http.StatusSeeOther)
w.Write([]byte(path))
} else {
w.WriteHeader(http.StatusSeeOther)
}
}
// Setup response
w.Header().Set("Location", "/login")
if mode == JSON {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("\"Bye Bye\""));
return
}
if mode & (HTMLFULL | HTML) != 0 {
w.WriteHeader(http.StatusUnauthorized);
w.Write([]byte("Bye Bye"));
} else {
w.WriteHeader(http.StatusSeeOther);
}
func logoff(mode AnswerType, w http.ResponseWriter, r *http.Request) {
// Delete cookie
cookie := &http.Cookie{
Name: "auth",
Value: "",
Expires: time.Unix(0, 0),
}
http.SetCookie(w, cookie)
redirect("/login", mode, w, r)
}
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 (x Handle) staticFiles(pathTest string, fileType string, contentType string) {
http.HandleFunc(pathTest, func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path[len(pathTest):]
if !strings.HasSuffix(path, fileType) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("File not found"))
return
}
t, err := template.ParseFiles("./views" + pathTest + path)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Failed to load template"))
return
}
w.Header().Set("Content-Type", contentType+"; charset=utf-8")
t.Execute(w, nil)
})
}
func errorCode(err error, code int, data AnyMap) *Error {
// 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 {
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):]
fmt.Printf("Requested path: %s\n", user_path)
if !strings.HasSuffix(user_path, fileType) {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("File not found"))
return
}
bytes, err := os.ReadFile(path.Join(baseFilePath, pathTest, user_path))
if err != nil {
fmt.Println(err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Failed to load file"))
return
}
w.Header().Set("Content-Type", contentType)
w.Write(bytes)
})
}
func NewHandler(db *sql.DB) *Handle {
var gets []HandleFunc
var posts []HandleFunc
x := &Handle{ db, gets, posts, }
var gets []HandleFunc
var posts []HandleFunc
var deletes []HandleFunc
x := &Handle{db, gets, posts, deletes}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Decide answertype
@@ -380,53 +499,11 @@ func NewHandler(db *sql.DB) *Handle {
x.handlePosts(w, r, context)
return
}
panic("TODO handle: " + r.Method)
})
// TODO Handle this in other way
http.HandleFunc("/styles/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path[len("/styles/"):]
if !strings.HasSuffix(path, ".css") {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("File not found"))
if r.Method == "DELETE" {
x.handleDeletes(w, r, context)
return
}
t, err := template.ParseFiles("./views/styles/" + path)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Failed to load template"))
fmt.Println("Error:")
fmt.Println(err)
return
}
w.Header().Set("Content-Type", "text/css; charset=utf-8")
t.Execute(w, nil)
})
// TODO Handle this in other way
http.HandleFunc("/js/", func(w http.ResponseWriter, r *http.Request) {
path := r.URL.Path[len("/js/"):]
if !strings.HasSuffix(path, ".js") {
w.WriteHeader(http.StatusNotFound)
w.Write([]byte("File not found"))
return
}
t, err := template.ParseFiles("./views/js/" + path)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("Failed to load template"))
fmt.Println("Error:")
fmt.Println(err)
return
}
w.Header().Set("Content-Type", "text/javascript; charset=utf-8")
t.Execute(w, nil)
panic("TODO handle method: " + r.Method)
})
return x