feat: moved files into a better position for organization closes #8

This commit is contained in:
2023-09-21 16:43:11 +01:00
parent b8278bacf6
commit 1986be1a84
16 changed files with 582 additions and 500 deletions

517
logic/utils/handler.go Normal file
View File

@@ -0,0 +1,517 @@
package utils
import (
"database/sql"
"errors"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
"path"
"strings"
"time"
dbtypes "git.andr3h3nriqu3s.com/andr3/fyp/logic/db_types"
)
func baseLoadTemplate(base string, path string) (*template.Template, any) {
return template.New(base).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 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
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")
}
}
type HandleFunc struct {
path string
mode AnswerType
fn func(w http.ResponseWriter, r *http.Request, 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)
}
type Handle struct {
Db *sql.DB
gets []HandleFunc
posts []HandleFunc
deletes []HandleFunc
}
func decodeBody(r *http.Request) (string, *Error) {
body, err := io.ReadAll(r.Body)
if err == nil {
return "", &Error{Code: http.StatusBadRequest}
}
return string(body[:]), nil
}
func handleError(err *Error, w http.ResponseWriter, context *Context) {
if err != nil {
data := context.AddMap(err.data)
w.WriteHeader(err.Code)
if err.Code == http.StatusNotFound {
LoadBasedOnAnswer(context.Mode, w, "404.html", data)
return
}
if err.Code == http.StatusBadRequest {
LoadBasedOnAnswer(context.Mode, w, "400.html", data)
return
}
if err.Msg != nil {
w.Write([]byte(*err.Msg))
}
}
}
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) 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) 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) 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) {
for _, s := range x.gets {
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 (x *Handle) handlePosts(w http.ResponseWriter, r *http.Request, 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)
return
}
}
if context.Mode != HTMLFULL {
w.WriteHeader(http.StatusNotFound)
}
LoadBasedOnAnswer(context.Mode, w, "404.html", context.AddMap(nil))
}
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.UserType < 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 !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
}
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 {
if c.User == nil {
return true
}
return false
}
var LogoffError = errors.New("Invalid token!")
func (x Handle) createContext(mode AnswerType, r *http.Request) (*Context, error) {
var token *string
for _, r := range r.Cookies() {
if r.Name == "auth" {
token = &r.Value
}
}
// TODO check that the token is still valid
if token == nil {
return &Context{
Mode: mode,
}, nil
}
user, err := dbtypes.UserFromToken(x.Db, *token)
if err != nil {
return nil, errors.Join(err, LogoffError)
}
return &Context{token, user, mode}, 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.WriteHeader(http.StatusSeeOther)
w.Write([]byte(path))
} 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
var deletes []HandleFunc
x := &Handle{db, gets, posts, deletes}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Decide answertype
ans := NORMAL
if r.Header.Get("Request-Type") == "htmlfull" {
ans = HTMLFULL
}
if r.Header.Get("Request-Type") == "html" {
ans = HTML
}
//TODO JSON
//Login state
context, err := x.createContext(ans, r)
if err != nil {
Logoff(ans, w, r)
return
}
if r.Method == "GET" {
x.handleGets(w, r, context)
return
}
if r.Method == "POST" {
x.handlePosts(w, r, context)
return
}
if r.Method == "DELETE" {
x.handleDeletes(w, r, context)
return
}
panic("TODO handle method: " + r.Method)
})
return x
}
func (x Handle) Startup() {
fmt.Printf("Starting up!\n")
log.Fatal(http.ListenAndServe(":8000", nil))
}

150
logic/utils/utils.go Normal file
View File

@@ -0,0 +1,150 @@
package utils
import (
"errors"
"io"
"mime"
"net/http"
"net/url"
"github.com/google/uuid"
)
func CheckEmpty(f url.Values, path string) bool {
return !f.Has(path) || f.Get(path) == ""
}
func CheckId(f url.Values, path string) bool {
return !CheckEmpty(f, path) && IsValidUUID(f.Get(path))
}
func IsValidUUID(u string) bool {
_, err := uuid.Parse(u)
return err == nil
}
func GetIdFromUrl(r *http.Request, target string) (string, error) {
if !r.URL.Query().Has(target) {
return "", errors.New("Query does not have " + target)
}
id := r.URL.Query().Get("id")
if len(id) == 0 {
return "", errors.New("Query is empty for " + target)
}
if !IsValidUUID(id) {
return "", errors.New("Value of query is not a valid uuid for " + target)
}
return id, nil
}
type maxBytesReader struct {
w http.ResponseWriter
r io.ReadCloser // underlying reader
i int64 // max bytes initially, for MaxBytesError
n int64 // max bytes remaining
err error // sticky error
}
type MaxBytesError struct {
Limit int64
}
func (e *MaxBytesError) Error() string {
// Due to Hyrum's law, this text cannot be changed.
return "http: request body too large"
}
func (l *maxBytesReader) Read(p []byte) (n int, err error) {
if l.err != nil {
return 0, l.err
}
if len(p) == 0 {
return 0, nil
}
// If they asked for a 32KB byte read but only 5 bytes are
// remaining, no need to read 32KB. 6 bytes will answer the
// question of the whether we hit the limit or go past it.
// 0 < len(p) < 2^63
if int64(len(p))-1 > l.n {
p = p[:l.n+1]
}
n, err = l.r.Read(p)
if int64(n) <= l.n {
l.n -= int64(n)
l.err = err
return n, err
}
n = int(l.n)
l.n = 0
// The server code and client code both use
// maxBytesReader. This "requestTooLarge" check is
// only used by the server code. To prevent binaries
// which only using the HTTP Client code (such as
// cmd/go) from also linking in the HTTP server, don't
// use a static type assertion to the server
// "*response" type. Check this interface instead:
type requestTooLarger interface {
requestTooLarge()
}
if res, ok := l.w.(requestTooLarger); ok {
res.requestTooLarge()
}
l.err = &MaxBytesError{l.i}
return n, l.err
}
func (l *maxBytesReader) Close() error {
return l.r.Close()
}
func MyParseForm(r *http.Request) (vs url.Values, err error) {
if r.Body == nil {
err = errors.New("missing form body")
return
}
ct := r.Header.Get("Content-Type")
// RFC 7231, section 3.1.1.5 - empty type
// MAY be treated as application/octet-stream
if ct == "" {
ct = "application/octet-stream"
}
ct, _, err = mime.ParseMediaType(ct)
switch {
case ct == "application/x-www-form-urlencoded":
var reader io.Reader = r.Body
maxFormSize := int64(1<<63 - 1)
if _, ok := r.Body.(*maxBytesReader); !ok {
maxFormSize = int64(10 << 20) // 10 MB is a lot of text.
reader = io.LimitReader(r.Body, maxFormSize+1)
}
b, e := io.ReadAll(reader)
if e != nil {
if err == nil {
err = e
}
break
}
if int64(len(b)) > maxFormSize {
err = errors.New("http: POST too large")
return
}
vs, e = url.ParseQuery(string(b))
if err == nil {
err = e
}
case ct == "multipart/form-data":
// handled by ParseMultipartForm (which is calling us, or should be)
// TODO(bradfitz): there are too many possible
// orders to call too many functions here.
// Clean this up and write more tests.
// request_test.go contains the start of this,
// in TestParseMultipartFormOrder and others.
}
return
}