chore: did some clean up

This commit is contained in:
2024-04-13 23:55:01 +01:00
parent 4862e9a79e
commit fbf7eb9271
5 changed files with 148 additions and 345 deletions

View File

@@ -4,8 +4,6 @@ import (
"database/sql"
"errors"
"fmt"
"html/template"
"io"
"net/http"
"os"
"path"
@@ -47,15 +45,6 @@ type Handle struct {
validate *validator.Validate
}
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, c *Context) {
if err != nil {
c.Logger.Warn("Responded with error", "code", err.Code, "data", err.data)
@@ -73,10 +62,20 @@ func handleError(err *Error, c *Context) {
}
}
// This group of functions defines some endpoints
func (x *Handle) Get(path string, fn func(c *Context) *Error) {
x.gets = append(x.gets, HandleFunc{path, fn})
}
func (x *Handle) GetAuth(path string, authLevel int, fn func(c *Context) *Error) {
inner_fn := func(c *Context) *Error {
if !c.CheckAuthLevel(authLevel) {
return nil
}
return fn(c)
}
x.gets = append(x.gets, HandleFunc{path, inner_fn})
}
func (x *Handle) Post(path string, fn func(c *Context) *Error) {
x.posts = append(x.posts, HandleFunc{path, fn})
}
@@ -91,9 +90,9 @@ func (x *Handle) PostAuth(path string, authLevel int, fn func(c *Context) *Error
x.posts = append(x.posts, HandleFunc{path, inner_fn})
}
func PostAuthJson[T interface{}](x *Handle, path string, authLevel int, fn func(c *Context, obj *T) *Error) {
func PostAuthJson[T interface{}](x *Handle, path string, authLevel dbtypes.UserType, fn func(c *Context, obj *T) *Error) {
inner_fn := func(c *Context) *Error {
if !c.CheckAuthLevel(authLevel) {
if !c.CheckAuthLevel(int(authLevel)) {
return nil
}
@@ -141,7 +140,8 @@ func DeleteAuthJson[T interface{}](x *Handle, path string, authLevel int, fn fun
x.deletes = append(x.deletes, HandleFunc{path, inner_fn})
}
func (x *Handle) handleGets(context *Context) {
// This function handles loop of a list of possible handler functions
func handleLoop(array []HandleFunc, context *Context) {
defer func() {
if r := recover(); r != nil {
context.Logger.Error("Something went very wrong", "Error", r)
@@ -149,60 +149,30 @@ func (x *Handle) handleGets(context *Context) {
}
}()
for _, s := range x.gets {
for _, s := range array {
if s.path == context.R.URL.Path {
handleError(s.fn(context), context)
return
}
}
context.ShowMessage = false
handleError(&Error{404, "Endpoint not found"}, context)
}
func (x *Handle) handlePosts(context *Context) {
defer func() {
if r := recover(); r != nil {
context.Logger.Error("Something went very wrong", "Error", r)
handleError(&Error{500, "500"}, context)
}
}()
for _, s := range x.posts {
if s.path == context.R.URL.Path {
handleError(s.fn(context), context)
return
}
}
context.ShowMessage = false
handleError(&Error{404, "Endpoint not found"}, context)
}
func (x *Handle) handleDeletes(context *Context) {
defer func() {
if r := recover(); r != nil {
context.Logger.Error("Something went very wrong", "Error", r)
handleError(&Error{500, "500"}, context)
}
}()
for _, s := range x.deletes {
if s.path == context.R.URL.Path {
handleError(s.fn(context), context)
return
}
}
context.ShowMessage = false
handleError(&Error{404, "Endpoint not found"}, context)
}
func (c *Context) CheckAuthLevel(authLevel int) bool {
if authLevel > 0 {
if c.requireAuth() {
c.Logoff()
if c.User == nil {
contextlessLogoff(c.Writer)
return false
}
if c.User.UserType < authLevel {
c.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!"))
}
return false
}
}
@@ -221,6 +191,7 @@ type Context struct {
Handle *Handle
}
// This is required for this to integrate simealy with my orl
func (c Context) GetDb() *sql.DB {
return c.Db
}
@@ -237,7 +208,6 @@ func (c Context) Prepare(str string) (*sql.Stmt, error) {
if c.Tx == nil {
return c.Db.Prepare(str)
}
return c.Tx.Prepare(str)
}
@@ -395,6 +365,7 @@ func (c Context) ErrorCode(err error, code int, data any) *Error {
return &Error{code, data}
}
// Deprecated: Use the E500M instead
func (c Context) Error500(err error) *Error {
return c.ErrorCode(err, http.StatusInternalServerError, nil)
}
@@ -403,13 +374,6 @@ func (c Context) E500M(msg string, err error) *Error {
return c.ErrorCode(err, http.StatusInternalServerError, msg)
}
func (c *Context) requireAuth() bool {
if c.User == nil {
return true
}
return false
}
var LogoffError = errors.New("Invalid token!")
func (x Handle) createContext(handler *Handle, r *http.Request, w http.ResponseWriter) (*Context, error) {
@@ -453,102 +417,6 @@ func contextlessLogoff(w http.ResponseWriter) {
w.Write([]byte("\"Not Authorized\""))
}
func (c *Context) Logoff() { contextlessLogoff(c.Writer) }
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!"))
}
}
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 (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)
})
}
// TODO remove this
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
index := -1
for i, fileType := range fileTypes {
if strings.HasSuffix(user_path, fileType) {
found = true
index = i
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 (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)
@@ -586,7 +454,6 @@ func (x Handle) ReadTypesFilesApi(pathTest string, baseFilePath string, fileType
}
func NewHandler(db *sql.DB, config Config) *Handle {
var gets []HandleFunc
var posts []HandleFunc
var deletes []HandleFunc
@@ -624,11 +491,11 @@ func NewHandler(db *sql.DB, config Config) *Handle {
// context.Logger.Info("Parsing", "path", r.URL.Path)
if r.Method == "GET" {
x.handleGets(context)
handleLoop(x.gets, context)
} else if r.Method == "POST" {
x.handlePosts(context)
handleLoop(x.posts, context)
} else if r.Method == "DELETE" {
x.handleDeletes(context)
handleLoop(x.deletes, context)
} else if r.Method == "OPTIONS" {
// do nothing
} else {