183 lines
6.3 KiB
Go
183 lines
6.3 KiB
Go
package v1
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"math"
|
|
"strings"
|
|
"time"
|
|
|
|
"lincodex/backend/internal/adapter/primary/http/api"
|
|
httpmiddleware "lincodex/backend/internal/adapter/primary/http/middleware"
|
|
"lincodex/backend/internal/adapter/primary/http/problem"
|
|
"lincodex/backend/internal/usecase/identity"
|
|
)
|
|
|
|
// AccountRegistration is what IdentityHandler needs from the registration
|
|
// usecase.
|
|
type AccountRegistration interface {
|
|
Register(ctx context.Context, command identity.RegisterCommand) error
|
|
ResendVerification(ctx context.Context, command identity.ResendCommand) error
|
|
}
|
|
|
|
// EmailConfirmation is what IdentityHandler needs from the confirmation usecase.
|
|
type EmailConfirmation interface {
|
|
Confirm(ctx context.Context, command identity.ConfirmCommand) (identity.ConfirmationResult, error)
|
|
}
|
|
|
|
// IdentityHandlerOption configures an optional identity operation.
|
|
type IdentityHandlerOption func(*IdentityHandler)
|
|
|
|
// IdentityHandler serves anonymous registration, resend, and confirmation
|
|
// operations.
|
|
type IdentityHandler struct {
|
|
registration AccountRegistration
|
|
confirmation EmailConfirmation
|
|
confirmationOrigin string
|
|
}
|
|
|
|
func NewIdentityHandler(registration AccountRegistration, options ...IdentityHandlerOption) *IdentityHandler {
|
|
handler := &IdentityHandler{registration: registration}
|
|
for _, option := range options {
|
|
option(handler)
|
|
}
|
|
return handler
|
|
}
|
|
|
|
// WithEmailConfirmation serves ConfirmEmail and compares Origin with the
|
|
// configured public application origin. The request Host is never trusted.
|
|
func WithEmailConfirmation(confirmation EmailConfirmation, publicOrigin string) IdentityHandlerOption {
|
|
return func(handler *IdentityHandler) {
|
|
handler.confirmation = confirmation
|
|
handler.confirmationOrigin = publicOrigin
|
|
}
|
|
}
|
|
|
|
func (handler *IdentityHandler) RegisterAccount(
|
|
ctx context.Context,
|
|
request *api.RegistrationRequest,
|
|
params api.RegisterAccountParams,
|
|
) (api.RegisterAccountRes, error) {
|
|
err := handler.registration.Register(ctx, identity.RegisterCommand{
|
|
IdempotencyKey: params.IdempotencyKey,
|
|
Email: string(request.Email),
|
|
Password: string(request.Password),
|
|
Scenario: string(request.Scenario),
|
|
ConsentTextVersion: string(request.ConsentC1.TextVersion),
|
|
ClientKey: clientKey(ctx),
|
|
})
|
|
switch {
|
|
case err == nil:
|
|
return accepted(), nil
|
|
case errors.Is(err, identity.ErrInvalidField):
|
|
return (*api.RegisterAccountBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
|
|
case errors.Is(err, identity.ErrIdempotencyKeyReused):
|
|
return (*api.RegisterAccountUnprocessableEntity)(&problem.New(ctx, api.ProblemCodeIdempotencyKeyReused).Response), nil
|
|
}
|
|
if limited, ok := rateLimited(ctx, err); ok {
|
|
return limited, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
func (handler *IdentityHandler) ResendEmailVerification(
|
|
ctx context.Context,
|
|
request *api.EmailVerificationResendRequest,
|
|
) (api.ResendEmailVerificationRes, error) {
|
|
if handler.registration == nil {
|
|
return nil, errors.New("IdentityHandler.ResendEmailVerification - registration is not configured")
|
|
}
|
|
err := handler.registration.ResendVerification(ctx, identity.ResendCommand{
|
|
Email: string(request.Email),
|
|
ClientKey: clientKey(ctx),
|
|
})
|
|
switch {
|
|
case err == nil:
|
|
return accepted(), nil
|
|
case errors.Is(err, identity.ErrInvalidField):
|
|
return (*api.ResendEmailVerificationBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
|
|
}
|
|
if limited, ok := rateLimited(ctx, err); ok {
|
|
return limited, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
func (handler *IdentityHandler) ConfirmEmail(
|
|
ctx context.Context,
|
|
request *api.EmailVerificationRequest,
|
|
params api.ConfirmEmailParams,
|
|
) (api.ConfirmEmailRes, error) {
|
|
if handler.confirmation == nil {
|
|
return nil, errors.New("IdentityHandler.ConfirmEmail - confirmation is not configured")
|
|
}
|
|
origin, ok := params.Origin.Get()
|
|
if !ok || strings.TrimSpace(origin) == "" || origin != handler.confirmationOrigin {
|
|
return (*api.ConfirmEmailForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
|
}
|
|
|
|
result, err := handler.confirmation.Confirm(ctx, identity.ConfirmCommand{
|
|
Token: string(request.Token),
|
|
Password: request.Password,
|
|
ClientKey: clientKey(ctx),
|
|
})
|
|
switch {
|
|
case err == nil:
|
|
return &api.EmailVerificationResult{
|
|
EmailVerified: api.EmailVerificationResultEmailVerifiedTrue,
|
|
Scenario: api.AccountScenario(result.Scenario),
|
|
OnboardingStep: api.OnboardingStep(result.OnboardingStep),
|
|
}, nil
|
|
case errors.Is(err, identity.ErrVerificationTokenInvalid):
|
|
return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenInvalid).Response), nil
|
|
case errors.Is(err, identity.ErrVerificationTokenExpired):
|
|
return (*api.ConfirmEmailBadRequest)(&problem.New(ctx, api.ProblemCodeVerificationTokenExpired).Response), nil
|
|
}
|
|
if limited, ok := rateLimited(ctx, err); ok {
|
|
return limited, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
func accepted() *api.IdentityRequestAccepted {
|
|
return &api.IdentityRequestAccepted{Status: api.IdentityRequestAcceptedStatusAccepted}
|
|
}
|
|
|
|
// clientKey is the limiter key of the client network address that the
|
|
// ClientIP middleware resolved. Without it, for example when the middleware
|
|
// is not mounted, the per-client limit is skipped and only the per-address
|
|
// limits apply: a shared bucket would let one client lock everyone out.
|
|
func clientKey(ctx context.Context) string {
|
|
address, ok := httpmiddleware.ClientAddr(ctx)
|
|
if !ok {
|
|
return ""
|
|
}
|
|
return httpmiddleware.LimiterKey(address)
|
|
}
|
|
|
|
func invalidFieldProblem(ctx context.Context, err error) *api.ProblemStatusCode {
|
|
field, ok := errors.AsType[*identity.InvalidFieldError](err)
|
|
if !ok {
|
|
return problem.InvalidField(ctx, api.ProblemFieldLocationBody, "")
|
|
}
|
|
location := api.ProblemFieldLocationBody
|
|
if field.Pointer == "/Idempotency-Key" {
|
|
location = api.ProblemFieldLocationHeader
|
|
}
|
|
return problem.InvalidField(ctx, location, field.Pointer)
|
|
}
|
|
|
|
func rateLimited(ctx context.Context, err error) (*api.TooManyRequestsHeaders, bool) {
|
|
limited, ok := errors.AsType[*identity.RateLimitedError](err)
|
|
if !ok {
|
|
return nil, false
|
|
}
|
|
return problem.RateLimited(ctx, wholeSeconds(limited.RetryAfter)), true
|
|
}
|
|
|
|
// wholeSeconds rounds a wait up, so a client that waits the stated time is
|
|
// not refused again for the remainder.
|
|
func wholeSeconds(wait time.Duration) int32 {
|
|
return int32(min(math.Ceil(wait.Seconds()), math.MaxInt32))
|
|
}
|