package http import ( "io/fs" "net/http" "strings" "time" "git.javil.eu/jacob1123/budgeteer" "git.javil.eu/jacob1123/budgeteer/bcrypt" "git.javil.eu/jacob1123/budgeteer/postgres" "git.javil.eu/jacob1123/budgeteer/web" "github.com/gin-gonic/gin" ) // Handler handles incoming requests type Handler struct { Service *postgres.Database TokenVerifier budgeteer.TokenVerifier CredentialsVerifier *bcrypt.Verifier } const ( expiration = 72 ) // Serve starts the HTTP Server func (h *Handler) Serve() { router := gin.Default() router.FuncMap["now"] = time.Now static, err := fs.Sub(web.Static, "dist") if err != nil { panic("couldn't open static files") } staticFS := http.FS(static) router.Use(enableCachingForStaticFiles()) router.NoRoute( func(c *gin.Context) { c.FileFromFS(c.Request.URL.Path, staticFS) }, ) withLogin := router.Group("") withLogin.Use(h.verifyLoginWithRedirect) withBudget := router.Group("") withBudget.Use(h.verifyLoginWithForbidden) withBudget.GET("/budget/:budgetid/:year/:month", h.budgeting) withBudget.GET("/budget/:budgetid/all-accounts", h.allAccounts) withBudget.GET("/budget/:budgetid/settings/clean-negative", h.cleanNegativeBudget) withBudget.GET("/budget/:budgetid/transaction/:transactionid", h.transaction) api := router.Group("/api/v1") unauthenticated := api.Group("/user") unauthenticated.GET("/login", func(c *gin.Context) { c.Redirect(http.StatusPermanentRedirect, "/login") }) unauthenticated.POST("/login", h.loginPost) unauthenticated.POST("/register", h.registerPost) authenticated := api.Group("") authenticated.Use(h.verifyLoginWithForbidden) authenticated.GET("/dashboard", h.dashboard) authenticated.GET("/account/:accountid/transactions", h.transactionsForAccount) authenticated.GET("/admin/clear-database", h.clearDatabase) authenticated.GET("/budget/:budgetid", h.budgeting) authenticated.POST("/budget/:budgetid/import/ynab", h.importYNAB) authenticated.POST("/budget/:budgetid/settings/clear", h.clearBudget) budget := authenticated.Group("/budget") budget.POST("/new", h.newBudget) transaction := authenticated.Group("/transaction") transaction.POST("/new", h.newTransaction) transaction.POST("/:transactionid", h.newTransaction) router.Run(":1323") } func enableCachingForStaticFiles() gin.HandlerFunc { return func(c *gin.Context) { if strings.HasPrefix(c.Request.RequestURI, "/static/") { c.Header("Cache-Control", "max-age=86400") } } }