package auth import ( "net/http" "slices" "git.schreifuchs.ch/schreifuchs/ng-blog/internal/model" ) // Authenticated: This function is a middleware that authenticates incoming HTTP requests using JWT tokens and role-based access control. func (s *Service) Authenticated(next http.HandlerFunc, roles ...model.Role) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Our middleware logic goes here... token, err := extractToken(r) if err != nil { w.WriteHeader(http.StatusUnauthorized) return } claims, err := s.validateJWT(token) if err != nil { w.WriteHeader(http.StatusUnauthorized) return } // if roles specified check if satisfied if len(roles) > 0 && !slices.Contains(roles, claims.Role) { w.WriteHeader(http.StatusForbidden) return } r = writeToContext(r, &claims) next(w, r) }) }