101 lines
2.5 KiB
Go
101 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/labstack/echo/v4/middleware"
|
|
)
|
|
|
|
func main() {
|
|
// Database Setup
|
|
dbPath := os.Getenv("DB_PATH")
|
|
if dbPath == "" {
|
|
dbPath = "./timetracking.db"
|
|
}
|
|
|
|
db := InitDB(dbPath)
|
|
defer db.Close()
|
|
|
|
app := &App{DB: db}
|
|
|
|
// Echo instance
|
|
e := echo.New()
|
|
|
|
// Middleware
|
|
e.Use(middleware.Logger())
|
|
e.Use(middleware.Recover())
|
|
e.Use(middleware.CORSWithConfig(middleware.CORSConfig{
|
|
AllowOrigins: []string{"*"},
|
|
AllowMethods: []string{http.MethodGet, http.MethodPost, http.MethodPut, http.MethodDelete},
|
|
AllowHeaders: []string{echo.HeaderOrigin, echo.HeaderContentType, echo.HeaderAccept, echo.HeaderAuthorization},
|
|
}))
|
|
|
|
// Custom error handler
|
|
e.HTTPErrorHandler = customHTTPErrorHandler
|
|
|
|
// Public routes
|
|
e.POST("/api/login", app.LoginHandler)
|
|
|
|
// Protected routes group
|
|
protected := e.Group("/api")
|
|
protected.Use(JWTMiddleware())
|
|
{
|
|
protected.GET("/schedules", app.GetSchedulesHandler)
|
|
protected.POST("/time-entries", app.CreateTimeEntryHandler)
|
|
protected.GET("/my-time-entries", app.GetMyTimeEntriesHandler)
|
|
protected.DELETE("/my-time-entries/week", app.DeleteWeekEntries)
|
|
protected.GET("/week-dates", app.GetWeekDates) // NEU
|
|
protected.GET("/week-has-entries", app.CheckWeekHasEntries) // NEU
|
|
}
|
|
|
|
// Admin routes group
|
|
admin := e.Group("/api/admin")
|
|
admin.Use(JWTMiddleware())
|
|
admin.Use(AdminMiddleware())
|
|
{
|
|
admin.POST("/schedules", app.CreateScheduleHandler)
|
|
admin.DELETE("/schedules/delete", app.DeleteScheduleHandler)
|
|
admin.POST("/users", app.CreateUserHandler)
|
|
admin.GET("/users/list", app.GetUsersHandler)
|
|
admin.DELETE("/users/delete", app.DeleteUserHandler)
|
|
admin.GET("/time-entries", app.GetAllTimeEntriesHandler)
|
|
admin.GET("/weekly-hours", app.GetWeeklyHoursHandler)
|
|
}
|
|
|
|
// Static files
|
|
e.Static("/", "./static")
|
|
|
|
// Start server
|
|
port := os.Getenv("PORT")
|
|
if port == "" {
|
|
port = "8080"
|
|
}
|
|
|
|
log.Printf("Server starting on port %s", port)
|
|
e.Logger.Fatal(e.Start(":" + port))
|
|
}
|
|
|
|
// Custom error handler for better error responses
|
|
func customHTTPErrorHandler(err error, c echo.Context) {
|
|
code := http.StatusInternalServerError
|
|
message := "Internal Server Error"
|
|
|
|
if he, ok := err.(*echo.HTTPError); ok {
|
|
code = he.Code
|
|
message = he.Message.(string)
|
|
}
|
|
|
|
// Don't override response if already written
|
|
if !c.Response().Committed {
|
|
if c.Request().Method == http.MethodHead {
|
|
c.NoContent(code)
|
|
} else {
|
|
c.JSON(code, map[string]string{
|
|
"error": message,
|
|
})
|
|
}
|
|
}
|
|
}
|