62 lines
1.6 KiB
Go
62 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"isp-gate-service/domain"
|
|
"isp-gate-service/httperrors"
|
|
"isp-gate-service/request"
|
|
|
|
"github.com/txix-open/isp-kit/errors"
|
|
"github.com/txix-open/isp-kit/log"
|
|
)
|
|
|
|
type UserAuthenticator interface {
|
|
Authenticate(ctx *request.Context) (*domain.AuthenticateUserResponse, error)
|
|
}
|
|
|
|
func UserAuthenticate(authenticator UserAuthenticator, logger log.Logger) Middleware {
|
|
return func(next Handler) Handler {
|
|
return HandlerFunc(func(ctx *request.Context) error {
|
|
resp, err := authenticator.Authenticate(ctx)
|
|
switch {
|
|
case errors.Is(err, domain.ErrEmptyUserToken):
|
|
return httperrors.New(
|
|
http.StatusUnauthorized,
|
|
"user token required",
|
|
errors.New("customAuth: authenticate user: user token required"),
|
|
)
|
|
case errors.Is(err, domain.ErrInvalidUserToken):
|
|
return httperrors.New(
|
|
http.StatusUnauthorized,
|
|
"invalid user token",
|
|
errors.WithMessage(err, "customAuth: authenticate user: invalid user token"),
|
|
)
|
|
case err != nil:
|
|
return errors.WithMessage(err, "customAuth: authenticate user: authenticator error")
|
|
}
|
|
|
|
if resp.SkipUserAuth {
|
|
return next.Handle(ctx)
|
|
}
|
|
if !resp.Authenticated {
|
|
return httperrors.New(
|
|
http.StatusUnauthorized,
|
|
"invalid user token",
|
|
errors.Errorf("customAuth: authenticate user: authenticate: %s", resp.ErrorReason),
|
|
)
|
|
}
|
|
|
|
ctx.AuthenticateUser(*resp.AuthData)
|
|
|
|
if ctx.SkipAppAuth() {
|
|
logger.Debug(
|
|
ctx.Context(),
|
|
"skip app auth is set. All steps that require app auth data are skipped",
|
|
)
|
|
}
|
|
return next.Handle(ctx)
|
|
})
|
|
}
|
|
}
|