MSP-437 implement auth middleware
This commit is contained in:
1 parent
f9f127f6b9
commit
51d9cc0397
1 file changed
+30
-13
+30
-13
@@ -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)
|
||||
})
|
||||
|
||||
Reference in new issue
Block a user