package serverconfig

import (
	"bitbucket.org/nemt/nemt-portal-api/infra/auth"
	"bitbucket.org/nemt/nemt-portal-api/infra/config"
	"bitbucket.org/nemt/nemt-portal-api/infra/errors"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

func setJWTMiddleware(e *echo.Echo, cfg *config.Config) error {
	key, err := auth.GetCertPublicKey(cfg.HTTP.Auth.CertificatePath)
	if err != nil {
		return errors.Wrap(err)
	}

	e.Pre(middlewareErrorWrapper(middleware.JWTWithConfig(middleware.JWTConfig{
		TokenLookup:   "header:" + auth.AppTokenHeaderName,
		Skipper:       authSkipper,
		SigningKey:    key,
		SigningMethod: auth.TokenSigningMethod.Name,
	})))

	return nil
}
