fyp/logic/utils/handler.go

697 lines
17 KiB
Go
Raw Normal View History

package utils
2023-09-18 00:26:42 +01:00
import (
"database/sql"
"errors"
2023-09-18 00:26:42 +01:00
"fmt"
"html/template"
"io"
2023-09-18 00:26:42 +01:00
"net/http"
"os"
"path"
2023-09-18 00:26:42 +01:00
"strings"
"time"
dbtypes "git.andr3h3nriqu3s.com/andr3/fyp/logic/db_types"
2023-10-20 12:37:56 +01:00
"github.com/charmbracelet/log"
2024-02-23 23:49:23 +00:00
"github.com/goccy/go-json"
2023-09-18 00:26:42 +01:00
)
2023-10-20 12:37:56 +01:00
func Mul(n1 int, n2 int) int {
return n1 * n2
}
2023-10-20 12:37:56 +01:00
func Add(n1 int, n2 int) int {
return n1 + n2
}
2023-09-18 00:26:42 +01:00
func baseLoadTemplate(base string, path string) (*template.Template, any) {
2023-10-20 12:37:56 +01:00
funcs := map[string]any{
"startsWith": strings.HasPrefix,
"replace": strings.Replace,
"mul": Mul,
"add": Add,
}
return template.New(base).Funcs(funcs).ParseFiles(
2023-09-18 00:26:42 +01:00
"./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) {
2023-10-20 12:37:56 +01:00
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 + "\" . }}")
2023-10-20 12:37:56 +01:00
if err != nil {
panic("Lol")
}
2023-10-20 12:37:56 +01:00
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{}
2023-09-18 00:26:42 +01:00
type Error struct {
Code int
Msg *string
data AnyMap
2023-09-18 00:26:42 +01:00
}
type AnswerType int
const (
NORMAL AnswerType = 1 << iota
2023-09-18 00:26:42 +01:00
HTML
JSON
HTMLFULL
)
func LoadBasedOnAnswer(ans AnswerType, w http.ResponseWriter, path string, data map[string]interface{}) {
if ans == NORMAL {
LoadView(w, path, data)
2023-09-18 00:26:42 +01:00
return
} else if ans == HTML {
LoadHtml(w, path, data)
2023-09-18 00:26:42 +01:00
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
}
2023-09-18 00:26:42 +01:00
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)
2023-09-18 00:26:42 +01:00
}
type Handle struct {
Db *sql.DB
gets []HandleFunc
posts []HandleFunc
deletes []HandleFunc
}
2023-09-18 00:26:42 +01:00
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) {
2023-09-18 00:26:42 +01:00
if err != nil {
data := context.AddMap(err.data)
if err.Code == http.StatusNotFound {
2023-10-20 12:37:56 +01:00
if context.Mode == HTML {
w.WriteHeader(309)
context.Mode = HTMLFULL
}
LoadBasedOnAnswer(context.Mode, w, "404.html", data)
return
}
2023-10-06 10:46:45 +01:00
w.WriteHeader(err.Code)
if err.Code == http.StatusBadRequest {
LoadBasedOnAnswer(context.Mode, w, "400.html", data)
2023-09-18 00:26:42 +01:00
return
}
if err.Msg != nil {
w.Write([]byte(*err.Msg))
2023-09-18 00:26:42 +01:00
}
}
}
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})
2023-09-18 00:26:42 +01:00
}
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 {
2023-10-20 12:37:56 +01:00
Token *string
User *dbtypes.User
Mode AnswerType
Logger *log.Logger
Db *sql.DB
2023-10-06 09:45:47 +01:00
}
2024-02-23 23:49:23 +00:00
func (c Context) ToJSON(r *http.Request, dat any) *Error {
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(dat)
if err != nil {
return c.Error500(err)
}
return nil
}
func (c Context) SendJSON(w http.ResponseWriter, dat any) *Error {
w.Header().Add("content-type", "application/json")
text, err := json.Marshal(dat)
if err != nil {
return c.Error500(err)
}
if _, err = w.Write(text); err != nil {
return c.Error500(err)
}
return nil
}
func (c Context) SendJSONStatus(w http.ResponseWriter, status int, dat any) *Error {
w.Header().Add("content-type", "application/json")
w.WriteHeader(status)
text, err := json.Marshal(dat)
if err != nil {
return c.Error500(err)
}
if _, err = w.Write(text); err != nil {
return c.Error500(err)
}
return nil
}
2023-10-06 10:46:45 +01:00
func (c Context) Error400(err error, message string, w http.ResponseWriter, path string, base string, data AnyMap) *Error {
2023-10-20 12:37:56 +01:00
c.SetReportCaller(true)
c.Logger.Error(message)
c.SetReportCaller(false)
2023-10-06 10:46:45 +01:00
if err != nil {
c.Logger.Errorf("Something went wrong returning with: %d\n.Err:\n", http.StatusBadRequest)
c.Logger.Error(err)
}
2023-10-20 12:37:56 +01:00
if c.Mode == JSON {
return &Error{http.StatusBadRequest, nil, c.AddMap(data)}
}
2023-10-06 10:46:45 +01:00
2023-10-20 12:37:56 +01:00
LoadDefineTemplate(w, path, base, c.AddMap(data))
return nil
2023-10-06 10:46:45 +01:00
}
func (c Context) SetReportCaller(report bool) {
2023-10-20 12:37:56 +01:00
if report {
c.Logger.SetCallerOffset(2)
c.Logger.SetReportCaller(true)
} else {
c.Logger.SetCallerOffset(1)
c.Logger.SetReportCaller(false)
}
2023-10-06 10:46:45 +01:00
}
2023-10-06 09:45:47 +01:00
func (c Context) ErrorCode(err error, code int, data AnyMap) *Error {
2023-10-20 12:37:56 +01:00
if code == 400 {
c.SetReportCaller(true)
c.Logger.Warn("When returning BadRequest(400) please use context.Error400\n")
c.SetReportCaller(false)
}
2023-10-06 09:45:47 +01:00
if err != nil {
c.Logger.Errorf("Something went wrong returning with: %d\n.Err:\n", code)
c.Logger.Error(err)
}
2023-10-06 10:46:45 +01:00
return &Error{code, nil, c.AddMap(data)}
}
2023-10-12 12:08:12 +01:00
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)}
}
2023-10-06 10:46:45 +01:00
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 {
if c.User == nil {
return true
}
return false
}
var LogoffError = errors.New("Invalid token!")
func (x Handle) createContext(handler *Handle, mode AnswerType, r *http.Request) (*Context, error) {
var token *string
2023-10-20 12:37:56 +01:00
logger := log.NewWithOptions(os.Stdout, log.Options{
2024-02-08 18:20:58 +00:00
ReportCaller: true,
2023-10-20 12:37:56 +01:00
ReportTimestamp: true,
TimeFormat: time.Kitchen,
Prefix: r.URL.Path,
})
2023-10-12 12:08:12 +01:00
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{
2023-10-20 12:37:56 +01:00
Mode: mode,
Logger: logger,
Db: handler.Db,
}, nil
}
user, err := dbtypes.UserFromToken(x.Db, *token)
if err != nil {
return nil, errors.Join(err, LogoffError)
}
return &Context{token, user, mode, logger, handler.Db}, 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 {
2023-10-20 12:37:56 +01:00
w.Header().Add("HX-Redirect", path)
w.WriteHeader(204)
} 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 {
2023-10-20 12:37:56 +01:00
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 {
2023-10-20 12:37:56 +01:00
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):]
2023-09-27 21:20:39 +01:00
// 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)
})
}
2023-10-20 12:37:56 +01:00
func (x Handle) ReadTypesFiles(pathTest string, baseFilePath string, fileTypes []string, contentTypes []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)
found := false
2023-10-24 22:35:11 +01:00
index := -1
2023-10-20 12:37:56 +01:00
for i, fileType := range fileTypes {
if strings.HasSuffix(user_path, fileType) {
found = true
2023-10-24 22:35:11 +01:00
index = i
2023-10-20 12:37:56 +01:00
break
}
}
if !found {
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", contentTypes[index])
w.Write(bytes)
})
}
func NewHandler(db *sql.DB) *Handle {
var gets []HandleFunc
var posts []HandleFunc
var deletes []HandleFunc
x := &Handle{db, gets, posts, deletes}
2023-09-18 00:26:42 +01:00
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Decide answertype
ans := NORMAL
2023-10-06 10:46:45 +01:00
if r.Header.Get("HX-Request") == "true" || r.Header.Get("Request-Type") == "html" {
ans = HTML
}
if r.Header.Get("Request-Type") == "htmlfull" {
ans = HTMLFULL
}
2024-02-23 23:49:23 +00:00
if r.Header.Get("content-type") == "application/json" {
ans = JSON
}
//TODO JSON
//Login state
context, err := x.createContext(x, ans, r)
if err != nil {
Logoff(ans, w, r)
return
}
2024-02-23 23:49:23 +00:00
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Header().Add("Access-Control-Allow-Headers", "*")
if r.Method == "GET" {
x.handleGets(w, r, context)
2023-09-18 00:26:42 +01:00
return
}
if r.Method == "POST" {
x.handlePosts(w, r, context)
return
}
if r.Method == "DELETE" {
x.handleDeletes(w, r, context)
2023-09-18 00:26:42 +01:00
return
}
2024-02-23 23:49:23 +00:00
if r.Method == "OPTIONS" {
return
}
panic("TODO handle method: " + r.Method)
})
return x
2023-09-18 00:26:42 +01:00
}
func (x Handle) Startup() {
2024-02-02 16:16:26 +00:00
log.Info("Starting up!\n")
2023-10-24 22:35:11 +01:00
port := os.Getenv("PORT")
if port == "" {
port = "8000"
}
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
2023-09-18 00:26:42 +01:00
}