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.
50 lines
1.3 KiB
50 lines
1.3 KiB
package web
|
|
|
|
import (
|
|
"database/sql"
|
|
"encoding/json"
|
|
"net/http"
|
|
|
|
"github.com/domagojzecevic/cammonitor/internal/auth"
|
|
"github.com/domagojzecevic/cammonitor/internal/config"
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
func NewRouter(cfg *config.Config, database *sql.DB, _ any) 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)
|
|
|
|
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("/", func(w http.ResponseWriter, _ *http.Request) {
|
|
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
|
_, _ = w.Write([]byte("CamMonitor"))
|
|
})
|
|
|
|
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
|
|
}
|
|
|