From bc3b437ebc7662174bc96a7af2c8f9118aee48c0 Mon Sep 17 00:00:00 2001 From: Evan Reichard Date: Mon, 11 Jan 2021 23:48:32 -0500 Subject: [PATCH] WIP --- cmd/cmd.go | 126 +++++++++++++++---------------- imagini.db | Bin 69632 -> 69632 bytes internal/auth/auth.go | 15 ++-- internal/auth/ldap.go | 4 +- internal/auth/local.go | 17 +++-- internal/config/config.go | 2 + internal/context/context.go | 21 ++++++ internal/models/api.go | 22 ++++++ internal/models/db.go | 45 +++++++++++ internal/models/models.go | 45 ----------- internal/{db => query}/db.go | 10 +-- internal/{db => query}/errors.go | 2 +- internal/{db => query}/users.go | 7 +- main.go | 2 +- routes/albums.go | 2 +- routes/auth.go | 61 ++++++++++++++- routes/info.go | 2 +- routes/media_items.go | 2 +- routes/routes.go | 104 +++++++++++++++---------- routes/tags.go | 2 +- routes/upload.go | 2 +- routes/users.go | 32 +++++++- 22 files changed, 339 insertions(+), 186 deletions(-) create mode 100644 internal/context/context.go create mode 100644 internal/models/api.go create mode 100644 internal/models/db.go delete mode 100644 internal/models/models.go rename internal/{db => query}/db.go (95%) rename internal/{db => query}/errors.go (86%) rename internal/{db => query}/users.go (70%) diff --git a/cmd/cmd.go b/cmd/cmd.go index c2a4761..ced6e2b 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -1,13 +1,8 @@ package cmd import ( - "fmt" - "errors" "reichard.io/imagini/routes" - "reichard.io/imagini/internal/db" - "reichard.io/imagini/internal/auth" - "reichard.io/imagini/internal/models" - "reichard.io/imagini/internal/config" + "reichard.io/imagini/internal/context" "github.com/urfave/cli/v2" "net/http" @@ -21,67 +16,72 @@ var CmdServe = cli.Command{ Action: serveWeb, } -var CmdDBTest = cli.Command{ - Name: "test", - Aliases: []string{"t"}, - Usage: "test db.", - Action: testDatabase, -} +// var CmdDBTest = cli.Command{ +// Name: "test", +// Aliases: []string{"t"}, +// Usage: "test db.", +// Action: testDatabase, +// } -func serveWeb(ctx *cli.Context) error { +func serveWeb(cliCtx *cli.Context) error { log.Info("Serving Web") - routes.RegisterRoutes() - if err := http.ListenAndServe(":8080", nil); err != nil { + + ctx := context.NewImaginiContext() + routes.RegisterRoutes(ctx) + //listener, _ := net.Listen("tcp", ctx.Config.ListenPort) + + if err := http.ListenAndServe(":" + ctx.Config.ListenPort, nil); err != nil { log.Fatal(err) } - return nil -} - -func testDatabase(ctx *cli.Context) error { - log.Info("Testing Database") - c := config.NewConfig() - db.ConnectDB(c) - - err := auth.CreateUser(models.User{ - Username: "User12346", - Email: "user26@evan.pub", - FirstName: "User", - LastName: "Reichard", - AuthType: "Local", - }, "myPassword123") - - if err != nil { - fmt.Println(err) - } - - resp := auth.AuthenticateUser("User123", "myPassword123") - if resp == true { - log.Info("USER SUCCESSFULLY AUTHENTICATED BY USERNAME") - }else { - log.Info("USER NOT AUTHENTICATED") - } - - resp = auth.AuthenticateUser("user@evan.pub", "myPassword123") - if resp == true { - log.Info("USER SUCCESSFULLY AUTHENTICATED BY EMAIL") - }else { - log.Info("USER NOT AUTHENTICATED") - } - - resp = auth.AuthenticateUser("user@evan.pub", "myPassword12") - if resp == true { - log.Info("USER SUCCESSFULLY AUTHENTICATED BY EMAIL") - }else { - log.Info("USER NOT AUTHENTICATED") - } - - // foundUser, err := db.GetUser(db.User{Username: "User123"}) - - // if errors.Is(err, gorm.ErrRecordNotFound) { - // log.Warn("RECORD NOT FOUND") - // } else { - // log.Info("FOUND USER", foundUser) - // } return nil } + +// func testDatabase(cliCtx *cli.Context) error { +// log.Info("Testing Database") +// c := config.NewConfig() +// db.ConnectDB(c) +// +// err := auth.CreateUser(models.User{ +// Username: "User123", +// Email: "user26@evan.pub", +// FirstName: "User", +// LastName: "Reichard", +// AuthType: "Local", +// }, "myPassword123") +// +// if err != nil { +// fmt.Println(err) +// } +// +// resp := auth.AuthenticateUser(models.APICredentials{User:"User123", Password: "myPassword123"}) +// if resp == true { +// log.Info("USER SUCCESSFULLY AUTHENTICATED BY USERNAME") +// }else { +// log.Info("USER NOT AUTHENTICATED") +// } +// +// resp = auth.AuthenticateUser(models.APICredentials{User:"user26@evan.pub", Password: "myPassword123"}) +// if resp == true { +// log.Info("USER SUCCESSFULLY AUTHENTICATED BY EMAIL") +// }else { +// log.Info("USER NOT AUTHENTICATED") +// } +// +// resp = auth.AuthenticateUser(models.APICredentials{User:"user@evan.pub", Password: "myPassword12"}) +// if resp == true { +// log.Info("USER SUCCESSFULLY AUTHENTICATED BY EMAIL") +// }else { +// log.Info("USER NOT AUTHENTICATED") +// } +// +// // foundUser, err := db.GetUser(db.User{Username: "User123"}) +// +// // if errors.Is(err, gorm.ErrRecordNotFound) { +// // log.Warn("RECORD NOT FOUND") +// // } else { +// // log.Info("FOUND USER", foundUser) +// // } +// +// return nil +// } diff --git a/imagini.db b/imagini.db index 8efa76a66ca7ac230a68d25924b1087b50b18026..5e3b750da73635f3f93388fe134edab6f7d34b7e 100644 GIT binary patch delta 298 zcmZozz|ydQWr8##??f4AM&6AHn>Z$CaC%I>$0jzJo6}+Q2F?&QHb#Cw27bTIf&wo5 zp^f^CJPf|R4BFD7vf_=bMg~TPx(0^2hK34;7FMR_R>r1!29^fKW|q1Jrd9?9gyc($ zQ;UquCNH+vu(!y}i40Fp&v41hDoaW6PV_GD^Ud@Rt27P{iU<$z4)McSM zGInw|b@dO*PuJsOU|?Y6f6KuC7U;ak{IWvK+MEzG9a75@^YjWzlORgIGVp%|DtXN> u%Ec_r849%4(8w4f^@oA~4^ZkoKReJcW@ZM?O#&Z$yb6QT0;*^~%#Obkl180aD7c=iG2L1rPdAzSS z3kuxft#34B=3(&lWzd!vl@)JfH8LU z@}0sbz_IdIhCPp+K&ok+F#xh!K>UnVgYWl;V@0oS36xl&E58pi&=cn30?8 zot;=}k*HUiZt89s=#`mWT3nnKWmZ&{lNp+6=w^~`t$F)%PN^PgbgKf!;8|2;4z?BaJ5X4Yl|2LvMen1z@% zA!6{rVG>|g=L9K(i$Kh}#lZiS{{{aopjl`5O?a8*89~7Zj(cVvW?49oiHlj96DkGK s`H6x55C3=mPe7ed`1x3v85o&C1QRne1Lr0I7KOzu0&u*UMc|J-0QFABeE, password: } - // [POST] /Logout - // [GET] /MediaItems +func RegisterRoutes(cctx *context.ImaginiContext) { + ctx := &ImaginiContext{cctx} + http.HandleFunc("/MediaItems", ctx.mediaItemsHandler) + http.HandleFunc("/Upload", ctx.uploadHandler) + http.HandleFunc("/Albums", ctx.albumsHandler) + http.HandleFunc("/Logout", ctx.logoutHandler) + http.HandleFunc("/Login", ctx.loginHandler) + http.HandleFunc("/Users", ctx.usersHandler) + http.HandleFunc("/Tags", ctx.tagsHandler) + http.HandleFunc("/Info", ctx.infoHandler) + http.HandleFunc("/Me", ctx.meHandler) +} - // commonMiddleware := []Middleware{ - // logMiddleware, - // authMiddleware, - // } - // http.Handle("/Users", MultipleMiddleware(usersHandler, commonMiddleware...)) - // http.Handle("/Uploads/", MultipleMiddleware(uploadsHandler, commonMiddleware...)) +// https://stackoverflow.com/a/59764037 +func JSONError(w http.ResponseWriter, err string, code int) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.WriteHeader(code) + json.NewEncoder(w).Encode(map[string]interface{}{"error": err}) +} - // // http.HandleFunc("/uploads/", uploadsHandler()) - // http.Handle("/Uploads/", func(next http.Handler) http.Handler { - // return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // _, ok := ValidateUserToken(r) +func JSONSuccess(w http.ResponseWriter, msg string, code int) { + w.Header().Set("Content-Type", "application/json; charset=utf-8") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.WriteHeader(code) + json.NewEncoder(w).Encode(map[string]interface{}{"success": msg}) +} - // if ok { - // next.ServeHTTP(w, r) - // } else { - // w.WriteHeader(http.StatusUnauthorized) - // } - // }) - // }(http.StripPrefix("/Uploads/", tusHandler))) +// METHOD: +// switch r.Method { +// case http.MethodGet: +// // Serve the resource. +// case http.MethodPost: +// // Create a new record. +// case http.MethodPut: +// // Update an existing record. +// case http.MethodDelete: +// // Remove the record. +// default: +// // Give an error message. +// } + + +// commonMiddleware := []Middleware{ +// logMiddleware, +// authMiddleware, +// } +// http.Handle("/Users", MultipleMiddleware(usersHandler, commonMiddleware...)) +// http.Handle("/Uploads/", MultipleMiddleware(uploadsHandler, commonMiddleware...)) + +// // http.HandleFunc("/uploads/", uploadsHandler()) +// http.Handle("/Uploads/", func(next http.Handler) http.Handler { +// return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { +// _, ok := ValidateUserToken(r) + +// if ok { +// next.ServeHTTP(w, r) +// } else { +// w.WriteHeader(http.StatusUnauthorized) +// } +// }) +// }(http.StripPrefix("/Uploads/", tusHandler))) // Filter Example: // query := r.URL.Query() // filters, present := query["filters"] -// HTTP Errors -// if r.Method != "GET" { -// http.Error(w, "Method is not supported.", http.StatusNotFound) -// return -// } -// if r.URL.Path != "/hello" { -// http.Error(w, "404 not found.", http.StatusNotFound) -// return -// } - // func uploadsHandler() http.Handler { // store := filestore.FileStore{ // Path: "./Uploads", diff --git a/routes/tags.go b/routes/tags.go index 4e81579..93dd07a 100644 --- a/routes/tags.go +++ b/routes/tags.go @@ -4,6 +4,6 @@ import ( "net/http" ) -func tagsHandler(w http.ResponseWriter, r *http.Request) { +func (ctx *ImaginiContext) tagsHandler(w http.ResponseWriter, r *http.Request) { } diff --git a/routes/upload.go b/routes/upload.go index 85fd2a6..91abd32 100644 --- a/routes/upload.go +++ b/routes/upload.go @@ -4,6 +4,6 @@ import ( "net/http" ) -func uploadHandler(w http.ResponseWriter, r *http.Request) { +func (ctx *ImaginiContext) uploadHandler(w http.ResponseWriter, r *http.Request) { } diff --git a/routes/users.go b/routes/users.go index 96de876..a9213b6 100644 --- a/routes/users.go +++ b/routes/users.go @@ -2,12 +2,38 @@ package routes import ( "net/http" + log "github.com/sirupsen/logrus" ) -func usersHandler(w http.ResponseWriter, r *http.Request) { - +func (ctx *ImaginiContext) usersHandler(w http.ResponseWriter, r *http.Request) { + if r.Method == http.MethodPost { + // CREATE + } else if r.Method == http.MethodPut { + // UPDATE / REPLACE + } else if r.Method == http.MethodPatch { + // UPDATE / MODIFY + } else if r.Method == http.MethodDelete { + // DELETE + } else if r.Method == http.MethodGet { + // GET + } else { + JSONError(w, "Method is not supported.", http.StatusMethodNotAllowed) + return + } } -func meHandler(w http.ResponseWriter, r *http.Request) { +func (ctx *ImaginiContext) meHandler(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodGet { + JSONError(w, "Method is not supported.", http.StatusMethodNotAllowed) + return + } + // Get Authenticated User & Return Object + authCookie, err := r.Cookie("Token") + if err != nil { + log.Error("[routes] ", err) + return + } + + log.Info("[routes] INFO: ", authCookie) }