300 lines
9.9 KiB
Go
300 lines
9.9 KiB
Go
package v1
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"math"
|
|
"net/http"
|
|
"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/domain"
|
|
"lincodex/backend/internal/usecase/identity"
|
|
)
|
|
|
|
func (handler *Handler) RegisterAccount(
|
|
ctx context.Context,
|
|
request *api.RegistrationRequest,
|
|
params api.RegisterAccountParams,
|
|
) (api.RegisterAccountRes, error) {
|
|
if handler.identity == nil {
|
|
return handler.UnimplementedHandler.RegisterAccount(ctx, request, params)
|
|
}
|
|
return handler.identity.RegisterAccount(ctx, request, params)
|
|
}
|
|
|
|
func (handler *Handler) ResendEmailVerification(
|
|
ctx context.Context,
|
|
request *api.EmailVerificationResendRequest,
|
|
) (api.ResendEmailVerificationRes, error) {
|
|
if handler.identity == nil {
|
|
return handler.UnimplementedHandler.ResendEmailVerification(ctx, request)
|
|
}
|
|
return handler.identity.ResendEmailVerification(ctx, request)
|
|
}
|
|
|
|
func (handler *Handler) ConfirmEmail(
|
|
ctx context.Context,
|
|
request *api.EmailVerificationRequest,
|
|
params api.ConfirmEmailParams,
|
|
) (api.ConfirmEmailRes, error) {
|
|
if handler.identity == nil || handler.identity.confirmation == nil {
|
|
return handler.UnimplementedHandler.ConfirmEmail(ctx, request, params)
|
|
}
|
|
return handler.identity.ConfirmEmail(ctx, request, params)
|
|
}
|
|
|
|
func (handler *Handler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) {
|
|
if handler.identity == nil || handler.identity.sessions == nil {
|
|
return handler.UnimplementedHandler.Login(ctx, request)
|
|
}
|
|
return handler.identity.Login(ctx, request)
|
|
}
|
|
|
|
func (handler *Handler) GetCurrentSession(ctx context.Context) (api.GetCurrentSessionRes, error) {
|
|
if handler.identity == nil || handler.identity.sessions == nil {
|
|
return handler.UnimplementedHandler.GetCurrentSession(ctx)
|
|
}
|
|
return handler.identity.GetCurrentSession(ctx)
|
|
}
|
|
|
|
func (handler *Handler) Logout(ctx context.Context) (api.LogoutRes, error) {
|
|
if handler.identity == nil || handler.identity.sessions == nil {
|
|
return handler.UnimplementedHandler.Logout(ctx)
|
|
}
|
|
return handler.identity.Logout(ctx)
|
|
}
|
|
|
|
func (handler *IdentityHandler) RegisterAccount(
|
|
ctx context.Context,
|
|
request *api.RegistrationRequest,
|
|
params api.RegisterAccountParams,
|
|
) (api.RegisterAccountRes, error) {
|
|
if !originAllowed(ctx, handler.publicOrigin) {
|
|
return (*api.RegisterAccountForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
|
}
|
|
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 !originAllowed(ctx, handler.publicOrigin) {
|
|
return (*api.ResendEmailVerificationForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
|
}
|
|
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,
|
|
_ api.ConfirmEmailParams,
|
|
) (api.ConfirmEmailRes, error) {
|
|
if handler.confirmation == nil {
|
|
return nil, errors.New("IdentityHandler.ConfirmEmail - confirmation is not configured")
|
|
}
|
|
if !originAllowed(ctx, handler.publicOrigin) {
|
|
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 (handler *IdentityHandler) Login(ctx context.Context, request *api.LoginRequest) (api.LoginRes, error) {
|
|
if !originAllowed(ctx, handler.publicOrigin) {
|
|
return (*api.LoginForbidden)(&problem.New(ctx, api.ProblemCodeCsrfCheckFailed).Response), nil
|
|
}
|
|
result, err := handler.sessions.Login(ctx, identity.LoginCommand{
|
|
Email: string(request.Email),
|
|
Password: string(request.Password),
|
|
ClientKey: clientKey(ctx),
|
|
Incoming: httpmiddleware.IncomingSessionToken(ctx),
|
|
})
|
|
switch {
|
|
case err == nil:
|
|
return &api.SessionHeaders{
|
|
CacheControl: api.CacheControlNoStoreNoStore,
|
|
SetCookie: sessionCookie(result.Token, result.Session),
|
|
Response: api.Session{
|
|
Account: accountFromUser(result.User),
|
|
CsrfToken: api.CsrfToken(result.CSRFToken),
|
|
},
|
|
}, nil
|
|
case errors.Is(err, identity.ErrInvalidField):
|
|
return (*api.LoginBadRequest)(&invalidFieldProblem(ctx, err).Response), nil
|
|
case errors.Is(err, identity.ErrInvalidCredentials):
|
|
return (*api.LoginUnauthorized)(&problem.New(ctx, api.ProblemCodeInvalidCredentials).Response), nil
|
|
case errors.Is(err, identity.ErrEmailNotVerified):
|
|
return (*api.LoginForbidden)(&problem.New(ctx, api.ProblemCodeEmailNotVerified).Response), nil
|
|
}
|
|
if limited, ok := rateLimited(ctx, err); ok {
|
|
return limited, nil
|
|
}
|
|
return nil, err
|
|
}
|
|
|
|
func (handler *IdentityHandler) GetCurrentSession(ctx context.Context) (api.GetCurrentSessionRes, error) {
|
|
session, ok := sessionFromContext(ctx)
|
|
if !ok || !session.EmailVerified {
|
|
return unauthenticatedProblemResponse(ctx), nil
|
|
}
|
|
return &api.GetCurrentSessionOKHeaders{
|
|
CacheControl: api.CacheControlNoStoreNoStore,
|
|
Response: api.Session{
|
|
Account: accountFromUser(session.User),
|
|
CsrfToken: api.CsrfToken(session.CSRFToken),
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
func (handler *IdentityHandler) Logout(ctx context.Context) (api.LogoutRes, error) {
|
|
session, ok := sessionFromContext(ctx)
|
|
if !ok || !session.EmailVerified {
|
|
return unauthenticatedProblemResponse(ctx), nil
|
|
}
|
|
if err := handler.sessions.Logout(ctx, session.SessionID); err != nil {
|
|
if errors.Is(err, identity.ErrUnauthenticated) {
|
|
return unauthenticatedProblemResponse(ctx), nil
|
|
}
|
|
return nil, err
|
|
}
|
|
return &api.LogoutNoContent{SetCookie: ExpiredSessionCookie()}, nil
|
|
}
|
|
|
|
func accepted() *api.IdentityRequestAccepted {
|
|
return &api.IdentityRequestAccepted{Status: api.IdentityRequestAcceptedStatusAccepted}
|
|
}
|
|
|
|
// clientKey is the limiter key of the client address resolved through trusted
|
|
// proxies. Without the middleware only per-address limits apply.
|
|
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
|
|
}
|
|
|
|
func wholeSeconds(wait time.Duration) int32 {
|
|
return int32(min(math.Ceil(wait.Seconds()), math.MaxInt32))
|
|
}
|
|
|
|
func originAllowed(ctx context.Context, expected string) bool {
|
|
if expected == "" {
|
|
return false
|
|
}
|
|
origin, ok := httpmiddleware.RequestOrigin(ctx)
|
|
return ok && origin != "" && origin == expected
|
|
}
|
|
|
|
func unauthenticatedProblemResponse(ctx context.Context) *api.Problem {
|
|
response := problem.New(ctx, api.ProblemCodeUnauthenticated).Response
|
|
return &response
|
|
}
|
|
|
|
func sessionCookie(token domain.SecretToken, session domain.Session) string {
|
|
maxAge := int(math.Ceil(session.ExpiresAt.Sub(session.CreatedAt).Seconds()))
|
|
cookie := &http.Cookie{
|
|
Name: httpmiddleware.SessionCookieName,
|
|
Value: token.Reveal(),
|
|
Path: "/",
|
|
MaxAge: maxAge,
|
|
Expires: session.ExpiresAt.UTC(),
|
|
Secure: true,
|
|
HttpOnly: true,
|
|
SameSite: http.SameSiteStrictMode,
|
|
}
|
|
return cookie.String()
|
|
}
|
|
|
|
func ExpiredSessionCookie() string {
|
|
return (&http.Cookie{
|
|
Name: httpmiddleware.SessionCookieName,
|
|
Value: "",
|
|
Path: "/",
|
|
MaxAge: -1,
|
|
Expires: time.Unix(1, 0).UTC(),
|
|
Secure: true,
|
|
HttpOnly: true,
|
|
SameSite: http.SameSiteStrictMode,
|
|
}).String()
|
|
}
|