feat: initial commit
This commit is contained in:
52
internal/route/api/create_user.go
Normal file
52
internal/route/api/create_user.go
Normal file
@ -0,0 +1,52 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/storage"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/api"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
)
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username" validate:"required"`
|
||||
Attributes map[string]any `json:"attributes"`
|
||||
}
|
||||
|
||||
type CreateUserResponse struct {
|
||||
User *storage.User `json:"user"`
|
||||
}
|
||||
|
||||
func CreateUser(w http.ResponseWriter, r *http.Request) {
|
||||
createUserReq := &CreateUserRequest{}
|
||||
if ok := api.Bind(w, r, createUserReq); !ok {
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
ctn := container.Must(ctx)
|
||||
storageSrv := storage.Must(ctn)
|
||||
|
||||
user, err := storageSrv.User().CreateUser(ctx, createUserReq.Username, createUserReq.Attributes)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrAlreadyExist) {
|
||||
logger.Warn(ctx, "user already exists", logger.E(errors.WithStack(err)), logger.F("username", createUserReq.Username))
|
||||
api.ErrorResponse(w, http.StatusConflict, ErrCodeAlreadyExist, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
logger.Error(ctx, "could not create user", logger.E(errors.WithStack(err)))
|
||||
api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
response := CreateUserResponse{
|
||||
User: user,
|
||||
}
|
||||
|
||||
api.DataResponse(w, http.StatusCreated, response)
|
||||
}
|
8
internal/route/api/error.go
Normal file
8
internal/route/api/error.go
Normal file
@ -0,0 +1,8 @@
|
||||
package api
|
||||
|
||||
import "gitlab.com/wpetit/goweb/api"
|
||||
|
||||
var (
|
||||
ErrCodeAlreadyExist api.ErrorCode = "already-exist"
|
||||
ErrNotModified api.ErrorCode = "not-modified"
|
||||
)
|
45
internal/route/api/generate_registration_link.go
Normal file
45
internal/route/api/generate_registration_link.go
Normal file
@ -0,0 +1,45 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/storage"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/api"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
)
|
||||
|
||||
type GenerateRegistrationLinkResponse struct {
|
||||
RegistrationLink *storage.RegistrationLink `json:"registrationLink"`
|
||||
}
|
||||
|
||||
func GenerateRegistrationLink(w http.ResponseWriter, r *http.Request) {
|
||||
userID := chi.URLParam(r, "userID")
|
||||
|
||||
ctx := r.Context()
|
||||
ctn := container.Must(ctx)
|
||||
storageSrv := storage.Must(ctn)
|
||||
|
||||
registrationLink, err := storageSrv.User().GenerateRegistrationLink(ctx, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
logger.Warn(ctx, "user not found", logger.E(errors.WithStack(err)), logger.F("userID", userID))
|
||||
api.ErrorResponse(w, http.StatusNotFound, api.ErrCodeNotFound, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
logger.Error(ctx, "could not generate registration link", logger.E(errors.WithStack(err)))
|
||||
api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
response := GenerateRegistrationLinkResponse{
|
||||
RegistrationLink: registrationLink,
|
||||
}
|
||||
|
||||
api.DataResponse(w, http.StatusCreated, response)
|
||||
}
|
45
internal/route/api/get_registration_link.go
Normal file
45
internal/route/api/get_registration_link.go
Normal file
@ -0,0 +1,45 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/storage"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/api"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
)
|
||||
|
||||
type GetRegistrationLinkResponse struct {
|
||||
RegistrationLink *storage.RegistrationLink `json:"registrationLink"`
|
||||
}
|
||||
|
||||
func GetRegistrationLink(w http.ResponseWriter, r *http.Request) {
|
||||
userID := chi.URLParam(r, "userID")
|
||||
|
||||
ctx := r.Context()
|
||||
ctn := container.Must(ctx)
|
||||
storageSrv := storage.Must(ctn)
|
||||
|
||||
registrationLink, err := storageSrv.User().GetRegistrationLink(ctx, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
logger.Warn(ctx, "registration link or associated user not found", logger.E(errors.WithStack(err)), logger.F("userID", userID))
|
||||
api.ErrorResponse(w, http.StatusNotFound, api.ErrCodeNotFound, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
logger.Error(ctx, "could not get registration link", logger.E(errors.WithStack(err)))
|
||||
api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
response := GetRegistrationLinkResponse{
|
||||
RegistrationLink: registrationLink,
|
||||
}
|
||||
|
||||
api.DataResponse(w, http.StatusOK, response)
|
||||
}
|
45
internal/route/api/get_user.go
Normal file
45
internal/route/api/get_user.go
Normal file
@ -0,0 +1,45 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/storage"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/api"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
)
|
||||
|
||||
type GetUserResponse struct {
|
||||
User *storage.User `json:"user"`
|
||||
}
|
||||
|
||||
func GetUser(w http.ResponseWriter, r *http.Request) {
|
||||
userID := chi.URLParam(r, "userID")
|
||||
|
||||
ctx := r.Context()
|
||||
ctn := container.Must(ctx)
|
||||
storageSrv := storage.Must(ctn)
|
||||
|
||||
user, err := storageSrv.User().FindUserByID(ctx, userID)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
logger.Warn(ctx, "could not find user", logger.E(errors.WithStack(err)), logger.F("userID", userID))
|
||||
api.ErrorResponse(w, http.StatusNotFound, api.ErrCodeNotFound, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
logger.Error(ctx, "could not get user", logger.E(errors.WithStack(err)))
|
||||
api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
response := GetUserResponse{
|
||||
User: user,
|
||||
}
|
||||
|
||||
api.DataResponse(w, http.StatusOK, response)
|
||||
}
|
42
internal/route/api/list_users.go
Normal file
42
internal/route/api/list_users.go
Normal file
@ -0,0 +1,42 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/storage"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/api"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
)
|
||||
|
||||
type ListUsersResponse struct {
|
||||
Users []storage.UserHeader `json:"users"`
|
||||
}
|
||||
|
||||
func ListUsers(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
ctn := container.Must(ctx)
|
||||
storageSrv := storage.Must(ctn)
|
||||
|
||||
users, err := storageSrv.User().ListUsers(ctx)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
logger.Warn(ctx, "could not list users", logger.E(errors.WithStack(err)))
|
||||
api.ErrorResponse(w, http.StatusNotFound, api.ErrCodeNotFound, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
logger.Error(ctx, "could not get user", logger.E(errors.WithStack(err)))
|
||||
api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
response := ListUsersResponse{
|
||||
Users: users,
|
||||
}
|
||||
|
||||
api.DataResponse(w, http.StatusOK, response)
|
||||
}
|
33
internal/route/api/mount.go
Normal file
33
internal/route/api/mount.go
Normal file
@ -0,0 +1,33 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/config"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-chi/chi/middleware"
|
||||
)
|
||||
|
||||
func Mount(r *chi.Mux, config *config.Config) error {
|
||||
basicAuth := middleware.BasicAuth("Hydra WebAuthn", toCredentials(config.API.Authentication.Accounts))
|
||||
|
||||
r.Route("/api/v1", func(r chi.Router) {
|
||||
r.Use(basicAuth)
|
||||
r.Post("/users", CreateUser)
|
||||
r.Get("/users/{userID}", GetUser)
|
||||
r.Get("/users", ListUsers)
|
||||
r.Post("/users/{userID}/registration-link", GenerateRegistrationLink)
|
||||
r.Get("/users/{userID}/registration-link", GetRegistrationLink)
|
||||
r.Put("/users/{userID}", UpdateUser)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func toCredentials(accounts []config.AccountConfig) map[string]string {
|
||||
credentials := make(map[string]string, len(accounts))
|
||||
|
||||
for _, acc := range accounts {
|
||||
credentials[acc.Username] = acc.Password
|
||||
}
|
||||
|
||||
return credentials
|
||||
}
|
85
internal/route/api/update_user.go
Normal file
85
internal/route/api/update_user.go
Normal file
@ -0,0 +1,85 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/storage"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/api"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
)
|
||||
|
||||
type UpdateUserRequest struct {
|
||||
Username *string `json:"username"`
|
||||
Attributes *map[string]any `json:"attributes"`
|
||||
}
|
||||
|
||||
type UpdateUserResponse struct {
|
||||
User *storage.User `json:"user"`
|
||||
}
|
||||
|
||||
func UpdateUser(w http.ResponseWriter, r *http.Request) {
|
||||
userID := chi.URLParam(r, "userID")
|
||||
|
||||
updateUserReq := &UpdateUserRequest{}
|
||||
if ok := api.Bind(w, r, updateUserReq); !ok {
|
||||
return
|
||||
}
|
||||
|
||||
ctx := r.Context()
|
||||
ctn := container.Must(ctx)
|
||||
storageSrv := storage.Must(ctn)
|
||||
|
||||
var (
|
||||
user *storage.User
|
||||
err error
|
||||
)
|
||||
|
||||
if updateUserReq.Username != nil {
|
||||
user, err = storageSrv.User().UpdateUserUsername(ctx, userID, *updateUserReq.Username)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
logger.Warn(ctx, "could not find user", logger.E(errors.WithStack(err)), logger.F("userID", userID))
|
||||
api.ErrorResponse(w, http.StatusNotFound, api.ErrCodeNotFound, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
logger.Error(ctx, "could not update username", logger.E(errors.WithStack(err)))
|
||||
api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if updateUserReq.Attributes != nil {
|
||||
user, err = storageSrv.User().UpdateUserAttributes(ctx, userID, *updateUserReq.Attributes)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
logger.Warn(ctx, "could not find user", logger.E(errors.WithStack(err)), logger.F("userID", userID))
|
||||
api.ErrorResponse(w, http.StatusNotFound, api.ErrCodeNotFound, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
logger.Error(ctx, "could not update attributes", logger.E(errors.WithStack(err)), logger.F("userID", userID))
|
||||
api.ErrorResponse(w, http.StatusInternalServerError, api.ErrCodeUnknownError, nil)
|
||||
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if user == nil {
|
||||
api.ErrorResponse(w, http.StatusBadRequest, ErrNotModified, nil)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
response := UpdateUserResponse{
|
||||
User: user,
|
||||
}
|
||||
|
||||
api.DataResponse(w, http.StatusOK, response)
|
||||
}
|
58
internal/route/common/helper.go
Normal file
58
internal/route/common/helper.go
Normal file
@ -0,0 +1,58 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/config"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
"gitlab.com/wpetit/goweb/service"
|
||||
"gitlab.com/wpetit/goweb/service/template"
|
||||
"gitlab.com/wpetit/goweb/template/html"
|
||||
)
|
||||
|
||||
func ExtendTemplateData(w http.ResponseWriter, r *http.Request, data template.Data) template.Data {
|
||||
ctn := container.Must(r.Context())
|
||||
data, err := template.Extend(data,
|
||||
html.WithFlashes(w, r, ctn),
|
||||
template.WithBuildInfo(w, r, ctn),
|
||||
withBaseURL(w, r, ctn),
|
||||
)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not extend template data"))
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
func withBaseURL(w http.ResponseWriter, r *http.Request, ctn *service.Container) template.DataExtFunc {
|
||||
return func(data template.Data) (template.Data, error) {
|
||||
conf, err := config.From(ctn)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
data["BaseURL"] = strings.TrimSuffix(conf.HTTP.BaseURL, "/")
|
||||
|
||||
return data, nil
|
||||
}
|
||||
}
|
||||
|
||||
func RenderErrorPage(w http.ResponseWriter, r *http.Request, statusCode int, title, description string) error {
|
||||
ctn := container.Must(r.Context())
|
||||
tmpl := template.Must(ctn)
|
||||
|
||||
data := ExtendTemplateData(w, r, template.Data{
|
||||
"ErrorTitle": title,
|
||||
"ErrorDescription": description,
|
||||
})
|
||||
|
||||
w.WriteHeader(statusCode)
|
||||
|
||||
if err := tmpl.RenderPage(w, "error.html.tmpl", data); err != nil {
|
||||
return errors.Wrap(err, "could not render error page")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
21
internal/route/home.go
Normal file
21
internal/route/home.go
Normal file
@ -0,0 +1,21 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/route/common"
|
||||
"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 := common.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))
|
||||
}
|
||||
}
|
50
internal/route/hydra/consent.go
Normal file
50
internal/route/hydra/consent.go
Normal file
@ -0,0 +1,50 @@
|
||||
package hydra
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/hydra"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
)
|
||||
|
||||
func serveConsentPage(w http.ResponseWriter, r *http.Request) {
|
||||
ctn := container.Must(r.Context())
|
||||
hydr := hydra.Must(ctn)
|
||||
|
||||
challenge, err := hydr.ConsentChallenge(r)
|
||||
if err != nil {
|
||||
if err == hydra.ErrChallengeNotFound {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
panic(errors.Wrap(err, "could not retrieve consent challenge"))
|
||||
}
|
||||
|
||||
consentRes, err := hydr.ConsentRequest(challenge)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve hydra consent response"))
|
||||
}
|
||||
|
||||
userAttributes, ok := consentRes.Context["userAttributes"].(map[string]any)
|
||||
if !ok {
|
||||
userAttributes = make(map[string]any)
|
||||
}
|
||||
|
||||
acceptConsentReq := &hydra.AcceptConsentRequest{
|
||||
GrantScope: consentRes.RequestedScope,
|
||||
GrantAccessTokenAudience: consentRes.RequestedAccessTokenAudience,
|
||||
Session: hydra.AcceptConsentSession{
|
||||
IDToken: userAttributes,
|
||||
},
|
||||
}
|
||||
|
||||
acceptRes, err := hydr.AcceptConsentRequest(challenge, acceptConsentReq)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not accept hydra consent request"))
|
||||
}
|
||||
|
||||
http.Redirect(w, r, acceptRes.RedirectTo, http.StatusTemporaryRedirect)
|
||||
}
|
272
internal/route/hydra/login.go
Normal file
272
internal/route/hydra/login.go
Normal file
@ -0,0 +1,272 @@
|
||||
package hydra
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/gob"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/config"
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/hydra"
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/route/common"
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/storage"
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/webauthn"
|
||||
"github.com/getsentry/sentry-go"
|
||||
"github.com/go-webauthn/webauthn/protocol"
|
||||
"github.com/gorilla/csrf"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
"gitlab.com/wpetit/goweb/service/session"
|
||||
"gitlab.com/wpetit/goweb/service/template"
|
||||
)
|
||||
|
||||
func init() {
|
||||
gob.Register(&webauthn.SessionData{})
|
||||
}
|
||||
|
||||
func serveLoginPage(w http.ResponseWriter, r *http.Request) {
|
||||
ctn := container.Must(r.Context())
|
||||
hydr := hydra.Must(ctn)
|
||||
|
||||
challenge, err := hydr.LoginChallenge(r)
|
||||
if err != nil {
|
||||
if errors.Is(err, hydra.ErrChallengeNotFound) {
|
||||
err := common.RenderErrorPage(
|
||||
w, r,
|
||||
http.StatusBadRequest,
|
||||
"Requête invalide",
|
||||
"Certaines informations requises afin de réaliser votre requête sont absentes.",
|
||||
)
|
||||
if err != nil {
|
||||
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
panic(errors.Wrap(err, "could not retrieve login challenge"))
|
||||
}
|
||||
|
||||
res, err := hydr.LoginRequest(challenge)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve hydra login response"))
|
||||
}
|
||||
|
||||
if res.Skip {
|
||||
accept := &hydra.AcceptLoginRequest{
|
||||
Subject: res.Subject,
|
||||
Context: map[string]interface{}{
|
||||
"username": res.Subject,
|
||||
},
|
||||
}
|
||||
|
||||
res, err := hydr.AcceptLoginRequest(challenge, accept)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve hydra accept response"))
|
||||
}
|
||||
|
||||
http.Redirect(w, r, res.RedirectTo, http.StatusSeeOther)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
tmpl := template.Must(ctn)
|
||||
|
||||
data := common.ExtendTemplateData(w, r, template.Data{
|
||||
csrf.TemplateTag: csrf.TemplateField(r),
|
||||
"LoginChallenge": challenge,
|
||||
"ClientName": res.Client.ClientName,
|
||||
"ClientURI": res.Client.ClientURI,
|
||||
"Username": "",
|
||||
"RememberMe": "",
|
||||
"CredentialAssertion": nil,
|
||||
})
|
||||
|
||||
if err := tmpl.RenderPage(w, "login.html.tmpl", data); err != nil {
|
||||
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
|
||||
}
|
||||
}
|
||||
|
||||
func handleLoginForm(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
ctn := container.Must(ctx)
|
||||
tmpl := template.Must(ctn)
|
||||
hydr := hydra.Must(ctn)
|
||||
strg := storage.Must(ctn)
|
||||
conf := config.Must(ctn)
|
||||
wbth := webauthn.Must(ctn)
|
||||
sesn := session.Must(ctn)
|
||||
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
challenge := r.Form.Get("challenge")
|
||||
|
||||
if challenge == "" {
|
||||
err := common.RenderErrorPage(
|
||||
w, r,
|
||||
http.StatusBadRequest,
|
||||
"Requête invalide",
|
||||
"Certaines informations requises sont manquantes pour pouvoir réaliser votre requête.",
|
||||
)
|
||||
if err != nil {
|
||||
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
res, err := hydr.LoginRequest(challenge)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve hydra login response"))
|
||||
}
|
||||
|
||||
username := r.Form.Get("username")
|
||||
rememberMe := r.Form.Get("rememberme") == "on"
|
||||
|
||||
renderPage := func(assertionRequest *protocol.CredentialAssertion) {
|
||||
data := common.ExtendTemplateData(w, r, template.Data{
|
||||
csrf.TemplateTag: csrf.TemplateField(r),
|
||||
"LoginChallenge": challenge,
|
||||
"Username": username,
|
||||
"RememberMe": rememberMe,
|
||||
"AssertionRequest": assertionRequest,
|
||||
"ClientName": res.Client.ClientName,
|
||||
"ClientURI": res.Client.ClientURI,
|
||||
})
|
||||
|
||||
if err := tmpl.RenderPage(w, "login.html.tmpl", data); err != nil {
|
||||
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
|
||||
}
|
||||
}
|
||||
|
||||
sess, err := sesn.Get(w, r)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve session"))
|
||||
}
|
||||
|
||||
renderFlashError := func(message string) {
|
||||
sess.AddFlash(session.FlashError, message)
|
||||
|
||||
if err := sess.Save(w, r); err != nil {
|
||||
panic(errors.Wrap(err, "could not save session"))
|
||||
}
|
||||
|
||||
renderPage(nil)
|
||||
}
|
||||
|
||||
user, err := strg.User().FindUserByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
renderFlashError("Impossible de trouver un compte associé à ce nom d'utilisateur.")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
panic(errors.Wrap(err, "could not find user"))
|
||||
}
|
||||
|
||||
if !r.Form.Has("assertion") {
|
||||
if len(user.WebAuthnCredentials()) == 0 {
|
||||
renderFlashError("Aucune clé n'est encore associée à ce compte. Contactez votre administrateur.")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
assertionRequest, webAuthnSessionData, err := wbth.BeginLogin(user)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not begin webauthn login"))
|
||||
}
|
||||
|
||||
sess.Set("webauthn", webAuthnSessionData)
|
||||
|
||||
if err := sess.Save(w, r); err != nil {
|
||||
panic(errors.Wrap(err, "could not save session"))
|
||||
}
|
||||
|
||||
renderPage(assertionRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
webAuthnSessionData, ok := sess.Get("webauthn").(*webauthn.SessionData)
|
||||
if !ok {
|
||||
panic(errors.New("could not retrieve webauthn session data"))
|
||||
}
|
||||
|
||||
base64Assertion := r.Form.Get("assertion")
|
||||
if base64Assertion == "" {
|
||||
renderFlashError("Authentification échouée.")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rawAssertion, err := base64.RawURLEncoding.DecodeString(base64Assertion)
|
||||
if err != nil {
|
||||
logger.Error(ctx, "could not parse base64 encoded assertion", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var car protocol.CredentialAssertionResponse
|
||||
if err := json.Unmarshal(rawAssertion, &car); err != nil {
|
||||
logger.Error(ctx, "could not parse credential assertion response", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
parsedResponse, err := car.Parse()
|
||||
if err != nil {
|
||||
logger.Error(ctx, "could not parse credential assertion response", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := wbth.ValidateLogin(user, *webAuthnSessionData, parsedResponse); err != nil {
|
||||
logger.Error(ctx, "could not authenticate user", logger.E(errors.WithStack(err)))
|
||||
renderFlashError("Authentification échouée.")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
rememberFor := conf.Session.DefaultDuration
|
||||
if rememberMe {
|
||||
rememberFor = conf.Session.RememberMeDuration
|
||||
}
|
||||
|
||||
accept := &hydra.AcceptLoginRequest{
|
||||
Subject: user.Username,
|
||||
Remember: rememberMe,
|
||||
RememberFor: rememberFor,
|
||||
Context: map[string]any{
|
||||
"userAttributes": user.Attributes,
|
||||
},
|
||||
}
|
||||
|
||||
loginRes, err := hydr.AcceptLoginRequest(challenge, accept)
|
||||
if err != nil {
|
||||
sentry.CaptureException(err)
|
||||
logger.Error(ctx, "could not retrieve hydra accept response", logger.E(err))
|
||||
|
||||
err := common.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, loginRes.RedirectTo, http.StatusSeeOther)
|
||||
}
|
47
internal/route/hydra/logout.go
Normal file
47
internal/route/hydra/logout.go
Normal file
@ -0,0 +1,47 @@
|
||||
package hydra
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/hydra"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
"gitlab.com/wpetit/goweb/service/session"
|
||||
)
|
||||
|
||||
func serveLogoutPage(w http.ResponseWriter, r *http.Request) {
|
||||
ctn := container.Must(r.Context())
|
||||
hydr := hydra.Must(ctn)
|
||||
|
||||
challenge, err := hydr.LogoutChallenge(r)
|
||||
if err != nil {
|
||||
if errors.Is(err, hydra.ErrChallengeNotFound) {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
panic(errors.Wrap(err, "could not retrieve logout challenge"))
|
||||
}
|
||||
|
||||
_, err = hydr.LogoutRequest(challenge)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve hydra logout response"))
|
||||
}
|
||||
|
||||
acceptRes, err := hydr.AcceptLogoutRequest(challenge)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve hydra accept logout response"))
|
||||
}
|
||||
|
||||
sess, err := session.Must(ctn).Get(w, r)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve session"))
|
||||
}
|
||||
|
||||
if err := sess.Delete(w, r); err != nil {
|
||||
panic(errors.Wrap(err, "could not delete session"))
|
||||
}
|
||||
|
||||
http.Redirect(w, r, acceptRes.RedirectTo, http.StatusSeeOther)
|
||||
}
|
34
internal/route/hydra/mount.go
Normal file
34
internal/route/hydra/mount.go
Normal file
@ -0,0 +1,34 @@
|
||||
package hydra
|
||||
|
||||
import (
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/config"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/gorilla/csrf"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/session/gorilla"
|
||||
)
|
||||
|
||||
func Mount(r *chi.Mux, config *config.Config) error {
|
||||
csrfSecret, err := gorilla.GenerateRandomBytes(32)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not generate CSRF secret")
|
||||
}
|
||||
|
||||
csrfMiddleware := csrf.Protect(
|
||||
csrfSecret,
|
||||
csrf.Secure(false),
|
||||
)
|
||||
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(csrfMiddleware)
|
||||
r.Get("/login", serveLoginPage)
|
||||
r.Post("/login", handleLoginForm)
|
||||
r.Get("/logout", serveLogoutPage)
|
||||
r.Get("/consent", serveConsentPage)
|
||||
r.Get("/register/{token}", serveRegisterPage)
|
||||
r.Post("/register/{token}", handleRegisterForm)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
171
internal/route/hydra/register.go
Normal file
171
internal/route/hydra/register.go
Normal file
@ -0,0 +1,171 @@
|
||||
package hydra
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/route/common"
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/storage"
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/webauthn"
|
||||
"github.com/go-chi/chi"
|
||||
"github.com/go-webauthn/webauthn/protocol"
|
||||
"github.com/gorilla/csrf"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
"gitlab.com/wpetit/goweb/middleware/container"
|
||||
"gitlab.com/wpetit/goweb/service/session"
|
||||
"gitlab.com/wpetit/goweb/service/template"
|
||||
)
|
||||
|
||||
func serveRegisterPage(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
ctn := container.Must(ctx)
|
||||
tmpl := template.Must(ctn)
|
||||
webAuthn := webauthn.Must(ctn)
|
||||
session := session.Must(ctn)
|
||||
storageSrv := storage.Must(ctn)
|
||||
|
||||
token := chi.URLParam(r, "token")
|
||||
registrationLink, err := storageSrv.User().GetRegistrationLinkByToken(ctx, token)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
logger.Warn(ctx, "registration link not found", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
panic(errors.Wrap(err, "could not retrieve registration link"))
|
||||
}
|
||||
|
||||
user, err := storageSrv.User().FindUserByID(ctx, registrationLink.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
logger.Warn(ctx, "user not found", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
panic(errors.Wrap(err, "could not retrieve user"))
|
||||
}
|
||||
|
||||
webAuthnOptions, webAuthnSessionData, err := webAuthn.BeginRegistration(user)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not begin discoverable login"))
|
||||
}
|
||||
|
||||
sess, err := session.Get(w, r)
|
||||
if err != nil {
|
||||
panic(errors.Wrap(err, "could not retrieve session"))
|
||||
}
|
||||
|
||||
sess.Set("webauthn", webAuthnSessionData)
|
||||
|
||||
if err := sess.Save(w, r); err != nil {
|
||||
panic(errors.Wrap(err, "could not save session"))
|
||||
}
|
||||
|
||||
data := common.ExtendTemplateData(w, r, template.Data{
|
||||
csrf.TemplateTag: csrf.TemplateField(r),
|
||||
"WebAuthnOptions": webAuthnOptions,
|
||||
"Token": registrationLink.Token,
|
||||
})
|
||||
|
||||
if err := tmpl.RenderPage(w, "register.html.tmpl", data); err != nil {
|
||||
panic(errors.Wrapf(err, "could not render '%s' page", r.URL.Path))
|
||||
}
|
||||
}
|
||||
|
||||
func handleRegisterForm(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
serviceContainer := container.Must(ctx)
|
||||
webAuthnService := webauthn.Must(serviceContainer)
|
||||
sessionService := session.Must(serviceContainer)
|
||||
storageSrv := storage.Must(serviceContainer)
|
||||
|
||||
token := chi.URLParam(r, "token")
|
||||
registrationLink, err := storageSrv.User().GetRegistrationLinkByToken(ctx, token)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
logger.Warn(ctx, "registration link not found", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
panic(errors.Wrap(err, "could not retrieve registration link"))
|
||||
}
|
||||
|
||||
user, err := storageSrv.User().FindUserByID(ctx, registrationLink.UserID)
|
||||
if err != nil {
|
||||
if errors.Is(err, storage.ErrNotFound) {
|
||||
logger.Warn(ctx, "user not found", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
panic(errors.Wrap(err, "could not retrieve user"))
|
||||
}
|
||||
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
base64Credentials := r.Form.Get("credentials")
|
||||
|
||||
rawCredentials, err := base64.RawURLEncoding.DecodeString(base64Credentials)
|
||||
if err != nil {
|
||||
logger.Error(ctx, "could not parse base64 encoded credentials", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
var ccr protocol.CredentialCreationResponse
|
||||
if err := json.Unmarshal(rawCredentials, &ccr); err != nil {
|
||||
logger.Error(ctx, "could not parse credential creation response", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
parsedResponse, err := ccr.Parse()
|
||||
if err != nil {
|
||||
logger.Error(ctx, "could not parse credential creation response", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
sess, err := sessionService.Get(w, r)
|
||||
if err != nil {
|
||||
logger.Error(ctx, "could not retrieve session", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
webAuthnSessionData := sess.Get("webauthn").(*webauthn.SessionData)
|
||||
|
||||
credential, err := webAuthnService.CreateCredential(user, *webAuthnSessionData, parsedResponse)
|
||||
if err != nil {
|
||||
logger.Error(ctx, "could not create user credential", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := storageSrv.User().AddUserCredential(ctx, user.ID, credential); err != nil {
|
||||
logger.Error(ctx, "could not add credential", logger.E(errors.WithStack(err)))
|
||||
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
http.Redirect(w, r, "/registered", http.StatusSeeOther)
|
||||
}
|
22
internal/route/mount.go
Normal file
22
internal/route/mount.go
Normal file
@ -0,0 +1,22 @@
|
||||
package route
|
||||
|
||||
import (
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/config"
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/route/api"
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/route/hydra"
|
||||
|
||||
"github.com/go-chi/chi"
|
||||
"gitlab.com/wpetit/goweb/static"
|
||||
)
|
||||
|
||||
func Mount(r *chi.Mux, config *config.Config) error {
|
||||
|
||||
r.Get("/", serveHomePage)
|
||||
hydra.Mount(r, config)
|
||||
api.Mount(r, config)
|
||||
|
||||
notFoundHandler := r.NotFoundHandler()
|
||||
r.Get("/*", static.Dir(config.HTTP.PublicDir, "", notFoundHandler))
|
||||
|
||||
return nil
|
||||
}
|
Reference in New Issue
Block a user