feat: initial commit
This commit is contained in:
48
internal/config/api.go
Normal file
48
internal/config/api.go
Normal file
@ -0,0 +1,48 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/davecgh/go-spew/spew"
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type APIConfig struct {
|
||||
Authentication AuthenticationConfig `yaml:"auth" envPrefix:"AUTH_"`
|
||||
}
|
||||
|
||||
type Accounts []AccountConfig
|
||||
|
||||
type AuthenticationConfig struct {
|
||||
Accounts Accounts `yaml:"accounts" env:"ACCOUNTS"`
|
||||
}
|
||||
|
||||
func parseAccounts(value string) (any, error) {
|
||||
var accounts Accounts
|
||||
|
||||
spew.Dump(value)
|
||||
|
||||
if err := json.Unmarshal([]byte(value), &accounts); err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
type AccountConfig struct {
|
||||
Username string `yaml:"username" json:"username"`
|
||||
Password string `yaml:"password" json:"password"`
|
||||
}
|
||||
|
||||
func NewDefaultAPIConfig() APIConfig {
|
||||
return APIConfig{
|
||||
Authentication: AuthenticationConfig{
|
||||
Accounts: []AccountConfig{
|
||||
{
|
||||
Username: "admin",
|
||||
Password: "webauthn",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
128
internal/config/config.go
Normal file
128
internal/config/config.go
Normal file
@ -0,0 +1,128 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"reflect"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
|
||||
"github.com/caarlos0/env/v10"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Debug bool `yaml:"debug" env:"DEBUG"`
|
||||
HTTP HTTPConfig `yaml:"http" envPrefix:"HTTP_"`
|
||||
Hydra HydraConfig `yaml:"hydra" envPrefix:"HYDRA_"`
|
||||
Session SessionConfig `yaml:"session" envPrefix:"SESSION_"`
|
||||
Sentry SentryConfig `yaml:"sentry" envPrefix:"SENTRY_"`
|
||||
WebAuthn WebAuthnConfig `yaml:"webauthn" envPrefix:"WEBAUTHN_"`
|
||||
API APIConfig `yaml:"api" envPrefix:"API_"`
|
||||
Storage StorageConfig `yaml:"storage" envPrefix:"STORAGE_"`
|
||||
}
|
||||
|
||||
// NewFromFile retrieves the configuration from the given file
|
||||
func NewFromFile(filepath string) (*Config, error) {
|
||||
config := NewDefault()
|
||||
|
||||
data, err := os.ReadFile(filepath)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "could not read file '%s'", filepath)
|
||||
}
|
||||
|
||||
if err := yaml.Unmarshal(data, config); err != nil {
|
||||
return nil, errors.Wrapf(err, "could not unmarshal configuration")
|
||||
}
|
||||
|
||||
return config, nil
|
||||
}
|
||||
|
||||
type HydraConfig struct {
|
||||
BaseURL string `yaml:"baseURL" env:"BASE_URL"`
|
||||
// Fake upstream SSL termination adding the "X-Forwarded-Proto: https" to the OIDC client
|
||||
// HTTP request headers.
|
||||
// Required by ory/hydra in some networks topologies
|
||||
FakeSSLTermination bool `yaml:"fakeSSLTermination" env:"FAKE_SSL_TERMINATION"`
|
||||
HTTPClientTimeout time.Duration `yaml:"httpClientTimeout" env:"HTTP_CLIENT_TIMEOUT"`
|
||||
}
|
||||
|
||||
type SessionConfig struct {
|
||||
DefaultDuration int `yaml:"defaultDuration" env:"DEFAULT_DURATION"`
|
||||
RememberMeDuration int `yaml:"rememberMeDuration" env:"REMEMBER_ME_DURATION"`
|
||||
}
|
||||
|
||||
type SentryConfig struct {
|
||||
DSN string `yaml:"dsn" env:"DSN"`
|
||||
// Server events sampling rate, see https://docs.sentry.io/platforms/go/configuration/options/
|
||||
ServerSampleRate float64 `yaml:"serverSampleRate" env:"SERVER_SAMPLE_RATE"`
|
||||
ServerFlushTimeout time.Duration `yaml:"serverFlushTimeout" env:"SERVER_FLUSH_TIMEOUT"`
|
||||
Environment string `yaml:"environment" env:"ENVIRONMENT"`
|
||||
}
|
||||
|
||||
func NewDumpDefault() *Config {
|
||||
config := NewDefault()
|
||||
return config
|
||||
}
|
||||
|
||||
func NewDefault() *Config {
|
||||
return &Config{
|
||||
Debug: false,
|
||||
HTTP: HTTPConfig{
|
||||
Address: ":3000",
|
||||
CookieAuthenticationKey: "",
|
||||
CookieEncryptionKey: "",
|
||||
TokenEncryptionKey: "",
|
||||
TokenSigningKey: "",
|
||||
CookieMaxAge: int((time.Hour * 1).Seconds()), // 1 hour
|
||||
TemplateDir: "template",
|
||||
PublicDir: "public",
|
||||
BaseURL: "/",
|
||||
},
|
||||
Hydra: HydraConfig{
|
||||
BaseURL: "http://localhost:4445/",
|
||||
FakeSSLTermination: false,
|
||||
HTTPClientTimeout: time.Second * 30, //nolint: gomnb
|
||||
},
|
||||
Session: SessionConfig{
|
||||
DefaultDuration: int((time.Hour * 1).Seconds()), // 1 hour
|
||||
RememberMeDuration: int((time.Hour * 24 * 30).Seconds()), // 30 days
|
||||
},
|
||||
Sentry: SentryConfig{
|
||||
DSN: "",
|
||||
ServerSampleRate: 1,
|
||||
ServerFlushTimeout: 2 * time.Second,
|
||||
Environment: "",
|
||||
},
|
||||
WebAuthn: NewDefaultWebAuthnConfig(),
|
||||
API: NewDefaultAPIConfig(),
|
||||
Storage: NewDefaultStorageConfig(),
|
||||
}
|
||||
}
|
||||
|
||||
func Dump(config *Config, w io.Writer) error {
|
||||
data, err := yaml.Marshal(config)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not dump config")
|
||||
}
|
||||
|
||||
if _, err := w.Write(data); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func WithEnvironment(conf *Config) error {
|
||||
if err := env.ParseWithOptions(conf, env.Options{
|
||||
Prefix: "HYDRA_WEBAUTHN_",
|
||||
FuncMap: map[reflect.Type]env.ParserFunc{
|
||||
reflect.TypeOf(Accounts{}): parseAccounts,
|
||||
},
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
13
internal/config/http.go
Normal file
13
internal/config/http.go
Normal file
@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
type HTTPConfig struct {
|
||||
Address string `yaml:"address" env:"ADDRESS"`
|
||||
CookieAuthenticationKey string `yaml:"cookieAuthenticationKey" env:"COOKIE_AUTHENTICATION_KEY"`
|
||||
CookieEncryptionKey string `yaml:"cookieEncryptionKey" env:"COOKIE_ENCRYPTION_KEY"`
|
||||
TokenSigningKey string `yaml:"tokenSigningKey" env:"TOKEN_SIGNING_KEY"`
|
||||
TokenEncryptionKey string `yaml:"tokenEncryptionKey" env:"TOKEN_ENCRYPTION_KEY"`
|
||||
BaseURL string `yaml:"basePublicUrl" env:"BASE_URL"`
|
||||
CookieMaxAge int `yaml:"cookieMaxAge" env:"COOKIE_MAX_AGE"`
|
||||
TemplateDir string `yaml:"templateDir" env:"TEMPLATE_DIR"`
|
||||
PublicDir string `yaml:"publicDir" env:"PUBLIC_DIR"`
|
||||
}
|
9
internal/config/provider.go
Normal file
9
internal/config/provider.go
Normal file
@ -0,0 +1,9 @@
|
||||
package config
|
||||
|
||||
import "gitlab.com/wpetit/goweb/service"
|
||||
|
||||
func ServiceProvider(config *Config) service.Provider {
|
||||
return func(ctn *service.Container) (interface{}, error) {
|
||||
return config, nil
|
||||
}
|
||||
}
|
33
internal/config/service.go
Normal file
33
internal/config/service.go
Normal file
@ -0,0 +1,33 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/service"
|
||||
)
|
||||
|
||||
const ServiceName service.Name = "config"
|
||||
|
||||
// From retrieves the config service in the given container
|
||||
func From(container *service.Container) (*Config, error) {
|
||||
service, err := container.Service(ServiceName)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
|
||||
}
|
||||
|
||||
srv, ok := service.(*Config)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
|
||||
}
|
||||
|
||||
return srv, nil
|
||||
}
|
||||
|
||||
// Must retrieves the config service in the given container or panic otherwise
|
||||
func Must(container *service.Container) *Config {
|
||||
srv, err := From(container)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return srv
|
||||
}
|
13
internal/config/storage.go
Normal file
13
internal/config/storage.go
Normal file
@ -0,0 +1,13 @@
|
||||
package config
|
||||
|
||||
type StorageConfig struct {
|
||||
Driver string `yaml:"driver" env:"DRIVER"`
|
||||
DSN string `yaml:"dsn" env:"DSN"`
|
||||
}
|
||||
|
||||
func NewDefaultStorageConfig() StorageConfig {
|
||||
return StorageConfig{
|
||||
Driver: "sqlite",
|
||||
DSN: "./data/storage.sqlite?mode=rw&_pragma=foreign_keys(1)&_pragma=busy_timeout=150000&_pragma=journal_mode=WAL",
|
||||
}
|
||||
}
|
21
internal/config/webauthn.go
Normal file
21
internal/config/webauthn.go
Normal file
@ -0,0 +1,21 @@
|
||||
package config
|
||||
|
||||
type WebAuthnConfig struct {
|
||||
RelyingParty WebAuthnRelyingPartyConfig `yaml:"relyingParty" envPrefix:"RELYINGPARTY_"`
|
||||
}
|
||||
|
||||
type WebAuthnRelyingPartyConfig struct {
|
||||
ID string `yaml:"id" env:"ID"`
|
||||
DisplayName string `yaml:"displayName" env:"DISPLAYNAME"`
|
||||
Origins []string `yaml:"origins" env:"ORIGINS" envSeparator:","`
|
||||
}
|
||||
|
||||
func NewDefaultWebAuthnConfig() WebAuthnConfig {
|
||||
return WebAuthnConfig{
|
||||
RelyingParty: WebAuthnRelyingPartyConfig{
|
||||
ID: "localhost",
|
||||
DisplayName: "WebAuthn",
|
||||
Origins: []string{"http://localhost:3000"},
|
||||
},
|
||||
}
|
||||
}
|
263
internal/hydra/client.go
Normal file
263
internal/hydra/client.go
Normal file
@ -0,0 +1,263 @@
|
||||
package hydra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
)
|
||||
|
||||
type Client struct {
|
||||
baseURL *url.URL
|
||||
http *http.Client
|
||||
}
|
||||
|
||||
func (c *Client) LoginRequest(challenge string) (*LoginResponse, error) {
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/login", url.Values{
|
||||
"login_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)
|
||||
loginRes := &LoginResponse{}
|
||||
|
||||
if err := decoder.Decode(loginRes); err != nil {
|
||||
return nil, errors.Wrap(err, "could not decode json response")
|
||||
}
|
||||
|
||||
return loginRes, nil
|
||||
}
|
||||
|
||||
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},
|
||||
})
|
||||
|
||||
res := &AcceptResponse{}
|
||||
|
||||
if err := c.putJSON(u, req, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
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},
|
||||
})
|
||||
|
||||
res := &RejectResponse{}
|
||||
|
||||
if err := c.putJSON(u, req, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (c *Client) LogoutRequest(challenge string) (*LogoutResponse, error) {
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/logout", url.Values{
|
||||
"logout_challenge": []string{challenge},
|
||||
})
|
||||
|
||||
res, err := c.http.Get(u)
|
||||
if err != nil {
|
||||
return nil, errors.Wrap(err, "could not retrieve logout 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)
|
||||
logoutRes := &LogoutResponse{}
|
||||
|
||||
if err := decoder.Decode(logoutRes); err != nil {
|
||||
return nil, errors.Wrap(err, "could not decode json response")
|
||||
}
|
||||
|
||||
return logoutRes, nil
|
||||
}
|
||||
|
||||
func (c *Client) AcceptLogoutRequest(challenge string) (*AcceptResponse, error) {
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/logout/accept", url.Values{
|
||||
"logout_challenge": []string{challenge},
|
||||
})
|
||||
|
||||
res := &AcceptResponse{}
|
||||
|
||||
if err := c.putJSON(u, nil, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (c *Client) RejectLogoutRequest(challenge string, req *RejectRequest) (*RejectResponse, error) {
|
||||
u := fromURL(*c.baseURL, "/oauth2/auth/requests/logout/reject", url.Values{
|
||||
"logout_challenge": []string{challenge},
|
||||
})
|
||||
|
||||
res := &RejectResponse{}
|
||||
|
||||
if err := c.putJSON(u, req, res); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func (c *Client) ConsentRequest(challenge string) (*ConsentResponse, error) {
|
||||
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) {
|
||||
return c.challenge(r, "login_challenge")
|
||||
}
|
||||
|
||||
func (c *Client) ConsentChallenge(r *http.Request) (string, error) {
|
||||
return c.challenge(r, "consent_challenge")
|
||||
}
|
||||
|
||||
func (c *Client) LogoutChallenge(r *http.Request) (string, error) {
|
||||
return c.challenge(r, "logout_challenge")
|
||||
}
|
||||
|
||||
func (c *Client) challenge(r *http.Request, name string) (string, error) {
|
||||
challenge := r.URL.Query().Get(name)
|
||||
if challenge == "" {
|
||||
return "", ErrChallengeNotFound
|
||||
}
|
||||
|
||||
return challenge, nil
|
||||
}
|
||||
|
||||
func (c *Client) putJSON(u string, payload interface{}, result interface{}) error {
|
||||
var buf bytes.Buffer
|
||||
|
||||
encoder := json.NewEncoder(&buf)
|
||||
if err := encoder.Encode(payload); err != nil {
|
||||
return errors.Wrap(err, "could not encode request body")
|
||||
}
|
||||
|
||||
req, err := http.NewRequest("PUT", u, &buf)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not create request")
|
||||
}
|
||||
|
||||
res, err := c.http.Do(req)
|
||||
if err != nil {
|
||||
return errors.Wrap(err, "could not retrieve login response")
|
||||
}
|
||||
|
||||
if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusBadRequest {
|
||||
return errors.Wrapf(ErrUnexpectedHydraResponse, "hydra responded with status code '%d'", res.StatusCode)
|
||||
}
|
||||
|
||||
defer res.Body.Close()
|
||||
|
||||
decoder := json.NewDecoder(res.Body)
|
||||
|
||||
if err := decoder.Decode(result); err != nil {
|
||||
return errors.Wrap(err, "could not decode json response")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func fromURL(url url.URL, path string, query url.Values) string {
|
||||
url.Path = path
|
||||
url.RawQuery = query.Encode()
|
||||
|
||||
return url.String()
|
||||
}
|
||||
|
||||
type fakeSSLTerminationTransport struct {
|
||||
T http.RoundTripper
|
||||
}
|
||||
|
||||
func (t *fakeSSLTerminationTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
req.Header.Add("X-Forwarded-Proto", "https")
|
||||
return t.T.RoundTrip(req)
|
||||
}
|
||||
|
||||
func NewClient(baseURL *url.URL, fakeSSLTermination bool, httpTimeout time.Duration) *Client {
|
||||
httpClient := &http.Client{
|
||||
Timeout: httpTimeout,
|
||||
}
|
||||
|
||||
if fakeSSLTermination {
|
||||
httpClient.Transport = &fakeSSLTerminationTransport{http.DefaultTransport}
|
||||
}
|
||||
|
||||
return &Client{
|
||||
baseURL: baseURL,
|
||||
http: httpClient,
|
||||
}
|
||||
}
|
8
internal/hydra/error.go
Normal file
8
internal/hydra/error.go
Normal file
@ -0,0 +1,8 @@
|
||||
package hydra
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrUnexpectedHydraResponse = errors.New("unexpected hydra response")
|
||||
ErrChallengeNotFound = errors.New("challenge not found")
|
||||
)
|
30
internal/hydra/provider.go
Normal file
30
internal/hydra/provider.go
Normal file
@ -0,0 +1,30 @@
|
||||
package hydra
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/service"
|
||||
)
|
||||
|
||||
func ServiceProvider(rawBaseURL string, fakeSSLTermination bool, httpTimeout time.Duration) service.Provider {
|
||||
var (
|
||||
baseURL *url.URL
|
||||
err error
|
||||
)
|
||||
|
||||
baseURL, err = url.Parse(rawBaseURL)
|
||||
if err != nil {
|
||||
err = errors.Wrap(err, "could not parse base url")
|
||||
}
|
||||
|
||||
client := NewClient(baseURL, fakeSSLTermination, httpTimeout)
|
||||
|
||||
return func(ctn *service.Container) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
}
|
29
internal/hydra/request.go
Normal file
29
internal/hydra/request.go
Normal file
@ -0,0 +1,29 @@
|
||||
package hydra
|
||||
|
||||
type AcceptLoginRequest struct {
|
||||
Subject string `json:"subject"`
|
||||
Remember bool `json:"remember"`
|
||||
RememberFor int `json:"remember_for"`
|
||||
ACR string `json:"acr"`
|
||||
Context map[string]interface{} `json:"context"`
|
||||
}
|
||||
|
||||
type AcceptLogoutRequest struct{}
|
||||
|
||||
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"`
|
||||
}
|
88
internal/hydra/response.go
Normal file
88
internal/hydra/response.go
Normal file
@ -0,0 +1,88 @@
|
||||
package hydra
|
||||
|
||||
import "time"
|
||||
|
||||
// https://www.ory.sh/hydra/docs/reference/api#get-a-login-request
|
||||
|
||||
type ClientResponseFragment struct {
|
||||
AllowCORSOrigins []string `json:"allowed_cors_origins"`
|
||||
Audience []string `json:"audience"`
|
||||
BackChannelLogoutSessionRequired bool `json:"backchannel_logout_session_required"`
|
||||
BackChannelLogoutURI string `json:"backchannel_logout_uri"`
|
||||
ClientID string `json:"client_id"`
|
||||
ClientName string `json:"client_name"`
|
||||
ClientSecret string `json:"client_secret"`
|
||||
ClientSecretExpiresAt int `json:"client_secret_expires_at"`
|
||||
ClientURI string `json:"client_uri"`
|
||||
Contacts []string `json:"contacts"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
FrontChannelLogoutSessionRequired bool `json:"frontchannel_logout_session_required"`
|
||||
FrontChannelLogoutURL string `json:"frontchannel_logout_uri"`
|
||||
GrantTypes []string `json:"grant_types"`
|
||||
JWKS map[string]interface{} `json:"jwks"`
|
||||
JwksURI string `json:"jwks_uri"`
|
||||
LogoURI string `json:"logo_uri"`
|
||||
Metadata map[string]interface{} `json:"metadata"`
|
||||
Owner string `json:"owner"`
|
||||
PolicyURI string `json:"policy_uri"`
|
||||
PostLogoutRedirectURIs []string `json:"post_logout_redirect_uris"`
|
||||
RedirectURIs []string `json:"redirect_uris"`
|
||||
RequestObjectSigningAlg string `json:"request_object_signing_alg"`
|
||||
RequestURIs []string `json:"request_uris"`
|
||||
ResponseTypes []string `json:"response_types"`
|
||||
Scope string `json:"scope"`
|
||||
SectorIdentifierURI string `json:"sector_identifier_uri"`
|
||||
SubjectType string `json:"subject_type"`
|
||||
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
|
||||
TosURI string `json:"tos_uri"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
UserInfoSignedResponseAlg string `json:"userinfo_signed_response_alg"`
|
||||
}
|
||||
|
||||
type OidcContextResponseFragment struct {
|
||||
ACRValues []string `json:"acr_values"`
|
||||
Display string `json:"display"`
|
||||
IDTokenHintClaims map[string]interface{} `json:"id_token_hint_claims"`
|
||||
LoginHint string `json:"login_hint"`
|
||||
UILocales []string `json:"ui_locales"`
|
||||
}
|
||||
|
||||
type LoginResponse 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"`
|
||||
}
|
||||
|
||||
type AcceptResponse struct {
|
||||
RedirectTo string `json:"redirect_to"`
|
||||
}
|
||||
|
||||
type RejectResponse struct {
|
||||
RedirectTo string `json:"redirect_to"`
|
||||
}
|
||||
|
||||
type LogoutResponse struct {
|
||||
Subject string `json:"subject"`
|
||||
SessionID string `json:"sid"`
|
||||
RPInitiated bool `json:"rp_initiated"`
|
||||
RequestURL string `json:"request_url"`
|
||||
}
|
||||
|
||||
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"`
|
||||
Context map[string]interface{} `json:"context"`
|
||||
}
|
33
internal/hydra/service.go
Normal file
33
internal/hydra/service.go
Normal file
@ -0,0 +1,33 @@
|
||||
package hydra
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/service"
|
||||
)
|
||||
|
||||
const ServiceName service.Name = "hydra"
|
||||
|
||||
// From retrieves the hydra service in the given container
|
||||
func From(container *service.Container) (*Client, error) {
|
||||
service, err := container.Service(ServiceName)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
|
||||
}
|
||||
|
||||
srv, ok := service.(*Client)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
|
||||
}
|
||||
|
||||
return srv, nil
|
||||
}
|
||||
|
||||
// Must retrieves the hydra service in the given container or panic otherwise
|
||||
func Must(container *service.Container) *Client {
|
||||
srv, err := From(container)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return srv
|
||||
}
|
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
|
||||
}
|
8
internal/storage/credential.go
Normal file
8
internal/storage/credential.go
Normal file
@ -0,0 +1,8 @@
|
||||
package storage
|
||||
|
||||
import "github.com/go-webauthn/webauthn/webauthn"
|
||||
|
||||
type Credential struct {
|
||||
ID string `json:"id"`
|
||||
Credential *webauthn.Credential `json:"credential"`
|
||||
}
|
8
internal/storage/error.go
Normal file
8
internal/storage/error.go
Normal file
@ -0,0 +1,8 @@
|
||||
package storage
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrAlreadyExist = errors.New("already exist")
|
||||
ErrNotFound = errors.New("not found")
|
||||
)
|
7
internal/storage/id.go
Normal file
7
internal/storage/id.go
Normal file
@ -0,0 +1,7 @@
|
||||
package storage
|
||||
|
||||
import "github.com/google/uuid"
|
||||
|
||||
func NewID() string {
|
||||
return uuid.New().String()
|
||||
}
|
15
internal/storage/provider.go
Normal file
15
internal/storage/provider.go
Normal file
@ -0,0 +1,15 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"gitlab.com/wpetit/goweb/service"
|
||||
)
|
||||
|
||||
func ServiceProvider(userRepo UserRepository) service.Provider {
|
||||
srv := &Service{
|
||||
userRepository: userRepo,
|
||||
}
|
||||
|
||||
return func(ctn *service.Container) (interface{}, error) {
|
||||
return srv, nil
|
||||
}
|
||||
}
|
17
internal/storage/registration_link.go
Normal file
17
internal/storage/registration_link.go
Normal file
@ -0,0 +1,17 @@
|
||||
package storage
|
||||
|
||||
import "time"
|
||||
|
||||
type RegistrationLink struct {
|
||||
Token string `json:"token"`
|
||||
UserID string `json:"userId"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
}
|
||||
|
||||
func NewRegistrationLink(userID string) *RegistrationLink {
|
||||
return &RegistrationLink{
|
||||
UserID: userID,
|
||||
Token: NewID(),
|
||||
CreatedAt: time.Now(),
|
||||
}
|
||||
}
|
41
internal/storage/service.go
Normal file
41
internal/storage/service.go
Normal file
@ -0,0 +1,41 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/service"
|
||||
)
|
||||
|
||||
const ServiceName service.Name = "storage"
|
||||
|
||||
// From retrieves the storage service in the given container
|
||||
func From(container *service.Container) (*Service, error) {
|
||||
service, err := container.Service(ServiceName)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
|
||||
}
|
||||
|
||||
srv, ok := service.(*Service)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
|
||||
}
|
||||
|
||||
return srv, nil
|
||||
}
|
||||
|
||||
// Must retrieves the storage service in the given container or panic otherwise
|
||||
func Must(container *service.Container) *Service {
|
||||
srv, err := From(container)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return srv
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
userRepository UserRepository
|
||||
}
|
||||
|
||||
func (s *Service) User() UserRepository {
|
||||
return s.userRepository
|
||||
}
|
682
internal/storage/sqlite/user_repository.go
Normal file
682
internal/storage/sqlite/user_repository.go
Normal file
@ -0,0 +1,682 @@
|
||||
package sqlite
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"forge.cadoles.com/wpetit/hydra-webauthn/internal/storage"
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
|
||||
_ "embed"
|
||||
|
||||
_ "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
db *sql.DB
|
||||
sqliteBusyRetryMaxAttempts int
|
||||
}
|
||||
|
||||
// Create implements storage.UserRepository.
|
||||
func (r *UserRepository) CreateUser(ctx context.Context, username string, attributes map[string]any) (*storage.User, error) {
|
||||
user := storage.NewUser(username, attributes)
|
||||
|
||||
err := r.withTxRetry(ctx, func(tx *sql.Tx) error {
|
||||
query := `SELECT COUNT(id) FROM users WHERE username = $1`
|
||||
args := []any{
|
||||
user.Username,
|
||||
}
|
||||
|
||||
row := tx.QueryRowContext(ctx, query, args...)
|
||||
|
||||
var count int64
|
||||
if err := row.Scan(&count); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := row.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if count > 0 {
|
||||
return errors.WithStack(storage.ErrAlreadyExist)
|
||||
}
|
||||
|
||||
query = `
|
||||
INSERT INTO users (id, username, attributes, created_at, updated_at)
|
||||
VALUES ($1, $2, $3, $4, $4)
|
||||
`
|
||||
|
||||
rawAttributes, err := json.Marshal(user.Attributes)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
args = []any{
|
||||
user.ID,
|
||||
user.Username,
|
||||
rawAttributes,
|
||||
user.CreatedAt,
|
||||
user.UpdatedAt,
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// DeleteUserByID implements storage.UserRepository.
|
||||
func (*UserRepository) DeleteUserByID(ctx context.Context, username string) error {
|
||||
panic("unimplemented")
|
||||
}
|
||||
|
||||
// FindUserByUsername implements storage.UserRepository.
|
||||
func (r *UserRepository) FindUserByUsername(ctx context.Context, username string) (*storage.User, error) {
|
||||
user, err := r.findUserBy(ctx, "username", username)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// FindUserByID implements storage.UserRepository.
|
||||
func (r *UserRepository) FindUserByID(ctx context.Context, userID string) (*storage.User, error) {
|
||||
user, err := r.findUserBy(ctx, "id", userID)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) findUserBy(ctx context.Context, column string, value any) (*storage.User, error) {
|
||||
user := &storage.User{}
|
||||
err := r.withTxRetry(ctx, func(tx *sql.Tx) error {
|
||||
query := fmt.Sprintf(`SELECT id, username, attributes, created_at, updated_at FROM users WHERE %s = $1`, column)
|
||||
args := []any{
|
||||
value,
|
||||
}
|
||||
|
||||
var rawAttributes []byte
|
||||
|
||||
row := tx.QueryRowContext(ctx, query, args...)
|
||||
if err := row.Scan(&user.ID, &user.Username, &rawAttributes, &user.CreatedAt, &user.UpdatedAt); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return errors.WithStack(storage.ErrNotFound)
|
||||
}
|
||||
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := row.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(rawAttributes, &user.Attributes); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if user.Attributes == nil {
|
||||
user.Attributes = make(map[string]any)
|
||||
}
|
||||
|
||||
query = `SELECT credential FROM user_credentials WHERE user_id = $1`
|
||||
args = []any{
|
||||
user.ID,
|
||||
}
|
||||
|
||||
rows, err := tx.QueryContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err := rows.Close(); err != nil {
|
||||
logger.Error(ctx, "could not close rows", logger.E(errors.WithStack(err)))
|
||||
}
|
||||
}()
|
||||
|
||||
user.Credentials = make([]webauthn.Credential, 0)
|
||||
|
||||
for rows.Next() {
|
||||
var (
|
||||
rawCredential []byte
|
||||
credential webauthn.Credential
|
||||
)
|
||||
|
||||
if err := rows.Scan(&rawCredential); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(rawCredential, &credential); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
user.Credentials = append(user.Credentials, credential)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// List implements storage.UserRepository.
|
||||
func (r *UserRepository) ListUsers(ctx context.Context) ([]storage.UserHeader, error) {
|
||||
users := make([]storage.UserHeader, 0)
|
||||
|
||||
err := r.withTxRetry(ctx, func(tx *sql.Tx) error {
|
||||
query := `SELECT id, username, created_at, updated_at FROM users`
|
||||
|
||||
rows, err := tx.QueryContext(ctx, query)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err := rows.Close(); err != nil {
|
||||
logger.Error(ctx, "could not close rows", logger.E(errors.WithStack(err)))
|
||||
}
|
||||
}()
|
||||
|
||||
for rows.Next() {
|
||||
user := storage.UserHeader{}
|
||||
if err := rows.Scan(&user.ID, &user.Username, &user.CreatedAt, &user.UpdatedAt); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
users = append(users, user)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return users, nil
|
||||
}
|
||||
|
||||
// UpdateUsername implements storage.UserRepository.
|
||||
func (r *UserRepository) UpdateUserUsername(ctx context.Context, userID string, username string) (*storage.User, error) {
|
||||
var user *storage.User
|
||||
|
||||
err := r.withTxRetry(ctx, func(tx *sql.Tx) error {
|
||||
query := `SELECT COUNT(id) FROM users WHERE id = $1`
|
||||
args := []any{
|
||||
userID,
|
||||
}
|
||||
|
||||
row := tx.QueryRowContext(ctx, query, args...)
|
||||
|
||||
var count int64
|
||||
if err := row.Scan(&count); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := row.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
return errors.WithStack(storage.ErrNotFound)
|
||||
}
|
||||
|
||||
query = `
|
||||
UPDATE users SET username = $1, updated_at = $2 WHERE id = $3
|
||||
RETURNING id, username, attributes, created_at, updated_at
|
||||
`
|
||||
|
||||
args = []any{
|
||||
username,
|
||||
time.Now(),
|
||||
userID,
|
||||
}
|
||||
|
||||
var rawAttributes []byte
|
||||
|
||||
user = &storage.User{}
|
||||
|
||||
row = tx.QueryRowContext(ctx, query, args...)
|
||||
if err := row.Scan(&user.ID, &user.Username, &rawAttributes, &user.CreatedAt, &user.UpdatedAt); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := row.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(rawAttributes, &user.Attributes); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if user.Attributes == nil {
|
||||
user.Attributes = make(map[string]any)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// Update implements storage.UserRepository.
|
||||
func (r *UserRepository) UpdateUserAttributes(ctx context.Context, userID string, attributes map[string]any) (*storage.User, error) {
|
||||
var user *storage.User
|
||||
|
||||
err := r.withTxRetry(ctx, func(tx *sql.Tx) error {
|
||||
query := `SELECT COUNT(id) FROM users WHERE id = $1`
|
||||
args := []any{
|
||||
userID,
|
||||
}
|
||||
|
||||
row := tx.QueryRowContext(ctx, query, args...)
|
||||
|
||||
var count int64
|
||||
if err := row.Scan(&count); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := row.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if count == 0 {
|
||||
return errors.WithStack(storage.ErrNotFound)
|
||||
}
|
||||
|
||||
query = `
|
||||
UPDATE users SET attributes = $1, updated_at = $2 WHERE id = $3
|
||||
RETURNING id, username, attributes, created_at, updated_at
|
||||
`
|
||||
|
||||
rawAttributes, err := json.Marshal(attributes)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
args = []any{
|
||||
rawAttributes,
|
||||
time.Now(),
|
||||
userID,
|
||||
}
|
||||
|
||||
user = &storage.User{}
|
||||
|
||||
row = tx.QueryRowContext(ctx, query, args...)
|
||||
if err := row.Scan(&user.ID, &user.Username, &rawAttributes, &user.CreatedAt, &user.UpdatedAt); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := row.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := json.Unmarshal(rawAttributes, &user.Attributes); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if user.Attributes == nil {
|
||||
user.Attributes = make(map[string]any)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// AddCredential implements storage.UserRepository.
|
||||
func (r *UserRepository) AddUserCredential(ctx context.Context, userID string, credential *webauthn.Credential) (string, error) {
|
||||
credentialID := storage.NewID()
|
||||
|
||||
err := r.withTxRetry(ctx, func(tx *sql.Tx) error {
|
||||
exists, err := r.userExists(ctx, tx, userID)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
return errors.WithStack(storage.ErrNotFound)
|
||||
}
|
||||
|
||||
query := `
|
||||
INSERT INTO user_credentials (id, user_id, credential, created_at)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
`
|
||||
|
||||
rawCredential, err := json.Marshal(credential)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
args := []any{
|
||||
credentialID,
|
||||
userID,
|
||||
rawCredential,
|
||||
time.Now(),
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return "", errors.WithStack(err)
|
||||
}
|
||||
|
||||
return credentialID, nil
|
||||
}
|
||||
|
||||
// RemoveCredential implements storage.UserRepository.
|
||||
func (r *UserRepository) RemoveUserCredential(ctx context.Context, userID string, credentialID string) error {
|
||||
err := r.withTxRetry(ctx, func(tx *sql.Tx) error {
|
||||
exists, err := r.userExists(ctx, tx, userID)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
return errors.WithStack(storage.ErrNotFound)
|
||||
}
|
||||
|
||||
query := `
|
||||
DELETE FROM user_credentials WHERE id = $1 AND user_id = $2
|
||||
`
|
||||
|
||||
args := []any{
|
||||
credentialID,
|
||||
userID,
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenerateRegistrationLink implements storage.UserRepository.
|
||||
func (r *UserRepository) GenerateRegistrationLink(ctx context.Context, userID string) (*storage.RegistrationLink, error) {
|
||||
registrationLink := storage.NewRegistrationLink(userID)
|
||||
|
||||
err := r.withTxRetry(ctx, func(tx *sql.Tx) error {
|
||||
exists, err := r.userExists(ctx, tx, userID)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if !exists {
|
||||
return errors.WithStack(storage.ErrNotFound)
|
||||
}
|
||||
|
||||
query := `DELETE FROM registration_links WHERE user_id = $1`
|
||||
args := []any{
|
||||
registrationLink.UserID,
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
query = `
|
||||
INSERT INTO registration_links (token, user_id, created_at)
|
||||
VALUES ($1, $2, $3)
|
||||
`
|
||||
|
||||
args = []any{
|
||||
registrationLink.Token,
|
||||
registrationLink.UserID,
|
||||
registrationLink.CreatedAt,
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx, query, args...); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return registrationLink, nil
|
||||
}
|
||||
|
||||
// ClearRegistrationLink implements storage.UserRepository.
|
||||
func (*UserRepository) ClearRegistrationLink(ctx context.Context, userID string) error {
|
||||
panic("unimplemented")
|
||||
}
|
||||
|
||||
// GetRegistrationLink implements storage.UserRepository.
|
||||
func (r *UserRepository) GetRegistrationLink(ctx context.Context, userID string) (*storage.RegistrationLink, error) {
|
||||
registrationLink := &storage.RegistrationLink{}
|
||||
err := r.withTxRetry(ctx, func(tx *sql.Tx) error {
|
||||
query := `SELECT token, user_id, created_at FROM registration_links WHERE user_id = $1`
|
||||
args := []any{
|
||||
userID,
|
||||
}
|
||||
|
||||
row := tx.QueryRowContext(ctx, query, args...)
|
||||
if err := row.Scan(®istrationLink.Token, ®istrationLink.UserID, ®istrationLink.CreatedAt); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return errors.WithStack(storage.ErrNotFound)
|
||||
}
|
||||
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := row.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return registrationLink, nil
|
||||
}
|
||||
|
||||
// GetRegistrationLinkByToken implements storage.UserRepository.
|
||||
func (r *UserRepository) GetRegistrationLinkByToken(ctx context.Context, token string) (*storage.RegistrationLink, error) {
|
||||
registrationLink := &storage.RegistrationLink{}
|
||||
err := r.withTxRetry(ctx, func(tx *sql.Tx) error {
|
||||
query := `SELECT token, user_id, created_at FROM registration_links WHERE token = $1`
|
||||
args := []any{
|
||||
token,
|
||||
}
|
||||
|
||||
row := tx.QueryRowContext(ctx, query, args...)
|
||||
if err := row.Scan(®istrationLink.Token, ®istrationLink.UserID, ®istrationLink.CreatedAt); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return errors.WithStack(storage.ErrNotFound)
|
||||
}
|
||||
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := row.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return registrationLink, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) userExists(ctx context.Context, tx *sql.Tx, userID string) (bool, error) {
|
||||
query := `SELECT COUNT(id) FROM users WHERE id = $1`
|
||||
args := []any{
|
||||
userID,
|
||||
}
|
||||
|
||||
row := tx.QueryRowContext(ctx, query, args...)
|
||||
|
||||
var count int64
|
||||
if err := row.Scan(&count); err != nil {
|
||||
return false, errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := row.Err(); err != nil {
|
||||
return false, errors.WithStack(err)
|
||||
}
|
||||
|
||||
return count >= 1, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) withTxRetry(ctx context.Context, fn func(*sql.Tx) error) error {
|
||||
attempts := 0
|
||||
max := r.sqliteBusyRetryMaxAttempts
|
||||
|
||||
ctx = logger.With(ctx, logger.F("max", max))
|
||||
|
||||
var err error
|
||||
for {
|
||||
ctx = logger.With(ctx)
|
||||
|
||||
if attempts >= max {
|
||||
logger.Debug(ctx, "transaction retrying failed", logger.F("attempts", attempts))
|
||||
|
||||
return errors.Wrapf(err, "transaction failed after %d attempts", max)
|
||||
}
|
||||
|
||||
err = r.withTx(ctx, fn)
|
||||
if err != nil {
|
||||
if !strings.Contains(err.Error(), "(5) (SQLITE_BUSY)") {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
err = errors.WithStack(err)
|
||||
|
||||
logger.Warn(ctx, "database is busy", logger.E(err))
|
||||
|
||||
wait := time.Duration(8<<(attempts+1)) * time.Millisecond
|
||||
|
||||
logger.Debug(
|
||||
ctx, "database is busy, waiting before retrying transaction",
|
||||
logger.F("wait", wait.String()),
|
||||
logger.F("attempts", attempts),
|
||||
)
|
||||
|
||||
timer := time.NewTimer(wait)
|
||||
select {
|
||||
case <-timer.C:
|
||||
attempts++
|
||||
continue
|
||||
|
||||
case <-ctx.Done():
|
||||
if err := ctx.Err(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r *UserRepository) withTx(ctx context.Context, fn func(*sql.Tx) error) error {
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
if err := tx.Rollback(); err != nil {
|
||||
if errors.Is(err, sql.ErrTxDone) {
|
||||
return
|
||||
}
|
||||
|
||||
err = errors.WithStack(err)
|
||||
logger.Error(ctx, "could not rollback transaction", logger.CapturedE(err))
|
||||
}
|
||||
}()
|
||||
|
||||
if err := fn(tx); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func NewUserRepository(dsn string) (*UserRepository, error) {
|
||||
db, err := sql.Open("sqlite", dsn)
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
|
||||
if err := applyUserRepositoryMigration(db); err != nil {
|
||||
return nil, errors.Wrap(err, "could not migrate schema")
|
||||
}
|
||||
|
||||
return &UserRepository{db, 5}, nil
|
||||
}
|
||||
|
||||
var _ storage.UserRepository = &UserRepository{}
|
||||
|
||||
//go:embed user_repository.sql
|
||||
var userRepositoryMigrationScript string
|
||||
|
||||
func applyUserRepositoryMigration(db *sql.DB) error {
|
||||
if err := db.Ping(); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
if _, err := db.Exec(userRepositoryMigrationScript); err != nil {
|
||||
return errors.WithStack(err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
22
internal/storage/sqlite/user_repository.sql
Normal file
22
internal/storage/sqlite/user_repository.sql
Normal file
@ -0,0 +1,22 @@
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
username TEXT NOT NULL UNIQUE,
|
||||
attributes JSON NOT NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
updated_at DATETIME NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS registration_links (
|
||||
token TEXT NOT NULL PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_credentials (
|
||||
id TEXT NOT NULL PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
credential JSON NOT NULL,
|
||||
created_at DATETIME NOT NULL,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id)
|
||||
);
|
65
internal/storage/user.go
Normal file
65
internal/storage/user.go
Normal file
@ -0,0 +1,65 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
)
|
||||
|
||||
type UserHeader struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
UpdatedAt time.Time `json:"updatedAt"`
|
||||
}
|
||||
|
||||
type User struct {
|
||||
UserHeader
|
||||
|
||||
Attributes map[string]any `json:"attributes"`
|
||||
Credentials []webauthn.Credential `json:"credentials"`
|
||||
}
|
||||
|
||||
// WebAuthnCredentials implements webauthn.User.
|
||||
func (u *User) WebAuthnCredentials() []webauthn.Credential {
|
||||
return u.Credentials
|
||||
}
|
||||
|
||||
// WebAuthnDisplayName implements webauthn.User.
|
||||
func (u *User) WebAuthnDisplayName() string {
|
||||
return u.Username
|
||||
}
|
||||
|
||||
// WebAuthnID implements webauthn.User.
|
||||
func (u *User) WebAuthnID() []byte {
|
||||
return []byte(u.ID)
|
||||
}
|
||||
|
||||
// WebAuthnIcon implements webauthn.User.
|
||||
func (u *User) WebAuthnIcon() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// WebAuthnName implements webauthn.User.
|
||||
func (u *User) WebAuthnName() string {
|
||||
return u.Username
|
||||
}
|
||||
|
||||
func NewUser(username string, attributes map[string]any) *User {
|
||||
now := time.Now()
|
||||
return &User{
|
||||
UserHeader: UserHeader{
|
||||
ID: NewID(),
|
||||
Username: username,
|
||||
|
||||
CreatedAt: now,
|
||||
UpdatedAt: now,
|
||||
},
|
||||
|
||||
Attributes: attributes,
|
||||
Credentials: make([]webauthn.Credential, 0),
|
||||
}
|
||||
}
|
||||
|
||||
var _ webauthn.User = &User{}
|
27
internal/storage/user_repository.go
Normal file
27
internal/storage/user_repository.go
Normal file
@ -0,0 +1,27 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
CreateUser(ctx context.Context, username string, attributes map[string]any) (*User, error)
|
||||
|
||||
UpdateUserUsername(ctx context.Context, userID string, username string) (*User, error)
|
||||
UpdateUserAttributes(ctx context.Context, userID string, attributes map[string]any) (*User, error)
|
||||
|
||||
AddUserCredential(ctx context.Context, userID string, credential *webauthn.Credential) (string, error)
|
||||
RemoveUserCredential(ctx context.Context, userID string, credentialID string) error
|
||||
|
||||
GenerateRegistrationLink(ctx context.Context, userID string) (*RegistrationLink, error)
|
||||
GetRegistrationLink(ctx context.Context, userID string) (*RegistrationLink, error)
|
||||
GetRegistrationLinkByToken(ctx context.Context, token string) (*RegistrationLink, error)
|
||||
ClearRegistrationLink(ctx context.Context, userID string) error
|
||||
|
||||
DeleteUserByID(ctx context.Context, userID string) error
|
||||
FindUserByID(ctx context.Context, userID string) (*User, error)
|
||||
FindUserByUsername(ctx context.Context, username string) (*User, error)
|
||||
ListUsers(ctx context.Context) ([]UserHeader, error)
|
||||
}
|
29
internal/webauthn/provider.go
Normal file
29
internal/webauthn/provider.go
Normal file
@ -0,0 +1,29 @@
|
||||
package webauthn
|
||||
|
||||
import (
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/service"
|
||||
)
|
||||
|
||||
type Config = webauthn.Config
|
||||
type TimeoutsConfig = webauthn.TimeoutsConfig
|
||||
type TimeoutConfig = webauthn.TimeoutConfig
|
||||
type LoginOption = webauthn.LoginOption
|
||||
type SessionData = webauthn.SessionData
|
||||
|
||||
var WithAllowedCredentials = webauthn.WithAllowedCredentials
|
||||
var WithAssertionExtensions = webauthn.WithAssertionExtensions
|
||||
var WithUserVerification = webauthn.WithUserVerification
|
||||
var WithAppIdExtension = webauthn.WithAppIdExtension
|
||||
|
||||
func ServiceProvider(config *Config) service.Provider {
|
||||
webauthn, err := webauthn.New(config)
|
||||
|
||||
return func(ctn *service.Container) (interface{}, error) {
|
||||
if err != nil {
|
||||
return nil, errors.WithStack(err)
|
||||
}
|
||||
return webauthn, nil
|
||||
}
|
||||
}
|
34
internal/webauthn/service.go
Normal file
34
internal/webauthn/service.go
Normal file
@ -0,0 +1,34 @@
|
||||
package webauthn
|
||||
|
||||
import (
|
||||
"github.com/go-webauthn/webauthn/webauthn"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/service"
|
||||
)
|
||||
|
||||
const ServiceName service.Name = "webauthn"
|
||||
|
||||
// From retrieves the webauthn service in the given container
|
||||
func From(container *service.Container) (*webauthn.WebAuthn, error) {
|
||||
service, err := container.Service(ServiceName)
|
||||
if err != nil {
|
||||
return nil, errors.Wrapf(err, "error while retrieving '%s' service", ServiceName)
|
||||
}
|
||||
|
||||
srv, ok := service.(*webauthn.WebAuthn)
|
||||
if !ok {
|
||||
return nil, errors.Errorf("retrieved service is not a valid '%s' service", ServiceName)
|
||||
}
|
||||
|
||||
return srv, nil
|
||||
}
|
||||
|
||||
// Must retrieves the config service in the given container or panic otherwise
|
||||
func Must(container *service.Container) *webauthn.WebAuthn {
|
||||
srv, err := From(container)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
return srv
|
||||
}
|
Reference in New Issue
Block a user