stillbox/pkg/gordio/server/routes.go

85 lines
1.8 KiB
Go
Raw Normal View History

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"
2024-07-14 13:47:48 -04:00
"github.com/go-chi/jwtauth/v5"
2024-07-14 17:39:03 -04:00
"github.com/go-chi/render"
2024-07-14 13:47:48 -04:00
)
func (s *Server) setupRoutes() {
r := s.r
r.Use(middleware.WithValue(database.DBCTXKeyValue, s.db))
2024-07-14 13:47:48 -04:00
r.Group(func(r chi.Router) {
r.Use(jwtauth.Verifier(s.jwt))
r.Use(jwtauth.Authenticator(s.jwt))
})
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-07-14 17:39:03 -04:00
r.Post("/auth", s.routeAuth)
2024-07-14 13:47:48 -04:00
})
r.Group(func(r chi.Router) {
2024-07-14 17:39:03 -04:00
r.Use(rateLimiter())
2024-07-14 13:47:48 -04:00
r.Use(jwtauth.Verifier(s.jwt))
// 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-14 17:39:03 -04:00
if cl, authenticated := s.Authenticated(r); authenticated {
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
}
2024-07-14 17:39:03 -04:00
func (s *Server) routeAuth(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
username, password := r.PostFormValue("username"), r.PostFormValue("password")
if username == "" || password == "" {
http.Error(w, "blank credentials", http.StatusBadRequest)
return
}
tok, err := s.Login(r.Context(), username, password)
if err != nil {
http.Error(w, err.Error(), http.StatusUnauthorized)
return
}
2024-07-15 19:03:48 -04:00
http.SetCookie(w, &http.Cookie{
Name: "jwt",
Value: tok,
HttpOnly: true,
Secure: true,
Domain: s.conf.Domain,
})
2024-07-14 17:39:03 -04:00
jr := struct {
JWT string `json:"jwt"`
}{
JWT: tok,
}
render.JSON(w, r, &jr)
2024-07-14 13:47:48 -04:00
}