|
| 1 | +-- 018_gdpr_compliance.sql |
| 2 | +-- GDPR compliance: account_deletions table + audit_logs FK change |
| 3 | + |
| 4 | +-- 1. Create account_deletions table |
| 5 | +CREATE TABLE IF NOT EXISTS account_deletions ( |
| 6 | + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), |
| 7 | + user_id UUID NOT NULL UNIQUE REFERENCES auth.users(id), |
| 8 | + requested_at TIMESTAMPTZ NOT NULL DEFAULT now(), |
| 9 | + scheduled_deletion_at TIMESTAMPTZ NOT NULL, |
| 10 | + cancelled_at TIMESTAMPTZ, |
| 11 | + completed_at TIMESTAMPTZ, |
| 12 | + reason TEXT, |
| 13 | + status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'cancelled', 'completed')), |
| 14 | + CONSTRAINT valid_scheduled_date CHECK (scheduled_deletion_at > requested_at) |
| 15 | +); |
| 16 | + |
| 17 | +CREATE INDEX idx_account_deletions_status ON account_deletions(status); |
| 18 | +CREATE INDEX idx_account_deletions_scheduled ON account_deletions(scheduled_deletion_at) WHERE status = 'pending'; |
| 19 | + |
| 20 | +ALTER TABLE account_deletions ENABLE ROW LEVEL SECURITY; |
| 21 | + |
| 22 | +CREATE POLICY "Users can view own deletion status" |
| 23 | + ON account_deletions FOR SELECT |
| 24 | + USING (auth.uid() = user_id); |
| 25 | + |
| 26 | +CREATE POLICY "Users can request own deletion" |
| 27 | + ON account_deletions FOR INSERT |
| 28 | + WITH CHECK (auth.uid() = user_id); |
| 29 | + |
| 30 | +CREATE POLICY "Users can cancel own deletion" |
| 31 | + ON account_deletions FOR UPDATE |
| 32 | + USING (auth.uid() = user_id); |
| 33 | + |
| 34 | +-- 2. Make audit_logs.user_id nullable and change FK to SET NULL |
| 35 | +-- This ensures audit logs survive user deletion (anonymized, not deleted) |
| 36 | +ALTER TABLE audit_logs ALTER COLUMN user_id DROP NOT NULL; |
| 37 | + |
| 38 | +ALTER TABLE audit_logs DROP CONSTRAINT IF EXISTS audit_logs_user_id_fkey; |
| 39 | +ALTER TABLE audit_logs |
| 40 | + ADD CONSTRAINT audit_logs_user_id_fkey |
| 41 | + FOREIGN KEY (user_id) REFERENCES auth.users(id) ON DELETE SET NULL; |
| 42 | + |
| 43 | +-- 3. Index for efficient data export queries |
| 44 | +CREATE INDEX IF NOT EXISTS idx_audit_logs_user_id ON audit_logs(user_id); |
0 commit comments