2024-07-14 13:47:48 -04:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
2024-08-08 22:01:03 -04:00
|
|
|
"io/fs"
|
2024-07-14 13:47:48 -04:00
|
|
|
"net/http"
|
2024-08-08 22:01:03 -04:00
|
|
|
"strings"
|
2024-07-14 17:39:03 -04:00
|
|
|
"time"
|
2024-07-14 13:47:48 -04:00
|
|
|
|
2024-08-08 22:01:03 -04:00
|
|
|
"dynatron.me/x/stillbox/client"
|
2024-07-14 21:26:53 -04:00
|
|
|
"dynatron.me/x/stillbox/pkg/gordio/database"
|
2024-07-14 13:47:48 -04:00
|
|
|
"github.com/go-chi/chi/v5"
|
2024-07-14 21:26:53 -04:00
|
|
|
"github.com/go-chi/chi/v5/middleware"
|
2024-07-14 17:39:03 -04:00
|
|
|
"github.com/go-chi/httprate"
|
|
|
|
"github.com/go-chi/render"
|
2024-07-14 13:47:48 -04:00
|
|
|
)
|
|
|
|
|
|
|
|
func (s *Server) setupRoutes() {
|
2024-08-10 10:42:22 -04:00
|
|
|
clientRoot, err := fs.Sub(client.Calls, "calls")
|
2024-08-08 22:01:03 -04:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
|
2024-07-14 13:47:48 -04:00
|
|
|
r := s.r
|
2024-07-15 22:31:49 -04:00
|
|
|
r.Use(middleware.WithValue(database.DBCTXKeyValue, s.db))
|
2024-07-14 13:47:48 -04:00
|
|
|
|
|
|
|
r.Group(func(r chi.Router) {
|
2024-07-29 00:29:16 -04:00
|
|
|
// authenticated routes
|
2024-08-04 01:53:19 -04:00
|
|
|
r.Use(s.auth.VerifyMiddleware(), s.auth.AuthMiddleware())
|
2024-08-04 07:39:52 -04:00
|
|
|
s.nex.PrivateRoutes(r)
|
2024-07-14 13:47:48 -04:00
|
|
|
})
|
|
|
|
|
2024-07-14 17:39:03 -04:00
|
|
|
r.Group(func(r chi.Router) {
|
|
|
|
r.Use(rateLimiter())
|
|
|
|
r.Use(render.SetContentType(render.ContentTypeJSON))
|
2024-07-14 13:47:48 -04:00
|
|
|
// public routes
|
2024-08-03 00:16:23 -04:00
|
|
|
s.auth.PublicRoutes(r)
|
|
|
|
s.sources.PublicRoutes(r)
|
2024-07-14 13:47:48 -04:00
|
|
|
})
|
|
|
|
|
|
|
|
r.Group(func(r chi.Router) {
|
2024-08-03 00:05:02 -04:00
|
|
|
r.Use(rateLimiter(), s.auth.VerifyMiddleware())
|
2024-07-14 13:47:48 -04:00
|
|
|
|
|
|
|
// optional auth routes
|
|
|
|
|
2024-08-08 22:01:03 -04:00
|
|
|
s.clientRoute(r, clientRoot)
|
2024-07-14 13:47:48 -04:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-07-14 17:39:03 -04:00
|
|
|
func rateLimiter() func(http.Handler) http.Handler {
|
|
|
|
return httprate.LimitByRealIP(100, 1*time.Minute)
|
|
|
|
}
|
|
|
|
|
2024-08-08 22:01:03 -04:00
|
|
|
func (s *Server) clientRoute(r chi.Router, clientRoot fs.FS) {
|
|
|
|
r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
rctx := chi.RouteContext(r.Context())
|
|
|
|
pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
|
|
|
|
fs := http.StripPrefix(pathPrefix, http.FileServer(http.FS(clientRoot)))
|
|
|
|
fs.ServeHTTP(w, r)
|
|
|
|
/*
|
|
|
|
if cl, authenticated := s.auth.Authenticated(r); authenticated {
|
|
|
|
w.Write([]byte("Hello " + cl["user"].(string) + "\n"))
|
|
|
|
}
|
|
|
|
w.Write([]byte("Welcome to gordio\n"))
|
|
|
|
*/
|
|
|
|
})
|
2024-07-14 13:47:48 -04:00
|
|
|
}
|