mirror of
https://git.freecumextremist.com/grumbulon/pomme.git
synced 2024-12-23 08:50:42 +00:00
61 lines
1.6 KiB
Go
61 lines
1.6 KiB
Go
package api
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.freecumextremist.com/grumbulon/pomme/internal"
|
|
"github.com/go-chi/chi/v5"
|
|
"github.com/go-chi/httprate"
|
|
"github.com/go-chi/jwtauth/v5"
|
|
"github.com/go-chi/render"
|
|
)
|
|
|
|
// API subroute handler.
|
|
func API() http.Handler {
|
|
api := chi.NewRouter()
|
|
|
|
// Protected routes
|
|
api.Group(func(api chi.Router) {
|
|
api.Use(httprate.Limit(
|
|
10, // requests
|
|
10*time.Second, // per duration
|
|
httprate.WithKeyFuncs(httprate.KeyByIP, httprate.KeyByEndpoint),
|
|
httprate.WithLimitHandler(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusTooManyRequests)
|
|
resp := internal.Response{
|
|
Message: "API rate limit exceded",
|
|
}
|
|
render.JSON(w, r, resp)
|
|
}),
|
|
))
|
|
api.Use(jwtauth.Verifier(tokenAuth))
|
|
|
|
api.Use(jwtauth.Authenticator)
|
|
api.With(setDBMiddleware).Post("/upload", ReceiveFile)
|
|
})
|
|
|
|
// Open routes
|
|
api.Group(func(api chi.Router) {
|
|
api.Use(httprate.Limit(
|
|
5, // requests
|
|
5*time.Second, // per duration
|
|
httprate.WithKeyFuncs(httprate.KeyByIP, httprate.KeyByEndpoint),
|
|
httprate.WithLimitHandler(func(w http.ResponseWriter, r *http.Request) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
w.WriteHeader(http.StatusTooManyRequests)
|
|
resp := internal.Response{
|
|
Message: "API rate limit exceded",
|
|
}
|
|
render.JSON(w, r, resp)
|
|
}),
|
|
))
|
|
api.Use(setDBMiddleware)
|
|
api.With(setDBMiddleware).Post("/create", NewUser)
|
|
api.With(setDBMiddleware).Post("/login", Login)
|
|
api.Post("/logout", Logout)
|
|
})
|
|
|
|
return api
|
|
}
|