1
0
mirror of https://github.com/NginxProxyManager/nginx-proxy-manager.git synced 2025-07-15 03:41:48 +03:00

Improvements to enforce middleware, linting, returning 404 properly

This commit is contained in:
Jamie Curnow
2024-09-11 15:03:00 +10:00
parent 833dd23dce
commit 9a2e5c92d5
18 changed files with 110 additions and 104 deletions

View File

@ -4,6 +4,7 @@ import (
"context"
"fmt"
"net/http"
"slices"
c "npm/internal/api/context"
h "npm/internal/api/http"
@ -11,7 +12,6 @@ import (
"npm/internal/entity/user"
njwt "npm/internal/jwt"
"npm/internal/logger"
"npm/internal/util"
"github.com/go-chi/jwtauth/v5"
)
@ -35,7 +35,7 @@ func DecodeAuth() func(http.Handler) http.Handler {
// Enforce is a authentication middleware to enforce access from the
// jwtauth.Verifier middleware request context values. The Authenticator sends a 401 Unauthorised
// response for any unverified tokens and passes the good ones through.
func Enforce(permission string) func(http.Handler) http.Handler {
func Enforce(permissions ...string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
@ -56,7 +56,7 @@ func Enforce(permission string) func(http.Handler) http.Handler {
}
// Check if permissions exist for this user
if permission != "" {
if len(permissions) > 0 {
// Since the permission that we require is not on the token, we have to get it from the DB
// So we don't go crazy with hits, we will use a memory cache
cacheKey := fmt.Sprintf("userCapabilties.%v", userID)
@ -75,9 +75,16 @@ func Enforce(permission string) func(http.Handler) http.Handler {
// Now check that they have the permission in their admin capabilities
// full-admin can do anything
if !util.SliceContainsItem(userCapabilities, user.CapabilityFullAdmin) && !util.SliceContainsItem(userCapabilities, permission) {
hasOnePermission := false
for _, permission := range permissions {
if slices.Contains(userCapabilities, user.CapabilityFullAdmin) || slices.Contains(userCapabilities, permission) {
hasOnePermission = true
}
}
if !hasOnePermission {
// Access denied
logger.Debug("User has: %+v but needs %s", userCapabilities, permission)
logger.Debug("Enforce Failed: User has %v but needs %v", userCapabilities, permissions)
h.ResultErrorJSON(w, r, http.StatusForbidden, "Forbidden", nil)
return
}