initial commit
This commit is contained in:
50
internal/server/middleware/utils.go
Normal file
50
internal/server/middleware/utils.go
Normal file
@@ -0,0 +1,50 @@
|
||||
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
|
||||
}
|
||||
Reference in New Issue
Block a user