hydra-passwordless/internal/route/verify.go

95 lines
2.2 KiB
Go

package route
import (
"net/http"
"forge.cadoles.com/wpetit/hydra-passwordless/internal/config"
"forge.cadoles.com/wpetit/hydra-passwordless/internal/hydra"
"forge.cadoles.com/wpetit/hydra-passwordless/internal/query"
"github.com/getsentry/sentry-go"
"github.com/pkg/errors"
"gitlab.com/wpetit/goweb/cqrs"
"gitlab.com/wpetit/goweb/logger"
"gitlab.com/wpetit/goweb/middleware/container"
)
func handleVerification(w http.ResponseWriter, r *http.Request) {
ctn := container.Must(r.Context())
bus := cqrs.Must(ctn)
conf := config.Must(ctn)
token := r.URL.Query().Get("token")
if token == "" {
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
qry := &query.VerifyUserRequest{
Token: token,
}
ctx := r.Context()
result, err := bus.Query(ctx, qry)
if err != nil {
sentry.CaptureException(err)
logger.Error(ctx, "could not verify token", logger.E(err))
err := renderErrorPage(
w, r,
http.StatusBadRequest,
"Lien invalide",
"Le lien de connexion utilisé est invalide ou a expiré.",
)
if err != nil {
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
}
return
}
verifyUserData, ok := result.Data().(*query.VerifyUserData)
if !ok {
err := errors.New("unexpected result data")
sentry.CaptureException(err)
panic(err)
}
hydr := hydra.Must(ctn)
rememberFor := conf.Session.DefaultDuration
if verifyUserData.RememberMe {
rememberFor = conf.Session.RememberMeDuration
}
accept := &hydra.AcceptLoginRequest{
Subject: verifyUserData.Email,
Remember: verifyUserData.RememberMe,
RememberFor: rememberFor,
Context: map[string]interface{}{
"email": verifyUserData.Email,
},
}
res, err := hydr.AcceptLoginRequest(verifyUserData.Challenge, accept)
if err != nil {
sentry.CaptureException(err)
logger.Error(ctx, "could not retrieve hydra accept response", logger.E(err))
err := renderErrorPage(
w, r,
http.StatusBadRequest,
"Lien invalide",
"Le lien de connexion utilisé est invalide ou a expiré.",
)
if err != nil {
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
}
return
}
http.Redirect(w, r, res.RedirectTo, http.StatusSeeOther)
}