Merge pull request 'Add middleware for AdminRouter and added IsAdmin function' (#5) from feature/admin into main

Reviewed-on: #5
This commit is contained in:
luiz 2024-11-24 15:52:53 +00:00
commit 43c2abf138
2 changed files with 32 additions and 6 deletions

View File

@ -34,6 +34,7 @@ type UserClaims struct {
Username string `json:"cognito:username"` Username string `json:"cognito:username"`
Picture string `json:"picture"` Picture string `json:"picture"`
Sub string `json:"sub"` Sub string `json:"sub"`
Groups []string `json:"cognito:groups"`
} }
func generateState() (string, error) { func generateState() (string, error) {

View File

@ -85,6 +85,31 @@ func (m *Middleware) ProtectedRouteWithRedirect(next http.Handler) http.Handler
}) })
} }
// IsAdmin Checks if admin group is present
func IsAdmin(groups []string) bool {
for _, group := range groups {
if group == "admin" {
return true
}
}
return false
}
// AdminProtectedRoute Checks if user is member of admin group, if not return forbidden
func (m *Middleware) AdminProtectedRoute(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
userOptional := r.Context().Value(userContextKey)
if userOptional != nil {
user := userOptional.(UserClaims)
if IsAdmin(user.Groups) {
next.ServeHTTP(w, r)
}
}
http.Error(w, "Forbidden", http.StatusForbidden)
})
}
func GetUserFromContext(r *http.Request) *UserClaims { func GetUserFromContext(r *http.Request) *UserClaims {
userOptional := r.Context().Value(userContextKey) userOptional := r.Context().Value(userContextKey)
if userOptional != nil { if userOptional != nil {