From 51d9cc039799d84a044813af3f8bb5d832bd2827 Mon Sep 17 00:00:00 2001 From: d1slike Date: Tue, 26 Jul 2022 21:36:08 +0300 Subject: [PATCH] MSP-437 implement auth middleware --- middleware/authenticate.go | 43 ++++++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/middleware/authenticate.go b/middleware/authenticate.go index 52d5667..c0a9c5c 100644 --- a/middleware/authenticate.go +++ b/middleware/authenticate.go @@ -1,31 +1,48 @@ package middleware import ( + "context" + "net/http" + "strings" + "github.com/pkg/errors" "isp-gate-service/domain" + "isp-gate-service/httperrors" + "isp-gate-service/request" ) const ( - adminTokenHeader = "x-auth-admin" + applicationTokenHeader = "x-application-token" ) -type AdminAuthenticate interface { - Authenticate(token string) (int, error) +type Authenticator interface { + Authenticate(ctx context.Context, token string) (*domain.AuthenticateResponse, error) } -func Authenticate(adminAuthenticate AdminAuthenticate) Middleware { +func Authenticate(authenticator Authenticator) Middleware { return func(next Handler) Handler { - return HandlerFunc(func(ctx *Context) error { - ctx.AppId = 1 // todo application - - adminToken := ctx.Request.Header.Get(adminTokenHeader) - adminId, err := adminAuthenticate.Authenticate(adminToken) - if err != nil { - return errors.WithMessagef(domain.ErrAuthenticate, "admin athenticate: %v", err) + return HandlerFunc(func(ctx *request.Context) error { + token := strings.TrimSpace(ctx.Request().Header.Get(applicationTokenHeader)) + if token == "" { + return httperrors.New( + http.StatusUnauthorized, + "application token required", + errors.New("authenticate: application token required"), + ) } - ctx.AdminId = adminId - ctx.authenticated = true + resp, err := authenticator.Authenticate(ctx.Context(), token) + if err != nil { + return errors.WithMessagef(err, "authenticate: authenticate") + } + if !resp.Authenticated { + return httperrors.New( + http.StatusUnauthorized, + "invalid application token", + errors.WithMessage(errors.New(resp.ErrorReason), "authenticate: authenticate"), + ) + } + ctx.Authenticate(request.AuthData(*resp.AuthData)) return next.Handle(ctx) })