diff --git a/pkg/auth/jwt.go b/pkg/auth/jwt.go index fc20edf..2eae750 100644 --- a/pkg/auth/jwt.go +++ b/pkg/auth/jwt.go @@ -94,8 +94,16 @@ func (a *Auth) AuthMiddleware() func(http.Handler) http.Handler { return } - if token != nil && jwt.Validate(token, a.jwt.ValidateOptions()...) == nil { - ctx := r.Context() + ctx := r.Context() + + if token != nil { + err := jwt.Validate(token, a.jwt.ValidateOptions()...) + if err != nil { + err = jwtauth.ErrorReason(err) + http.Error(w, err.Error(), http.StatusUnauthorized) + return + } + username := token.Subject() sub, err := users.FromCtx(ctx).GetUser(ctx, username) @@ -111,8 +119,9 @@ func (a *Auth) AuthMiddleware() func(http.Handler) http.Handler { return } - // Token is authenticated, pass it through - next.ServeHTTP(w, r) + // Public subject + ctx = entities.CtxWithSubject(ctx, entities.NewPublicSubject(r)) + next.ServeHTTP(w, r.WithContext(ctx)) } return http.HandlerFunc(hfn) } diff --git a/pkg/rbac/entities/entities.go b/pkg/rbac/entities/entities.go index eca0217..89553c0 100644 --- a/pkg/rbac/entities/entities.go +++ b/pkg/rbac/entities/entities.go @@ -2,6 +2,7 @@ package entities import ( "context" + "net/http" "github.com/el-mike/restrict/v2" ) @@ -66,6 +67,10 @@ func (s *PublicSubject) GetRoles() []string { return []string{RolePublic} } +func NewPublicSubject(r *http.Request) *PublicSubject { + return &PublicSubject{RemoteAddr: r.RemoteAddr} +} + type SystemServiceSubject struct { Name string }