serve frontend from go
This commit is contained in:
35
internal/auth/middleware.go
Normal file
35
internal/auth/middleware.go
Normal file
@ -0,0 +1,35 @@
|
||||
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)
|
||||
})
|
||||
}
|
Reference in New Issue
Block a user