51 lines
1.1 KiB
Go
51 lines
1.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type StatusRecorder struct {
|
|
gin.ResponseWriter
|
|
statusCode int
|
|
}
|
|
|
|
// WriteHeader records the status code and calls the original WriteHeader.
|
|
func (sr *StatusRecorder) WriteHeader(code int) {
|
|
sr.statusCode = code
|
|
sr.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
// GetStatusCode returns the recorded status code.
|
|
func (sr *StatusRecorder) GetStatusCode() int {
|
|
return sr.statusCode
|
|
}
|
|
|
|
func authorize(user *User, routePermission string, httpRoutePermissionMap map[string]string) bool {
|
|
for routePattern, requiredPermission := range httpRoutePermissionMap {
|
|
if matchRoute(routePermission, routePattern) {
|
|
return isPermitted(user, requiredPermission)
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func matchRoute(route string, pattern string) bool {
|
|
regexPattern := strings.ReplaceAll(pattern, "{param}", "[^/]+")
|
|
regexPattern = "^" + regexPattern + "$"
|
|
re := regexp.MustCompile(regexPattern)
|
|
return re.MatchString(route)
|
|
}
|
|
|
|
func isPermitted(user *User, permission string) bool {
|
|
for _, p := range user.Permissions {
|
|
if p == permission {
|
|
return true
|
|
}
|
|
}
|
|
|
|
return false
|
|
}
|