212 lines
8.7 KiB
Go
212 lines
8.7 KiB
Go
package postgres
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgtype"
|
|
|
|
"lincodex/backend/internal/adapter/secondary/postgres/sqlc"
|
|
"lincodex/backend/internal/domain"
|
|
"lincodex/backend/internal/port/outbound"
|
|
)
|
|
|
|
type accountDeletionRequestRepository struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
func (unit *UnitOfWork) AccountDeletionRequests() outbound.AccountDeletionRequests {
|
|
return accountDeletionRequestRepository{queries: unit.queries}
|
|
}
|
|
|
|
func (repository accountDeletionRequestRepository) CreateOrGet(
|
|
ctx context.Context,
|
|
request domain.AccountDeletionRequest,
|
|
) (domain.AccountDeletionRequest, bool, error) {
|
|
if request.IsZero() {
|
|
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - request is not initialized: %w", domain.ErrInvalidConsent)
|
|
}
|
|
row, err := repository.queries.CreateAccountDeletionRequest(ctx, sqlc.CreateAccountDeletionRequestParams{
|
|
ID: pgUUID(request.ID()),
|
|
SubjectID: pgUUID(request.SubjectID()),
|
|
RequestedAt: pgTime(request.RequestedAt()),
|
|
})
|
|
if err == nil {
|
|
stored, err := accountDeletionRequestFromRow(row.ID, row.SubjectID, row.Status, row.RequestedAt)
|
|
return stored, err == nil, err
|
|
}
|
|
if !errors.Is(err, pgx.ErrNoRows) {
|
|
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - insert request: %w", mapConsentError(err))
|
|
}
|
|
activeRow, err := repository.queries.GetActiveAccountDeletionRequest(ctx, pgUUID(request.SubjectID()))
|
|
if err != nil {
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - concurrent request was not readable: %w", outbound.ErrTransactionConflict)
|
|
}
|
|
return domain.AccountDeletionRequest{}, false, fmt.Errorf("accountDeletionRequestRepository.CreateOrGet - select active request: %w", mapConsentError(err))
|
|
}
|
|
stored, err := accountDeletionRequestFromRow(activeRow.ID, activeRow.SubjectID, activeRow.Status, activeRow.RequestedAt)
|
|
return stored, false, err
|
|
}
|
|
|
|
func accountDeletionRequestFromRow(id, subjectID pgtype.UUID, status string, requestedAt pgtype.Timestamptz) (domain.AccountDeletionRequest, error) {
|
|
if !id.Valid || !subjectID.Valid || !requestedAt.Valid {
|
|
return domain.AccountDeletionRequest{}, fmt.Errorf("postgres.accountDeletionRequestFromRow - required column is null: %w", domain.ErrInvalidConsent)
|
|
}
|
|
request, err := domain.RestoreAccountDeletionRequest(id.Bytes, subjectID.Bytes, status, requestedAt.Time)
|
|
if err != nil {
|
|
return domain.AccountDeletionRequest{}, fmt.Errorf("postgres.accountDeletionRequestFromRow - restore request: %w", err)
|
|
}
|
|
return request, nil
|
|
}
|
|
|
|
type consentRevocationEffects struct {
|
|
queries *sqlc.Queries
|
|
}
|
|
|
|
func (unit *UnitOfWork) ConsentRevocationEffects() outbound.ConsentRevocationEffects {
|
|
return consentRevocationEffects{queries: unit.queries}
|
|
}
|
|
|
|
var _ outbound.ConsentRevocationEffects = consentRevocationEffects{}
|
|
|
|
func (effects consentRevocationEffects) Apply(
|
|
ctx context.Context,
|
|
revocation domain.ConsentRevocation,
|
|
records []domain.ConsentRecord,
|
|
) error {
|
|
if revocation.IsZero() || len(records) == 0 {
|
|
return fmt.Errorf("consentRevocationEffects.Apply - revocation and affected records are required: %w", domain.ErrInvalidConsent)
|
|
}
|
|
for _, record := range records {
|
|
if record.IsZero() || record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() ||
|
|
(revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) {
|
|
return fmt.Errorf("consentRevocationEffects.Apply - record scope does not match revocation: %w", domain.ErrInvalidConsent)
|
|
}
|
|
}
|
|
if revocation.Purpose() == domain.ConsentPurposePublication {
|
|
if err := effects.closePublication(ctx, revocation, records); err != nil {
|
|
return fmt.Errorf("consentRevocationEffects.Apply - close publication: %w", err)
|
|
}
|
|
}
|
|
if err := effects.appendRevocationIntent(ctx, revocation, records); err != nil {
|
|
return fmt.Errorf("consentRevocationEffects.Apply - append outbox intent: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (effects consentRevocationEffects) closePublication(
|
|
ctx context.Context,
|
|
revocation domain.ConsentRevocation,
|
|
records []domain.ConsentRecord,
|
|
) error {
|
|
const location = "consentRevocationEffects.closePublication"
|
|
recordIDs := make([]pgtype.UUID, 0, len(records))
|
|
for _, record := range records {
|
|
if record.Purpose() == domain.ConsentPurposePublication {
|
|
recordIDs = append(recordIDs, pgUUID(record.ID()))
|
|
}
|
|
}
|
|
if len(recordIDs) == 0 {
|
|
return fmt.Errorf("%s - revoked C2 record IDs are required: %w", location, domain.ErrInvalidConsent)
|
|
}
|
|
row, err := effects.queries.LockCandidatePublicationForConsentRevocation(ctx, sqlc.LockCandidatePublicationForConsentRevocationParams{
|
|
UserID: pgUUID(revocation.SubjectID()), ConsentRecordIds: recordIDs,
|
|
})
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return nil
|
|
}
|
|
if err != nil {
|
|
return fmt.Errorf("%s - close publication: %w", location, mapConsentError(err))
|
|
}
|
|
if !row.Valid {
|
|
return fmt.Errorf("%s - query returned no closing time: %w", location, domain.ErrInvalidVisibility)
|
|
}
|
|
event, err := domain.NewConsentRevokedPublicationEvent(revocation.SubjectID(), row.Time)
|
|
if err != nil {
|
|
return fmt.Errorf("%s - build publication privacy event: %w", location, err)
|
|
}
|
|
if err := effects.queries.InsertCandidatePrivacyEvent(ctx, sqlc.InsertCandidatePrivacyEventParams{
|
|
ID: pgUUID(event.ID()),
|
|
UserID: pgUUID(event.UserID()),
|
|
Kind: string(event.Kind()),
|
|
OccurredAt: pgTime(event.OccurredAt()),
|
|
Fields: event.Fields().Codes(),
|
|
ConsentRecordID: pgtype.UUID{},
|
|
OrganizationID: pgtype.UUID{},
|
|
}); err != nil {
|
|
return fmt.Errorf("%s - record publication privacy event: %w", location, mapConsentError(err))
|
|
}
|
|
return nil
|
|
}
|
|
|
|
type consentRevocationPayload struct {
|
|
RevocationID uuid.UUID `json:"revocation_id"`
|
|
RecordID uuid.UUID `json:"record_id"`
|
|
SubjectID uuid.UUID `json:"subject_id"`
|
|
Purpose domain.ConsentPurpose `json:"purpose"`
|
|
Source domain.ConsentRevocationSource `json:"source"`
|
|
RevokedAt time.Time `json:"revoked_at"`
|
|
OrganizationID *uuid.UUID `json:"organization_id,omitempty"`
|
|
Fields []domain.ContactField `json:"fields,omitempty"`
|
|
}
|
|
|
|
func (effects consentRevocationEffects) appendRevocationIntent(
|
|
ctx context.Context,
|
|
revocation domain.ConsentRevocation,
|
|
records []domain.ConsentRecord,
|
|
) error {
|
|
events, err := newConsentRevocationEvents(revocation, records)
|
|
if err != nil {
|
|
return fmt.Errorf("consentRevocationEffects.appendRevocationIntent - build events: %w", err)
|
|
}
|
|
if err := outboxWriter(effects).Append(ctx, events...); err != nil {
|
|
return fmt.Errorf("consentRevocationEffects.appendRevocationIntent - append events: %w", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func newConsentRevocationEvents(revocation domain.ConsentRevocation, records []domain.ConsentRecord) ([]domain.DomainEvent, error) {
|
|
if revocation.IsZero() || len(records) == 0 {
|
|
return nil, fmt.Errorf("newConsentRevocationEvents - revocation and records are required: %w", domain.ErrInvalidConsent)
|
|
}
|
|
revocationID, err := uuid.NewV7()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("newConsentRevocationEvents - generate revocation ID: %w", err)
|
|
}
|
|
events := make([]domain.DomainEvent, 0, len(records))
|
|
for _, record := range records {
|
|
if record.IsZero() || record.SubjectID() != revocation.SubjectID() || record.Purpose() != revocation.Purpose() ||
|
|
(revocation.Purpose().OrganizationScoped() && record.OrganizationID() != revocation.OrganizationID()) {
|
|
return nil, fmt.Errorf("newConsentRevocationEvents - record scope does not match revocation: %w", domain.ErrInvalidConsent)
|
|
}
|
|
payload := consentRevocationPayload{
|
|
RevocationID: revocationID, RecordID: record.ID(), SubjectID: revocation.SubjectID(),
|
|
Purpose: revocation.Purpose(), Source: revocation.Source(), RevokedAt: revocation.RevokedAt(),
|
|
}
|
|
if revocation.Purpose().OrganizationScoped() {
|
|
organizationID := record.OrganizationID()
|
|
payload.OrganizationID = &organizationID
|
|
payload.Fields = record.Fields().Fields()
|
|
}
|
|
body, err := json.Marshal(payload)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("newConsentRevocationEvents - marshal payload: %w", err)
|
|
}
|
|
event, err := domain.NewDomainEvent(domain.DomainEventInput{
|
|
EventType: "consent.revoked", SchemaVersion: 1, AggregateType: "consent_record",
|
|
AggregateID: record.ID(), AggregateVersion: 2, Payload: body,
|
|
})
|
|
if err != nil {
|
|
return nil, fmt.Errorf("newConsentRevocationEvents - build event: %w", err)
|
|
}
|
|
events = append(events, event)
|
|
}
|
|
return events, nil
|
|
}
|