Basic but complete authentication flow
This commit is contained in:
104
internal/command/send_confirmation_email.go
Normal file
104
internal/command/send_confirmation_email.go
Normal file
@ -0,0 +1,104 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/config"
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/hydra"
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/mail"
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/token"
|
||||
"github.com/aymerick/douceur/inliner"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/cqrs"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
"gitlab.com/wpetit/goweb/service/build"
|
||||
"gitlab.com/wpetit/goweb/service/template"
|
||||
)
|
||||
|
||||
type SendConfirmationEmailRequest struct {
|
||||
Email string
|
||||
Challenge string
|
||||
DefaultScheme string
|
||||
DefaultAddress string
|
||||
}
|
||||
|
||||
func HandleSendConfirmationEmailRequest(ctx context.Context, cmd cqrs.Command) error {
|
||||
req, ok := cmd.Request().(*SendConfirmationEmailRequest)
|
||||
if !ok {
|
||||
return cqrs.ErrUnexpectedRequest
|
||||
}
|
||||
|
||||
ctn := container.Must(ctx)
|
||||
tmpl := template.Must(ctn)
|
||||
hydr := hydra.Must(ctn)
|
||||
info := build.Must(ctn)
|
||||
ml := mail.Must(ctn)
|
||||
conf := config.Must(ctn)
|
||||
|
||||
_, err := hydr.LoginRequest(req.Challenge)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not retrieve hydra login response")
|
||||
}
|
||||
|
||||
token, err := token.Generate(
|
||||
conf.HTTP.TokenSigningKey,
|
||||
conf.HTTP.TokenEncryptionKey,
|
||||
req.Email,
|
||||
req.Challenge,
|
||||
)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not generate jwt")
|
||||
}
|
||||
|
||||
address := req.DefaultAddress
|
||||
if conf.HTTP.PublicAddress != "" {
|
||||
address = conf.HTTP.PublicAddress
|
||||
}
|
||||
|
||||
scheme := req.DefaultScheme
|
||||
if scheme == "" {
|
||||
scheme = "http:"
|
||||
}
|
||||
|
||||
if conf.HTTP.PublicScheme != "" {
|
||||
scheme = conf.HTTP.PublicScheme
|
||||
}
|
||||
|
||||
log.Println(req, scheme)
|
||||
|
||||
verificationLink := fmt.Sprintf("%s//%s/verify?token=%s", scheme, address, token)
|
||||
|
||||
log.Println(verificationLink)
|
||||
|
||||
data := template.Data{
|
||||
"BuildInfo": info,
|
||||
"VerificationLink": verificationLink,
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := tmpl.Render(&buf, "verification_email.html.tmpl", data); err != nil {
|
||||
return errors.Wrap(err, "could not render email template")
|
||||
}
|
||||
|
||||
// Inline CSS for mail clients
|
||||
html, err := inliner.Inline(buf.String())
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not inline css")
|
||||
}
|
||||
|
||||
err = ml.Send(
|
||||
mail.WithSender(conf.SMTP.SenderAddress, conf.SMTP.SenderName),
|
||||
mail.WithRecipients(req.Email),
|
||||
mail.WithSubject(fmt.Sprintf("[Authentification]")),
|
||||
mail.WithBody(mail.ContentTypeHTML, html, nil),
|
||||
mail.WithAlternativeBody(mail.ContentTypeText, "", nil),
|
||||
)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not send email")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
@ -11,10 +11,9 @@ import (
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
HTTP HTTPConfig `yaml:"http"`
|
||||
TestApp TestAppConfig `yaml:"testApp"`
|
||||
SMTP SMTPConfig `yaml:"smtp"`
|
||||
Hydra HydraConfig `yaml:"hydra"`
|
||||
HTTP HTTPConfig `yaml:"http"`
|
||||
SMTP SMTPConfig `yaml:"smtp"`
|
||||
Hydra HydraConfig `yaml:"hydra"`
|
||||
}
|
||||
|
||||
// NewFromFile retrieves the configuration from the given file
|
||||
@ -37,17 +36,14 @@ type HTTPConfig struct {
|
||||
Address string `yaml:"address"`
|
||||
CookieAuthenticationKey string `yaml:"cookieAuthenticationKey"`
|
||||
CookieEncryptionKey string `yaml:"cookieEncryptionKey"`
|
||||
TokenSigningKey string `yaml:"tokenSigningKey"`
|
||||
TokenEncryptionKey string `yaml:"tokenEncryptionKey"`
|
||||
BasePublicURL string `yaml:"basePublicUrl"`
|
||||
CookieMaxAge int `yaml:"cookieMaxAge"`
|
||||
TemplateDir string `yaml:"templateDir"`
|
||||
PublicDir string `yaml:"publicDir"`
|
||||
}
|
||||
|
||||
type TestAppConfig struct {
|
||||
Enabled bool `yaml:"enabled"`
|
||||
ClientID string `yaml:"clientId"`
|
||||
ClientSecret string `yaml:"clientSecret"`
|
||||
IssuerURL string `ymal:"issuerUrl"`
|
||||
RedirectURL string `yaml:"redirectUrl"`
|
||||
PublicAddress string `yaml:"publicAddress"`
|
||||
PublicScheme string `yaml:"publicScheme"`
|
||||
}
|
||||
|
||||
type SMTPConfig struct {
|
||||
@ -76,14 +72,13 @@ func NewDefault() *Config {
|
||||
Address: ":3000",
|
||||
CookieAuthenticationKey: "",
|
||||
CookieEncryptionKey: "",
|
||||
TokenEncryptionKey: "",
|
||||
TokenSigningKey: "",
|
||||
CookieMaxAge: int((time.Hour * 1).Seconds()), // 1 hour
|
||||
TemplateDir: "template",
|
||||
PublicDir: "public",
|
||||
},
|
||||
TestApp: TestAppConfig{
|
||||
Enabled: false,
|
||||
IssuerURL: "http://localhost:4444/",
|
||||
RedirectURL: "http://localhost:3000/test/oauth2/callback",
|
||||
PublicAddress: "",
|
||||
PublicScheme: "",
|
||||
},
|
||||
SMTP: SMTPConfig{
|
||||
Host: "localhost",
|
||||
|
@ -41,8 +41,8 @@ func (c *Client) LoginRequest(challenge string) (*LoginResponse, error) {
|
||||
return loginRes, nil
|
||||
}
|
||||
|
||||
func (c *Client) AcceptRequest(challenge string, req *AcceptRequest) (*AcceptResponse, error) {
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/accept", url.Values{
|
||||
func (c *Client) AcceptLoginRequest(challenge string, req *AcceptLoginRequest) (*AcceptResponse, error) {
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/login/accept", url.Values{
|
||||
"login_challenge": []string{challenge},
|
||||
})
|
||||
|
||||
@ -55,8 +55,8 @@ func (c *Client) AcceptRequest(challenge string, req *AcceptRequest) (*AcceptRes
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (c *Client) RejectRequest(challenge string, req *RejectRequest) (*RejectResponse, error) {
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/reject", url.Values{
|
||||
func (c *Client) RejectLoginRequest(challenge string, req *RejectRequest) (*RejectResponse, error) {
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/login/reject", url.Values{
|
||||
"login_challenge": []string{challenge},
|
||||
})
|
||||
|
||||
@ -74,7 +74,57 @@ func (c *Client) LogoutRequest(challenge string) (*LogoutResponse, error) {
|
||||
}
|
||||
|
||||
func (c *Client) ConsentRequest(challenge string) (*ConsentResponse, error) {
|
||||
return nil, nil
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/consent", url.Values{
|
||||
"consent_challenge": []string{challenge},
|
||||
})
|
||||
|
||||
res, err := c.http.Get(u)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not retrieve login response")
|
||||
}
|
||||
|
||||
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
|
||||
return nil, errors.Wrapf(ErrUnexpectedHydraResponse, "hydra responded with status code '%d'", res.StatusCode)
|
||||
}
|
||||
|
||||
defer res.Body.Close()
|
||||
|
||||
decoder := json.NewDecoder(res.Body)
|
||||
consentRes := &ConsentResponse{}
|
||||
|
||||
if err := decoder.Decode(consentRes); err != nil {
|
||||
return nil, errors.Wrap(err, "could not decode json response")
|
||||
}
|
||||
|
||||
return consentRes, nil
|
||||
}
|
||||
|
||||
func (c *Client) AcceptConsentRequest(challenge string, req *AcceptConsentRequest) (*AcceptResponse, error) {
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/consent/accept", url.Values{
|
||||
"consent_challenge": []string{challenge},
|
||||
})
|
||||
|
||||
res := &AcceptResponse{}
|
||||
|
||||
if err := c.putJSON(u, req, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (c *Client) RejectConsentRequest(challenge string, req *RejectRequest) (*RejectResponse, error) {
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/consent/reject", url.Values{
|
||||
"consent_challenge": []string{challenge},
|
||||
})
|
||||
|
||||
res := &RejectResponse{}
|
||||
|
||||
if err := c.putJSON(u, req, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (c *Client) LoginChallenge(r *http.Request) (string, error) {
|
||||
|
@ -1,12 +1,25 @@
|
||||
package hydra
|
||||
|
||||
type AcceptRequest struct {
|
||||
type AcceptLoginRequest struct {
|
||||
Subject string `json:"subject"`
|
||||
Remember bool `json:"remember"`
|
||||
RememberFor int `json:"remember_for"`
|
||||
ACR string `json:"acr"`
|
||||
}
|
||||
|
||||
type AcceptConsentRequest struct {
|
||||
GrantScope []string `json:"grant_scope"`
|
||||
GrantAccessTokenAudience []string `json:"grant_access_token_audience"`
|
||||
Remember bool `json:"remember"`
|
||||
RememberFor int `json:"remember_for"`
|
||||
Session AcceptConsentSession `json:"session"`
|
||||
}
|
||||
|
||||
type AcceptConsentSession struct {
|
||||
AccessToken map[string]interface{} `json:"access_token"`
|
||||
IDToken map[string]interface{} `json:"id_token"`
|
||||
}
|
||||
|
||||
type RejectRequest struct {
|
||||
Error string `json:"error"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
|
@ -55,11 +55,12 @@ type LoginResponse struct {
|
||||
RequestURL string `json:"request_url"`
|
||||
RequestedScope []string `json:"requested_scope"`
|
||||
OidcContext OidcContextResponseFragment `json:"oidc_context"`
|
||||
RequestedAccessTokenAudience string `json:"requested_access_token_audience"`
|
||||
RequestedAccessTokenAudience []string `json:"requested_access_token_audience"`
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
|
||||
type AcceptResponse struct {
|
||||
RedirectTo string `json:"redirect_to"`
|
||||
}
|
||||
|
||||
type RejectResponse struct {
|
||||
@ -70,4 +71,13 @@ type LogoutResponse struct {
|
||||
}
|
||||
|
||||
type ConsentResponse struct {
|
||||
Challenge string `json:"challenge"`
|
||||
Skip bool `json:"skip"`
|
||||
Subject string `json:"subject"`
|
||||
Client ClientResponseFragment `json:"client"`
|
||||
RequestURL string `json:"request_url"`
|
||||
RequestedScope []string `json:"requested_scope"`
|
||||
OidcContext OidcContextResponseFragment `json:"oidc_context"`
|
||||
RequestedAccessTokenAudience []string `json:"requested_access_token_audience"`
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
|
47
internal/query/verify_user.go
Normal file
47
internal/query/verify_user.go
Normal file
@ -0,0 +1,47 @@
|
||||
package query
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/config"
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/token"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/cqrs"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
)
|
||||
|
||||
type VerifyUserRequest struct {
|
||||
Token string
|
||||
}
|
||||
|
||||
type VerifyUserData struct {
|
||||
Email string
|
||||
Challenge string
|
||||
}
|
||||
|
||||
func HandleVerifyUserRequest(ctx context.Context, qry cqrs.Query) (interface{}, error) {
|
||||
req, ok := qry.Request().(*VerifyUserRequest)
|
||||
if !ok {
|
||||
return nil, cqrs.ErrUnexpectedRequest
|
||||
}
|
||||
|
||||
ctn := container.Must(ctx)
|
||||
conf := config.Must(ctn)
|
||||
|
||||
email, challenge, err := token.Verify(
|
||||
conf.HTTP.TokenSigningKey,
|
||||
conf.HTTP.TokenEncryptionKey,
|
||||
req.Token,
|
||||
)
|
||||
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not verify token")
|
||||
}
|
||||
|
||||
data := &VerifyUserData{
|
||||
Email: email,
|
||||
Challenge: challenge,
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
@ -3,18 +3,64 @@ package route
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/hydra"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
"gitlab.com/wpetit/goweb/service/template"
|
||||
)
|
||||
|
||||
func serveConsentPage(w http.ResponseWriter, r *http.Request) {
|
||||
ctn := container.Must(r.Context())
|
||||
tmpl := template.Must(ctn)
|
||||
//tmpl := template.Must(ctn)
|
||||
hydr := hydra.Must(ctn)
|
||||
|
||||
data := extendTemplateData(w, r, template.Data{})
|
||||
challenge, err := hydr.ConsentChallenge(r)
|
||||
if err != nil {
|
||||
if err == hydra.ErrChallengeNotFound {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
|
||||
if err := tmpl.RenderPage(w, "consent.html.tmpl", data); err != nil {
|
||||
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
|
||||
return
|
||||
}
|
||||
|
||||
panic(errors.Wrap(err, "could not retrieve consent challenge"))
|
||||
}
|
||||
|
||||
res, err := hydr.ConsentRequest(challenge)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve hydra consent response"))
|
||||
}
|
||||
|
||||
if res.Skip {
|
||||
res, err := hydr.AcceptConsentRequest(challenge, &hydra.AcceptConsentRequest{
|
||||
GrantScope: res.RequestedScope,
|
||||
GrantAccessTokenAudience: res.RequestedAccessTokenAudience,
|
||||
})
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not accept hydra consent request"))
|
||||
}
|
||||
|
||||
http.Redirect(w, r, res.RedirectTo, http.StatusTemporaryRedirect)
|
||||
return
|
||||
}
|
||||
|
||||
res2, err := hydr.AcceptConsentRequest(challenge, &hydra.AcceptConsentRequest{
|
||||
GrantScope: res.RequestedScope,
|
||||
GrantAccessTokenAudience: res.RequestedAccessTokenAudience,
|
||||
})
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not accept hydra consent request"))
|
||||
}
|
||||
|
||||
http.Redirect(w, r, res2.RedirectTo, http.StatusTemporaryRedirect)
|
||||
|
||||
// spew.Dump(res)
|
||||
|
||||
// data := extendTemplateData(w, r, template.Data{
|
||||
// csrf.TemplateTag: csrf.TemplateField(r),
|
||||
// "RequestedScope": res.RequestedScope,
|
||||
// "ConsentChallenge": challenge,
|
||||
// })
|
||||
|
||||
// if err := tmpl.RenderPage(w, "consent.html.tmpl", data); err != nil {
|
||||
// panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
|
||||
// }
|
||||
}
|
||||
|
@ -1,20 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
"gitlab.com/wpetit/goweb/service/template"
|
||||
)
|
||||
|
||||
func serveHomePage(w http.ResponseWriter, r *http.Request) {
|
||||
ctn := container.Must(r.Context())
|
||||
tmpl := template.Must(ctn)
|
||||
|
||||
data := extendTemplateData(w, r, template.Data{})
|
||||
|
||||
if err := tmpl.RenderPage(w, "home.html.tmpl", data); err != nil {
|
||||
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
|
||||
}
|
||||
}
|
@ -1,18 +1,14 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/http"
|
||||
netMail "net/mail"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/config"
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/command"
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/hydra"
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/mail"
|
||||
"github.com/gorilla/csrf"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/cqrs"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
"gitlab.com/wpetit/goweb/service/session"
|
||||
"gitlab.com/wpetit/goweb/service/template"
|
||||
@ -39,7 +35,7 @@ func serveLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
if res.Skip {
|
||||
res, err := hydr.RejectRequest(challenge, &hydra.RejectRequest{
|
||||
res, err := hydr.RejectLoginRequest(challenge, &hydra.RejectRequest{
|
||||
Error: "email_not_validated",
|
||||
ErrorDescription: "The email adress could not be verified.",
|
||||
})
|
||||
@ -65,9 +61,10 @@ func serveLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func handleLoginForm(w http.ResponseWriter, r *http.Request) {
|
||||
ctn := container.Must(r.Context())
|
||||
ctx := r.Context()
|
||||
ctn := container.Must(ctx)
|
||||
tmpl := template.Must(ctn)
|
||||
hydr := hydra.Must(ctn)
|
||||
bus := cqrs.Must(ctn)
|
||||
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
@ -113,30 +110,14 @@ func handleLoginForm(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
res, err := hydr.LoginRequest(challenge)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve hydra login response"))
|
||||
cmd := &command.SendConfirmationEmailRequest{
|
||||
Email: email,
|
||||
Challenge: challenge,
|
||||
DefaultScheme: r.URL.Scheme,
|
||||
DefaultAddress: r.Host,
|
||||
}
|
||||
|
||||
spew.Dump(res)
|
||||
|
||||
ml := mail.Must(ctn)
|
||||
conf := config.Must(ctn)
|
||||
|
||||
var buf bytes.Buffer
|
||||
if err := tmpl.Render(&buf, "verification_email.html.tmpl", template.Data{}); err != nil {
|
||||
panic(errors.Wrap(err, "could not render email template"))
|
||||
}
|
||||
|
||||
err = ml.Send(
|
||||
mail.WithSender(conf.SMTP.SenderAddress, conf.SMTP.SenderName),
|
||||
mail.WithRecipients(email),
|
||||
mail.WithSubject(fmt.Sprintf("[Authentification]")),
|
||||
mail.WithBody(mail.ContentTypeHTML, buf.String(), nil),
|
||||
mail.WithAlternativeBody(mail.ContentTypeText, "", nil),
|
||||
)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not send email"))
|
||||
if _, err := bus.Exec(ctx, cmd); err != nil {
|
||||
panic(errors.Wrap(err, "could not execute command"))
|
||||
}
|
||||
|
||||
data := extendTemplateData(w, r, template.Data{})
|
||||
|
@ -1,10 +1,7 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/config"
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/oidc"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/gorilla/csrf"
|
||||
@ -31,20 +28,9 @@ func Mount(r *chi.Mux, config *config.Config) error {
|
||||
r.Post("/login", handleLoginForm)
|
||||
r.Get("/logout", serveLogoutPage)
|
||||
r.Get("/consent", serveConsentPage)
|
||||
r.Get("/verify", handleVerification)
|
||||
})
|
||||
|
||||
if config.TestApp.Enabled {
|
||||
log.Println("test app enabled")
|
||||
|
||||
r.Route("/test", func(r chi.Router) {
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(oidc.Middleware)
|
||||
|
||||
r.Get("/", serveTestAppHomePage)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
notFoundHandler := r.NotFoundHandler()
|
||||
r.Get("/*", static.Dir(config.HTTP.PublicDir, "", notFoundHandler))
|
||||
|
||||
|
@ -1,23 +0,0 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
"gitlab.com/wpetit/goweb/service/template"
|
||||
)
|
||||
|
||||
func serveTestAppHomePage(w http.ResponseWriter, r *http.Request) {
|
||||
ctn := container.Must(r.Context())
|
||||
tmpl := template.Must(ctn)
|
||||
|
||||
data := extendTemplateData(w, r, template.Data{})
|
||||
|
||||
log.Println("rendering test app home")
|
||||
|
||||
if err := tmpl.RenderPage(w, "home.html.tmpl", data); err != nil {
|
||||
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
|
||||
}
|
||||
}
|
55
internal/route/verify.go
Normal file
55
internal/route/verify.go
Normal file
@ -0,0 +1,55 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/hydra"
|
||||
"forge.cadoles.com/wpetit/hydra-passwordless/internal/query"
|
||||
"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)
|
||||
|
||||
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 {
|
||||
logger.Error(ctx, "could not verify token", logger.E(err))
|
||||
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
}
|
||||
|
||||
verifyUserData, ok := result.Data().(*query.VerifyUserData)
|
||||
if !ok {
|
||||
panic(errors.New("unexpected result data"))
|
||||
}
|
||||
|
||||
hydr := hydra.Must(ctn)
|
||||
|
||||
accept := &hydra.AcceptLoginRequest{
|
||||
Subject: verifyUserData.Email,
|
||||
}
|
||||
|
||||
res, err := hydr.AcceptLoginRequest(verifyUserData.Challenge, accept)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve hydra accept response"))
|
||||
}
|
||||
|
||||
http.Redirect(w, r, res.RedirectTo, http.StatusSeeOther)
|
||||
}
|
56
internal/token/generate.go
Normal file
56
internal/token/generate.go
Normal file
@ -0,0 +1,56 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"gopkg.in/square/go-jose.v2"
|
||||
"gopkg.in/square/go-jose.v2/jwt"
|
||||
)
|
||||
|
||||
const (
|
||||
jwtIssuer = "hydra-passwordless"
|
||||
)
|
||||
|
||||
type privateClaims struct {
|
||||
Challenge string `json:"challenge"`
|
||||
}
|
||||
|
||||
func Generate(signingKey, encryptionKey, email, challenge string) (string, error) {
|
||||
sig, err := jose.NewSigner(
|
||||
jose.SigningKey{
|
||||
Algorithm: jose.HS256,
|
||||
Key: []byte(signingKey),
|
||||
},
|
||||
(&jose.SignerOptions{}).WithType("JWT"),
|
||||
)
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "could not create jwt signer")
|
||||
}
|
||||
|
||||
enc, err := jose.NewEncrypter(
|
||||
jose.A256GCM,
|
||||
jose.Recipient{
|
||||
Algorithm: jose.DIRECT,
|
||||
Key: []byte(encryptionKey),
|
||||
},
|
||||
(&jose.EncrypterOptions{}).WithType("JWT").WithContentType("JWT"))
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "could not create jwt encrypter")
|
||||
}
|
||||
|
||||
claims := jwt.Claims{
|
||||
Subject: email,
|
||||
Issuer: jwtIssuer,
|
||||
Audience: jwt.Audience{jwtIssuer},
|
||||
}
|
||||
|
||||
privateClaims := privateClaims{
|
||||
Challenge: challenge,
|
||||
}
|
||||
|
||||
raw, err := jwt.SignedAndEncrypted(sig, enc).Claims(claims).Claims(privateClaims).CompactSerialize()
|
||||
if err != nil {
|
||||
return "", errors.Wrap(err, "could not sign and encrypt jwt")
|
||||
}
|
||||
|
||||
return raw, nil
|
||||
}
|
27
internal/token/verify.go
Normal file
27
internal/token/verify.go
Normal file
@ -0,0 +1,27 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"gopkg.in/square/go-jose.v2/jwt"
|
||||
)
|
||||
|
||||
func Verify(signingKey, encryptionKey, raw string) (string, string, error) {
|
||||
token, err := jwt.ParseSignedAndEncrypted(raw)
|
||||
if err != nil {
|
||||
return "", "", errors.Wrap(err, "could not parse token")
|
||||
}
|
||||
|
||||
nested, err := token.Decrypt([]byte(encryptionKey))
|
||||
if err != nil {
|
||||
return "", "", errors.Wrap(err, "could not decrypt token")
|
||||
}
|
||||
|
||||
baseClaims := jwt.Claims{}
|
||||
privateClaims := privateClaims{}
|
||||
|
||||
if err := nested.Claims([]byte(signingKey), &baseClaims, &privateClaims); err != nil {
|
||||
return "", "", errors.Wrap(err, "could not validate claims")
|
||||
}
|
||||
|
||||
return baseClaims.Subject, privateClaims.Challenge, nil
|
||||
}
|
Reference in New Issue
Block a user