feat(api tokens): move token validation middleware to new function
This commit is contained in:
@ -51,7 +51,6 @@ package routes
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
@ -81,7 +80,6 @@ import (
|
||||
|
||||
"github.com/getsentry/sentry-go"
|
||||
sentryecho "github.com/getsentry/sentry-go/echo"
|
||||
echojwt "github.com/labstack/echo-jwt/v4"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
elog "github.com/labstack/gommon/log"
|
||||
@ -281,50 +279,7 @@ func registerAPIRoutes(a *echo.Group) {
|
||||
}
|
||||
|
||||
// ===== Routes with Authentication =====
|
||||
a.Use(echojwt.WithConfig(echojwt.Config{
|
||||
SigningKey: []byte(config.ServiceJWTSecret.GetString()),
|
||||
Skipper: func(c echo.Context) bool {
|
||||
authHeader := c.Request().Header.Values("Authorization")
|
||||
if len(authHeader) == 0 {
|
||||
return false // let the jwt middleware handle invalid headers
|
||||
}
|
||||
|
||||
for _, s := range authHeader {
|
||||
if strings.HasPrefix(s, "Bearer "+models.APITokenPrefix) {
|
||||
c.Set("api_token", s)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
},
|
||||
}))
|
||||
|
||||
a.Use(func(next echo.HandlerFunc) echo.HandlerFunc {
|
||||
return func(c echo.Context) error {
|
||||
// If this is empty we assume we're dealing with a "real" user who has provided a jwt
|
||||
tokenString, is := c.Get("api_token").(string)
|
||||
if !is || tokenString == "" {
|
||||
return next(c)
|
||||
}
|
||||
token, err := models.GetTokenFromTokenString(db.NewSession(), strings.TrimPrefix(tokenString, "Bearer "))
|
||||
if err != nil {
|
||||
return echo.NewHTTPError(http.StatusInternalServerError).SetInternal(err)
|
||||
}
|
||||
|
||||
if time.Now().After(token.ExpiresAt) {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
if !models.CanDoAPIRoute(c, token) {
|
||||
return echo.NewHTTPError(http.StatusUnauthorized)
|
||||
}
|
||||
|
||||
c.Set("api_token", token)
|
||||
|
||||
return next(c)
|
||||
}
|
||||
})
|
||||
a.Use(SetupTokenMiddleware())
|
||||
|
||||
// Rate limit
|
||||
setupRateLimit(a, config.RateLimitKind.GetString())
|
||||
|
Reference in New Issue
Block a user