2024-07-14 13:47:48 -04:00
|
|
|
package server
|
|
|
|
|
|
|
|
import (
|
|
|
|
"net/http"
|
2024-07-14 17:39:03 -04:00
|
|
|
"time"
|
2024-07-14 13:47:48 -04:00
|
|
|
|
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() {
|
|
|
|
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
|
|
|
|
|
|
|
|
r.Get("/", s.routeIndex)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2024-07-14 17:39:03 -04:00
|
|
|
func rateLimiter() func(http.Handler) http.Handler {
|
|
|
|
return httprate.LimitByRealIP(100, 1*time.Minute)
|
|
|
|
}
|
|
|
|
|
2024-07-14 13:47:48 -04:00
|
|
|
func (s *Server) routeIndex(w http.ResponseWriter, r *http.Request) {
|
2024-07-29 00:29:16 -04:00
|
|
|
if cl, authenticated := s.auth.Authenticated(r); authenticated {
|
2024-07-14 17:39:03 -04:00
|
|
|
w.Write([]byte("Hello " + cl["user"].(string) + "\n"))
|
2024-07-14 13:47:48 -04:00
|
|
|
}
|
2024-07-14 17:39:03 -04:00
|
|
|
w.Write([]byte("Welcome to gordio\n"))
|
2024-07-14 13:47:48 -04:00
|
|
|
}
|