You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

60 lines
1.9 KiB

package web
import (
"database/sql"
"encoding/json"
"net/http"
"github.com/domagojzecevic/cammonitor/internal/auth"
"github.com/domagojzecevic/cammonitor/internal/config"
"github.com/domagojzecevic/cammonitor/internal/footage"
imagebrowser "github.com/domagojzecevic/cammonitor/internal/image"
videobrowser "github.com/domagojzecevic/cammonitor/internal/video"
"github.com/go-chi/chi/v5"
)
func NewRouter(cfg *config.Config, database *sql.DB, index *footage.Index) chi.Router {
router := chi.NewRouter()
router.Get("/health", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_ = json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
})
if cfg == nil || database == nil {
return router
}
store := auth.NewStore(database)
authHandler := auth.NewHandler(store, cfg.SessionTTL)
webHandler := NewHandler(index)
imageHandler := imagebrowser.NewHandler(cfg, index)
videoHandler := videobrowser.NewHandler(cfg, index)
router.Get("/login", authHandler.LoginPage)
router.Post("/login", authHandler.Login)
router.Post("/logout", authHandler.Logout)
router.Group(func(protected chi.Router) {
protected.Use(auth.RequireAuth(store))
protected.Get("/", webHandler.Index)
protected.Get("/day/{date}", webHandler.DayOverview)
protected.Get("/day/{date}/images", imageHandler.ServePage)
protected.Get("/day/{date}/videos", videoHandler.ServePage)
protected.Get("/raw/image/*", imageHandler.ServeRaw)
protected.Get("/thumb/image/*", imageHandler.ServeThumb)
protected.Get("/stream/video/*", videoHandler.ServeStream)
protected.Get("/thumb/video/*", videoHandler.ServeThumb)
protected.Group(func(admin chi.Router) {
admin.Use(auth.RequireAdmin)
admin.Get("/admin/users", authHandler.UsersPage)
admin.Post("/admin/users", authHandler.CreateUser)
admin.Post("/admin/users/{id}/delete", authHandler.DeleteUser)
})
})
return router
}