From ff7bbec976d00fcb414d0285547259d6468b8e5a Mon Sep 17 00:00:00 2001 From: Akshay Gaikwad Date: Thu, 24 Feb 2022 13:56:46 +0530 Subject: [PATCH] Add authentication middleware --- components/common/pkg/auth/v3/middleware.go | 32 ++++++++++++++------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/components/common/pkg/auth/v3/middleware.go b/components/common/pkg/auth/v3/middleware.go index 1ca45f2..fc7b8ee 100644 --- a/components/common/pkg/auth/v3/middleware.go +++ b/components/common/pkg/auth/v3/middleware.go @@ -3,17 +3,21 @@ package authv3 import ( "net/http" + commonpbv3 "github.com/RafaySystems/rcloud-base/components/common/proto/types/commonpb/v3" commonv3 "github.com/RafaySystems/rcloud-base/components/common/proto/types/commonpb/v3" "github.com/urfave/negroni" ) type authMiddleware struct { - ac authContext + ac authContext + opt Option } -// Not maintained. Instead use gRPC interceptor for authentication. -func (ac authContext) NewAuthMiddleware() negroni.Handler { - return &authMiddleware{ac} +func NewAuthMiddleware(opt Option) negroni.Handler { + return &authMiddleware{ + ac: NewAuthContext(), + opt: opt, + } } func (am *authMiddleware) ServeHTTP(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) { @@ -25,19 +29,25 @@ func (am *authMiddleware) ServeHTTP(rw http.ResponseWriter, r *http.Request, nex } res, err := am.ac.IsRequestAllowed(r.Context(), req) if err != nil { + _log.Errorf("Failed to authenticate a request: %s", err) http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) return } - if res.GetStatus() == commonv3.RequestStatus_RequestNotAuthenticated { - http.Error(rw, res.GetReason(), http.StatusUnauthorized) - return - } else if res.GetStatus() == commonv3.RequestStatus_RequestMethodOrURLNotAllowed { + s := res.GetStatus() + switch s { + case commonpbv3.RequestStatus_RequestAllowed: + ctx := newSessionContext(r.Context(), res.SessionData) + next(rw, r.WithContext(ctx)) + case commonpbv3.RequestStatus_RequestMethodOrURLNotAllowed: http.Error(rw, res.GetReason(), http.StatusForbidden) return + case commonpbv3.RequestStatus_RequestNotAuthenticated: + http.Error(rw, res.GetReason(), http.StatusUnauthorized) + return } - if res.GetStatus() == commonv3.RequestStatus_RequestAllowed { - next(rw, r) - } + // status is unknown + http.Error(rw, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return }