3760 lines
168 KiB
PL/PgSQL
3760 lines
168 KiB
PL/PgSQL
-- VA-P26a customer-portal RLS contract.
|
|
--
|
|
-- This is an additive, reviewed merge input, not a feature-branch migration.
|
|
-- The dedicated login is intentionally absent from the broad app/worker
|
|
-- tenant-policy generator. Every portal-visible entity requires both tenant
|
|
-- and PortalUser proof; project/file visibility additionally requires an
|
|
-- explicit active access/release row.
|
|
|
|
BEGIN;
|
|
|
|
DO $$
|
|
DECLARE portal_role record;
|
|
BEGIN
|
|
IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'hivegrid_portal') THEN
|
|
RAISE EXCEPTION 'hivegrid_portal must be provisioned before the portal RLS contract' USING ERRCODE = '55000';
|
|
END IF;
|
|
SELECT rolcanlogin, rolsuper, rolcreatedb, rolcreaterole, rolinherit, rolreplication, rolbypassrls
|
|
INTO portal_role FROM pg_roles WHERE rolname = 'hivegrid_portal';
|
|
IF NOT portal_role.rolcanlogin OR portal_role.rolsuper OR portal_role.rolcreatedb
|
|
OR portal_role.rolcreaterole OR portal_role.rolinherit OR portal_role.rolreplication
|
|
OR portal_role.rolbypassrls THEN
|
|
RAISE EXCEPTION 'hivegrid_portal must be LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS';
|
|
END IF;
|
|
IF EXISTS (
|
|
SELECT 1
|
|
FROM pg_auth_members AS membership
|
|
JOIN pg_roles AS granted ON granted.oid = membership.roleid
|
|
JOIN pg_roles AS member ON member.oid = membership.member
|
|
WHERE granted.rolname = 'hivegrid_portal' OR member.rolname = 'hivegrid_portal'
|
|
) THEN
|
|
RAISE EXCEPTION 'hivegrid_portal must not have role memberships';
|
|
END IF;
|
|
IF NOT current_setting('is_superuser')::boolean
|
|
AND NOT pg_has_role(current_user, 'hivegrid_rls_definer', 'MEMBER') THEN
|
|
RAISE EXCEPTION 'Migration role must be superuser or a member of hivegrid_rls_definer';
|
|
END IF;
|
|
END$$;
|
|
|
|
REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM hivegrid_portal;
|
|
REVOKE ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public FROM hivegrid_portal;
|
|
REVOKE CREATE ON SCHEMA public FROM hivegrid_portal;
|
|
GRANT USAGE ON SCHEMA public TO hivegrid_portal;
|
|
|
|
ALTER TABLE "Portal" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "Portal" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalUser" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalUser" FORCE ROW LEVEL SECURITY;
|
|
DO $portal_user_privacy_acknowledgement_constraint$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1
|
|
FROM pg_constraint
|
|
WHERE conname = 'PortalUser_privacyAcknowledgement_pair_check'
|
|
AND conrelid = 'public."PortalUser"'::regclass
|
|
) THEN
|
|
ALTER TABLE "PortalUser"
|
|
ADD CONSTRAINT "PortalUser_privacyAcknowledgement_pair_check"
|
|
CHECK (
|
|
("privacyNoticeAcknowledgedAt" IS NULL AND "privacyNoticeAcknowledgedUrl" IS NULL)
|
|
OR (
|
|
"privacyNoticeAcknowledgedAt" IS NOT NULL
|
|
AND NULLIF(btrim("privacyNoticeAcknowledgedUrl"), '') IS NOT NULL
|
|
)
|
|
) NOT VALID;
|
|
END IF;
|
|
END
|
|
$portal_user_privacy_acknowledgement_constraint$;
|
|
ALTER TABLE "PortalUser" VALIDATE CONSTRAINT "PortalUser_privacyAcknowledgement_pair_check";
|
|
ALTER TABLE "PortalSession" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalSession" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalToken" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalToken" FORCE ROW LEVEL SECURITY;
|
|
DO $portal_token_ip_binding_constraint$
|
|
BEGIN
|
|
IF NOT EXISTS (
|
|
SELECT 1
|
|
FROM pg_constraint
|
|
WHERE conname = 'PortalToken_requestedIpHash_binding_check'
|
|
AND conrelid = 'public."PortalToken"'::regclass
|
|
) THEN
|
|
ALTER TABLE "PortalToken"
|
|
ADD CONSTRAINT "PortalToken_requestedIpHash_binding_check"
|
|
CHECK (
|
|
("requestedIpHash" IS NOT NULL AND "requestedIpHash" ~ '^[a-f0-9]{64}$')
|
|
OR ("purpose"::text = 'setup' AND "requestedIpHash" IS NULL)
|
|
) NOT VALID;
|
|
END IF;
|
|
END
|
|
$portal_token_ip_binding_constraint$;
|
|
ALTER TABLE "PortalToken" VALIDATE CONSTRAINT "PortalToken_requestedIpHash_binding_check";
|
|
CREATE UNIQUE INDEX IF NOT EXISTS "PortalToken_one_live_setup_per_user_key"
|
|
ON "PortalToken" ("tenantId", "portalUserId")
|
|
WHERE "purpose" = 'setup' AND "consumedAt" IS NULL AND "revokedAt" IS NULL;
|
|
ALTER TABLE "PortalProjectAccess" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalProjectAccess" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalStageVisibility" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalStageVisibility" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalProjectDocument" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalProjectDocument" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalConfiguration" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalConfiguration" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalDocumentAutoReleaseRule" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalDocumentAutoReleaseRule" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalSubcontractorAccess" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalSubcontractorAccess" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalNotificationPreference" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalNotificationPreference" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalUpload" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalUpload" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalComplaint" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalComplaint" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalActivityRoutingRule" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalActivityRoutingRule" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalServiceInboxItem" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalServiceInboxItem" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalDeletionRequest" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalDeletionRequest" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalGdprExportJob" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PortalGdprExportJob" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "Projekt" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "Projekt" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PipelineStage" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "PipelineStage" FORCE ROW LEVEL SECURITY;
|
|
ALTER TABLE "File" ENABLE ROW LEVEL SECURITY;
|
|
ALTER TABLE "File" FORCE ROW LEVEL SECURITY;
|
|
|
|
-- PortalStageVisibility is portal-wide configuration, but a portal identity
|
|
-- may only read configuration for pipelines represented by one of its own
|
|
-- active projects. The helper runs outside the nested RLS graph so the
|
|
-- PortalStageVisibility and PipelineStage policies do not recurse into each
|
|
-- other while still proving the full user -> access -> project -> pipeline
|
|
-- chain for the exact visibility row.
|
|
GRANT SELECT ON "PortalUser", "PortalProjectAccess", "PortalStageVisibility", "PortalProjectDocument", "PortalConfiguration", "PortalSubcontractorAccess", "PortalNotificationPreference", "PortalUpload", "PortalComplaint", "PortalDeletionRequest", "PortalGdprExportJob", "PipelineStage", "Projekt", "File", "FileEntityLink", "TenantSubscription" TO hivegrid_rls_definer;
|
|
GRANT INSERT, UPDATE ON "PortalNotificationPreference" TO hivegrid_rls_definer;
|
|
GRANT INSERT ON "PortalGdprExportJob" TO hivegrid_rls_definer;
|
|
GRANT INSERT ("id", "tenantId", "eventType", "payload") ON "OutboxEvent" TO hivegrid_rls_definer;
|
|
GRANT CREATE ON SCHEMA public TO hivegrid_rls_definer;
|
|
SET LOCAL ROLE hivegrid_rls_definer;
|
|
|
|
-- The project-access policy calls one non-recursive definer helper so the
|
|
-- visibility gate can prove Portal -> configuration -> project without the
|
|
-- PortalProjectAccess/Projekt policies recursively querying each other.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_can_read_project_access(p_access_id text)
|
|
RETURNS boolean
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
session_user = 'hivegrid_portal'
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."PortalProjectAccess" AS project_access
|
|
JOIN public."PortalUser" AS portal_user
|
|
ON portal_user."id" = project_access."portalUserId"
|
|
AND portal_user."tenantId" = project_access."tenantId"
|
|
AND portal_user."portalId" = project_access."portalId"
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = project_access."portalId"
|
|
AND portal."tenantId" = project_access."tenantId"
|
|
JOIN public."PortalConfiguration" AS configuration
|
|
ON configuration."portalId" = project_access."portalId"
|
|
AND configuration."tenantId" = project_access."tenantId"
|
|
JOIN public."Projekt" AS project
|
|
ON project."id" = project_access."projectId"
|
|
AND project."tenantId" = project_access."tenantId"
|
|
WHERE project_access."id" = p_access_id
|
|
AND project_access."tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND project_access."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND portal."isPublished" = true
|
|
AND project."archivedAt" IS NULL
|
|
AND NULLIF(btrim(configuration."imprintUrl"), '') IS NOT NULL
|
|
AND NULLIF(btrim(configuration."privacyUrl"), '') IS NOT NULL
|
|
AND cardinality(configuration."enabledProjectTypes") > 0
|
|
AND project."projekttyp" = ANY(configuration."enabledProjectTypes")
|
|
AND (
|
|
portal_user."kind" = 'customer'
|
|
OR (
|
|
portal_user."kind" = 'subcontractor'
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."PortalSubcontractorAccess" AS subcontractor
|
|
WHERE subcontractor."tenantId" = project_access."tenantId"
|
|
AND subcontractor."portalId" = project_access."portalId"
|
|
AND subcontractor."portalUserId" = project_access."portalUserId"
|
|
AND subcontractor."projectId" = project_access."projectId"
|
|
AND subcontractor."projectAccessId" = project_access."id"
|
|
AND subcontractor."active" = true
|
|
AND subcontractor."revokedAt" IS NULL
|
|
AND (subcontractor."validFrom" IS NULL OR subcontractor."validFrom" <= CURRENT_TIMESTAMP)
|
|
AND (subcontractor."validUntil" IS NULL OR subcontractor."validUntil" > CURRENT_TIMESTAMP)
|
|
)
|
|
)
|
|
)
|
|
)
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_can_read_project_access(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_can_read_project_access(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_can_read_project_access(text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_can_read_stage_visibility(p_visibility_id text)
|
|
RETURNS boolean
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
session_user = 'hivegrid_portal'
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."PortalStageVisibility" AS visibility
|
|
JOIN public."PipelineStage" AS stage
|
|
ON stage."id" = visibility."stageId"
|
|
AND stage."tenantId" = visibility."tenantId"
|
|
JOIN public."PortalProjectAccess" AS project_access
|
|
ON project_access."tenantId" = visibility."tenantId"
|
|
AND project_access."portalId" = visibility."portalId"
|
|
JOIN public."Projekt" AS project
|
|
ON project."id" = project_access."projectId"
|
|
AND project."tenantId" = project_access."tenantId"
|
|
AND project."pipelineId" = stage."pipelineId"
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = visibility."portalId"
|
|
AND portal."tenantId" = visibility."tenantId"
|
|
JOIN public."PortalConfiguration" AS configuration
|
|
ON configuration."portalId" = visibility."portalId"
|
|
AND configuration."tenantId" = visibility."tenantId"
|
|
JOIN public."PortalUser" AS portal_user
|
|
ON portal_user."id" = project_access."portalUserId"
|
|
AND portal_user."tenantId" = project_access."tenantId"
|
|
AND portal_user."portalId" = project_access."portalId"
|
|
WHERE visibility."id" = p_visibility_id
|
|
AND visibility."tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND project_access."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
AND project."archivedAt" IS NULL
|
|
AND stage."archivedAt" IS NULL
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND portal."isPublished" = true
|
|
AND NULLIF(btrim(configuration."imprintUrl"), '') IS NOT NULL
|
|
AND NULLIF(btrim(configuration."privacyUrl"), '') IS NOT NULL
|
|
AND cardinality(configuration."enabledProjectTypes") > 0
|
|
AND project."projekttyp" = ANY(configuration."enabledProjectTypes")
|
|
AND (
|
|
portal_user."kind" = 'customer'
|
|
OR (
|
|
portal_user."kind" = 'subcontractor'
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."PortalSubcontractorAccess" AS subcontractor
|
|
WHERE subcontractor."tenantId" = project_access."tenantId"
|
|
AND subcontractor."portalId" = project_access."portalId"
|
|
AND subcontractor."portalUserId" = project_access."portalUserId"
|
|
AND subcontractor."projectId" = project_access."projectId"
|
|
AND subcontractor."projectAccessId" = project_access."id"
|
|
AND subcontractor."active" = true
|
|
AND subcontractor."revokedAt" IS NULL
|
|
AND (subcontractor."validFrom" IS NULL OR subcontractor."validFrom" <= CURRENT_TIMESTAMP)
|
|
AND (subcontractor."validUntil" IS NULL OR subcontractor."validUntil" > CURRENT_TIMESTAMP)
|
|
AND stage."id" = ANY(subcontractor."visibleStageIds")
|
|
)
|
|
)
|
|
)
|
|
)
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_can_read_stage_visibility(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_can_read_stage_visibility(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_can_read_stage_visibility(text) TO hivegrid_portal;
|
|
|
|
-- A release row is not portal-readable until the exact linked object has
|
|
-- passed malware scanning. The helper proves the document -> file -> access
|
|
-- -> portal-user chain outside the mutually dependent File/document policies,
|
|
-- avoiding recursive RLS while keeping the capability bound to one document.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_can_read_project_document(p_document_id text)
|
|
RETURNS boolean
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
session_user = 'hivegrid_portal'
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."PortalProjectDocument" AS project_document
|
|
JOIN public."File" AS file
|
|
ON file."id" = project_document."fileId"
|
|
AND file."tenantId" = project_document."tenantId"
|
|
JOIN public."PortalProjectAccess" AS project_access
|
|
ON project_access."tenantId" = project_document."tenantId"
|
|
AND project_access."portalId" = project_document."portalId"
|
|
AND project_access."projectId" = project_document."projectId"
|
|
JOIN public."Projekt" AS project
|
|
ON project."id" = project_document."projectId"
|
|
AND project."tenantId" = project_document."tenantId"
|
|
JOIN public."PortalUser" AS portal_user
|
|
ON portal_user."id" = project_access."portalUserId"
|
|
AND portal_user."tenantId" = project_access."tenantId"
|
|
AND portal_user."portalId" = project_access."portalId"
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = project_document."portalId"
|
|
AND portal."tenantId" = project_document."tenantId"
|
|
JOIN public."PortalConfiguration" AS configuration
|
|
ON configuration."portalId" = project_document."portalId"
|
|
AND configuration."tenantId" = project_document."tenantId"
|
|
WHERE project_document."id" = p_document_id
|
|
AND project_document."tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND project_document."releasedAt" <= CURRENT_TIMESTAMP
|
|
AND project_document."revokedAt" IS NULL
|
|
AND file."scanStatus" = 'clean'
|
|
AND file."archivedAt" IS NULL
|
|
AND project."archivedAt" IS NULL
|
|
AND project_access."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND portal."isPublished" = true
|
|
AND NULLIF(btrim(configuration."imprintUrl"), '') IS NOT NULL
|
|
AND NULLIF(btrim(configuration."privacyUrl"), '') IS NOT NULL
|
|
AND cardinality(configuration."enabledProjectTypes") > 0
|
|
AND project."projekttyp" = ANY(configuration."enabledProjectTypes")
|
|
AND (
|
|
portal_user."kind" = 'customer'
|
|
OR (
|
|
portal_user."kind" = 'subcontractor'
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."PortalSubcontractorAccess" AS subcontractor
|
|
WHERE subcontractor."tenantId" = project_access."tenantId"
|
|
AND subcontractor."portalId" = project_access."portalId"
|
|
AND subcontractor."portalUserId" = project_access."portalUserId"
|
|
AND subcontractor."projectId" = project_access."projectId"
|
|
AND subcontractor."projectAccessId" = project_access."id"
|
|
AND subcontractor."active" = true
|
|
AND subcontractor."revokedAt" IS NULL
|
|
AND (subcontractor."validFrom" IS NULL OR subcontractor."validFrom" <= CURRENT_TIMESTAMP)
|
|
AND (subcontractor."validUntil" IS NULL OR subcontractor."validUntil" > CURRENT_TIMESTAMP)
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."FileEntityLink" AS file_link
|
|
WHERE file_link."tenantId" = project_document."tenantId"
|
|
AND file_link."fileId" = project_document."fileId"
|
|
AND file_link."entityType" = 'project'
|
|
AND file_link."entityId" = project_document."projectId"
|
|
AND file_link."linkRole" = ANY(subcontractor."visibleDocumentTypes")
|
|
)
|
|
)
|
|
)
|
|
)
|
|
)
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_can_read_project_document(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_can_read_project_document(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_can_read_project_document(text) TO hivegrid_portal;
|
|
|
|
-- Portal actions enter the canonical AuditEvent hash-chain through the same
|
|
-- transactional outbox used by the core runtime. The portal login never gets
|
|
-- OutboxEvent/AuditEvent table privileges: this capability derives tenant and
|
|
-- actor from transaction-local GUCs, accepts only reviewed actions, and
|
|
-- independently proves a document target before appending its fixed payload.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_append_audit(
|
|
p_action text,
|
|
p_target_id text,
|
|
p_request_id text
|
|
)
|
|
RETURNS text
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
tenant_id text := NULLIF(current_setting('app.tenant_id', true), '');
|
|
portal_user_id text := NULLIF(current_setting('app.portal_user_id', true), '');
|
|
normalized_request_id text := NULLIF(btrim(p_request_id), '');
|
|
target_type text;
|
|
outbox_id text;
|
|
privacy_acknowledged_at timestamp with time zone;
|
|
privacy_acknowledged_url text;
|
|
canonical_privacy_url text;
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_portal'
|
|
OR tenant_id IS NULL
|
|
OR portal_user_id IS NULL
|
|
OR NULLIF(current_setting('app.user_id', true), '') IS NOT NULL THEN
|
|
RAISE EXCEPTION 'Portal audit identity context is required' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
IF p_action NOT IN (
|
|
'customer_portal.user.password_login',
|
|
'customer_portal.user.magic_link_login',
|
|
'customer_portal.user.setup_completed',
|
|
'customer_portal.user.email_verified',
|
|
'customer_portal.user.password_reset',
|
|
'customer_portal.user.logged_out',
|
|
'customer_portal.document.downloaded',
|
|
'customer_portal.gdpr_export.requested',
|
|
'customer_portal.gdpr_export.downloaded',
|
|
'customer_portal.deletion.requested',
|
|
'customer_portal.deletion.cancelled'
|
|
) THEN
|
|
RAISE EXCEPTION 'Unsupported portal audit action' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
IF p_target_id IS NULL OR btrim(p_target_id) = '' OR length(p_target_id) > 191 THEN
|
|
RAISE EXCEPTION 'Invalid portal audit target' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
IF normalized_request_id IS NOT NULL
|
|
AND normalized_request_id !~ '^[A-Za-z0-9._:-]{1,128}$' THEN
|
|
normalized_request_id := NULL;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1
|
|
FROM public."PortalUser" AS portal_user
|
|
WHERE portal_user."id" = portal_user_id
|
|
AND portal_user."tenantId" = tenant_id
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
) THEN
|
|
RAISE EXCEPTION 'Portal audit actor is not active in the tenant context' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
IF p_action = 'customer_portal.document.downloaded' THEN
|
|
IF NOT public.hivegrid_portal_can_read_project_document(p_target_id) THEN
|
|
RAISE EXCEPTION 'Portal document audit target is not accessible' USING ERRCODE = '42501';
|
|
END IF;
|
|
target_type := 'PortalProjectDocument';
|
|
ELSE
|
|
IF p_target_id <> portal_user_id THEN
|
|
RAISE EXCEPTION 'Portal audit target does not match the actor' USING ERRCODE = '42501';
|
|
END IF;
|
|
target_type := 'PortalUser';
|
|
END IF;
|
|
|
|
IF p_action = 'customer_portal.user.setup_completed' THEN
|
|
SELECT
|
|
portal_user."privacyNoticeAcknowledgedAt" AT TIME ZONE 'UTC',
|
|
portal_user."privacyNoticeAcknowledgedUrl",
|
|
configuration."privacyUrl"
|
|
INTO privacy_acknowledged_at, privacy_acknowledged_url, canonical_privacy_url
|
|
FROM public."PortalUser" AS portal_user
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = portal_user."portalId"
|
|
AND portal."tenantId" = portal_user."tenantId"
|
|
JOIN public."PortalConfiguration" AS configuration
|
|
ON configuration."portalId" = portal."id"
|
|
AND configuration."tenantId" = portal."tenantId"
|
|
WHERE portal_user."id" = portal_user_id
|
|
AND portal_user."tenantId" = tenant_id
|
|
AND portal."isPublished" = true
|
|
LIMIT 1;
|
|
IF privacy_acknowledged_at IS NULL
|
|
OR privacy_acknowledged_at > CURRENT_TIMESTAMP
|
|
OR NULLIF(btrim(privacy_acknowledged_url), '') IS NULL
|
|
OR canonical_privacy_url IS NULL
|
|
OR canonical_privacy_url <> btrim(canonical_privacy_url)
|
|
OR length(canonical_privacy_url) NOT BETWEEN 9 AND 2048
|
|
OR canonical_privacy_url !~ '^https://[^[:space:]#/?@]+([/?][^[:space:]#]*)?$'
|
|
OR privacy_acknowledged_url IS DISTINCT FROM canonical_privacy_url THEN
|
|
RAISE EXCEPTION 'Portal setup privacy acknowledgement is missing or stale' USING ERRCODE = '42501';
|
|
END IF;
|
|
END IF;
|
|
|
|
outbox_id := gen_random_uuid()::text;
|
|
INSERT INTO public."OutboxEvent" ("id", "tenantId", "eventType", "payload")
|
|
VALUES (
|
|
outbox_id,
|
|
tenant_id,
|
|
'audit.event.create',
|
|
jsonb_build_object(
|
|
'tenantId', tenant_id,
|
|
'actorId', portal_user_id,
|
|
'actorType', 'portal_user',
|
|
'actorEmail', NULL,
|
|
'actorIp', NULL,
|
|
'actorUserAgent', NULL,
|
|
'action', p_action,
|
|
'targetType', target_type,
|
|
'targetId', p_target_id,
|
|
'requestId', normalized_request_id,
|
|
'sourceModule', 'customer_portal',
|
|
'outcome', 'success',
|
|
'dataSensitivity', 'internal',
|
|
'regulatoryScope', jsonb_build_array('gdpr', 'soc2'),
|
|
'metadata', CASE
|
|
WHEN p_action = 'customer_portal.user.setup_completed' THEN
|
|
jsonb_build_object(
|
|
'surface', 'customer_portal',
|
|
'privacyNoticeAcknowledgedAt', privacy_acknowledged_at,
|
|
'privacyNoticeUrl', privacy_acknowledged_url
|
|
)
|
|
ELSE jsonb_build_object('surface', 'customer_portal')
|
|
END,
|
|
'beforeDiff', NULL,
|
|
'afterDiff', NULL,
|
|
'summaryText', NULL
|
|
)
|
|
);
|
|
IF p_action = 'customer_portal.document.downloaded' THEN
|
|
PERFORM public.hivegrid_portal_record_inbox_event('download', NULL, p_target_id, NULL);
|
|
INSERT INTO public."OutboxEvent" ("id", "tenantId", "eventType", "payload", "dispatchKey", "priority")
|
|
VALUES (
|
|
gen_random_uuid()::text,
|
|
tenant_id,
|
|
'workflow.trigger.event',
|
|
jsonb_build_object(
|
|
'event', 'portal.document_downloaded',
|
|
'tenantId', tenant_id,
|
|
'portalUserId', portal_user_id,
|
|
'portalProjectDocumentId', p_target_id
|
|
),
|
|
'workflow-trigger:portal-document-download:' || portal_user_id || ':' || p_target_id || ':' || COALESCE(normalized_request_id, outbox_id),
|
|
100
|
|
);
|
|
END IF;
|
|
RETURN outbox_id;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_append_audit(text,text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_append_audit(text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_append_audit(text,text,text) TO hivegrid_portal;
|
|
|
|
-- Pre-auth setup denial auditing deliberately cannot resolve a consumed or
|
|
-- otherwise invalid token back to an identity. This capability therefore
|
|
-- accepts only the already trusted tenant/portal pair, re-proves that exact
|
|
-- published portal, and appends one fixed anonymous blocked event. It accepts
|
|
-- no token, email, IP, request headers, action, reason, or free-form metadata.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_append_setup_denial_audit(
|
|
p_tenant_id text,
|
|
p_portal_id text
|
|
)
|
|
RETURNS text
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
outbox_id text;
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_portal'
|
|
OR NULLIF(current_setting('app.tenant_id', true), '') IS NOT NULL
|
|
OR NULLIF(current_setting('app.portal_user_id', true), '') IS NOT NULL
|
|
OR NULLIF(current_setting('app.user_id', true), '') IS NOT NULL
|
|
OR p_tenant_id !~ '^[A-Za-z0-9_-]{1,191}$'
|
|
OR p_portal_id !~ '^[A-Za-z0-9_-]{1,191}$' THEN
|
|
RAISE EXCEPTION 'Portal pre-auth audit context is invalid' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1
|
|
FROM public."Portal" AS portal
|
|
JOIN public."Tenant" AS tenant
|
|
ON tenant."id" = portal."tenantId"
|
|
WHERE portal."id" = p_portal_id
|
|
AND portal."tenantId" = p_tenant_id
|
|
AND portal."isPublished" = true
|
|
AND tenant."id" = p_tenant_id
|
|
AND tenant."active" = true
|
|
) THEN
|
|
RAISE EXCEPTION 'Portal pre-auth audit target is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
outbox_id := gen_random_uuid()::text;
|
|
INSERT INTO public."OutboxEvent" ("id", "tenantId", "eventType", "payload")
|
|
VALUES (
|
|
outbox_id,
|
|
p_tenant_id,
|
|
'audit.event.create',
|
|
jsonb_build_object(
|
|
'tenantId', p_tenant_id,
|
|
'actorId', NULL,
|
|
'actorType', 'anonymous',
|
|
'actorEmail', NULL,
|
|
'actorIp', NULL,
|
|
'actorUserAgent', NULL,
|
|
'action', 'customer_portal.user.setup_capability_blocked',
|
|
'targetType', 'Portal',
|
|
'targetId', p_portal_id,
|
|
'requestId', NULL,
|
|
'sourceModule', 'customer_portal',
|
|
'outcome', 'blocked',
|
|
'dataSensitivity', 'internal',
|
|
'regulatoryScope', jsonb_build_array('gdpr', 'soc2'),
|
|
'metadata', jsonb_build_object(
|
|
'surface', 'customer_portal',
|
|
'reason', 'invalid_or_replayed_setup_capability'
|
|
),
|
|
'beforeDiff', NULL,
|
|
'afterDiff', NULL,
|
|
'summaryText', NULL
|
|
)
|
|
);
|
|
RETURN outbox_id;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_append_setup_denial_audit(text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_append_setup_denial_audit(text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_append_setup_denial_audit(text,text) TO hivegrid_portal;
|
|
|
|
RESET ROLE;
|
|
REVOKE CREATE ON SCHEMA public FROM hivegrid_rls_definer;
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_Portal_select" ON "Portal";
|
|
CREATE POLICY "hg_portal_Portal_select" ON "Portal"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM "PortalUser" AS portal_user
|
|
WHERE portal_user."id" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND portal_user."tenantId" = "Portal"."tenantId"
|
|
AND portal_user."portalId" = "Portal"."id"
|
|
AND portal_user."status" IN ('invited', 'active')
|
|
AND portal_user."archivedAt" IS NULL
|
|
)
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalUser_select" ON "PortalUser";
|
|
CREATE POLICY "hg_portal_PortalUser_select" ON "PortalUser"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "id" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "status" IN ('invited', 'active')
|
|
AND "archivedAt" IS NULL
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalUser_update" ON "PortalUser";
|
|
CREATE POLICY "hg_portal_PortalUser_update" ON "PortalUser"
|
|
FOR UPDATE TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "id" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "status" IN ('invited', 'active')
|
|
AND "archivedAt" IS NULL
|
|
)
|
|
WITH CHECK (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "id" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "status" IN ('invited', 'active')
|
|
AND "archivedAt" IS NULL
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalSession_select" ON "PortalSession";
|
|
CREATE POLICY "hg_portal_PortalSession_select" ON "PortalSession"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalSession_insert" ON "PortalSession";
|
|
CREATE POLICY "hg_portal_PortalSession_insert" ON "PortalSession"
|
|
FOR INSERT TO hivegrid_portal
|
|
WITH CHECK (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "revokedAt" IS NULL
|
|
AND NULLIF(btrim("origin"), '') IS NOT NULL
|
|
AND EXISTS (
|
|
SELECT 1 FROM "PortalUser" AS portal_user
|
|
WHERE portal_user."id" = "PortalSession"."portalUserId"
|
|
AND portal_user."tenantId" = "PortalSession"."tenantId"
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
)
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalSession_update" ON "PortalSession";
|
|
CREATE POLICY "hg_portal_PortalSession_update" ON "PortalSession"
|
|
FOR UPDATE TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
)
|
|
WITH CHECK (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalToken_select" ON "PortalToken";
|
|
CREATE POLICY "hg_portal_PortalToken_select" ON "PortalToken"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalToken_insert" ON "PortalToken";
|
|
CREATE POLICY "hg_portal_PortalToken_insert" ON "PortalToken"
|
|
FOR INSERT TO hivegrid_portal
|
|
WITH CHECK (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "consumedAt" IS NULL
|
|
AND "revokedAt" IS NULL
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalToken_update" ON "PortalToken";
|
|
CREATE POLICY "hg_portal_PortalToken_update" ON "PortalToken"
|
|
FOR UPDATE TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "consumedAt" IS NULL
|
|
AND "revokedAt" IS NULL
|
|
)
|
|
WITH CHECK (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalProjectAccess_select" ON "PortalProjectAccess";
|
|
CREATE POLICY "hg_portal_PortalProjectAccess_select" ON "PortalProjectAccess"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "active" = true
|
|
AND "revokedAt" IS NULL
|
|
AND public.hivegrid_portal_can_read_project_access("id")
|
|
AND EXISTS (
|
|
SELECT 1 FROM "PortalUser" AS portal_user
|
|
WHERE portal_user."id" = "PortalProjectAccess"."portalUserId"
|
|
AND portal_user."tenantId" = "PortalProjectAccess"."tenantId"
|
|
AND portal_user."portalId" = "PortalProjectAccess"."portalId"
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND (
|
|
portal_user."kind" = 'customer'
|
|
OR (
|
|
portal_user."kind" = 'subcontractor'
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM "PortalSubcontractorAccess" AS subcontractor
|
|
WHERE subcontractor."tenantId" = "PortalProjectAccess"."tenantId"
|
|
AND subcontractor."portalId" = "PortalProjectAccess"."portalId"
|
|
AND subcontractor."portalUserId" = "PortalProjectAccess"."portalUserId"
|
|
AND subcontractor."projectId" = "PortalProjectAccess"."projectId"
|
|
AND subcontractor."projectAccessId" = "PortalProjectAccess"."id"
|
|
AND subcontractor."active" = true
|
|
AND subcontractor."revokedAt" IS NULL
|
|
AND (subcontractor."validFrom" IS NULL OR subcontractor."validFrom" <= CURRENT_TIMESTAMP)
|
|
AND (subcontractor."validUntil" IS NULL OR subcontractor."validUntil" > CURRENT_TIMESTAMP)
|
|
)
|
|
)
|
|
)
|
|
)
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalStageVisibility_select" ON "PortalStageVisibility";
|
|
CREATE POLICY "hg_portal_PortalStageVisibility_select" ON "PortalStageVisibility"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "visible" = true
|
|
AND public.hivegrid_portal_can_read_stage_visibility("id")
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalProjectDocument_select" ON "PortalProjectDocument";
|
|
CREATE POLICY "hg_portal_PortalProjectDocument_select" ON "PortalProjectDocument"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "releasedAt" <= CURRENT_TIMESTAMP
|
|
AND "revokedAt" IS NULL
|
|
AND public.hivegrid_portal_can_read_project_document("id")
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalConfiguration_select" ON "PortalConfiguration";
|
|
CREATE POLICY "hg_portal_PortalConfiguration_select" ON "PortalConfiguration"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND EXISTS (
|
|
SELECT 1 FROM "PortalUser" AS portal_user
|
|
WHERE portal_user."id" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND portal_user."tenantId" = "PortalConfiguration"."tenantId"
|
|
AND portal_user."portalId" = "PortalConfiguration"."portalId"
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
)
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalSubcontractorAccess_select" ON "PortalSubcontractorAccess";
|
|
CREATE POLICY "hg_portal_PortalSubcontractorAccess_select" ON "PortalSubcontractorAccess"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "active" = true
|
|
AND "revokedAt" IS NULL
|
|
AND ("validFrom" IS NULL OR "validFrom" <= CURRENT_TIMESTAMP)
|
|
AND ("validUntil" IS NULL OR "validUntil" > CURRENT_TIMESTAMP)
|
|
AND EXISTS (
|
|
SELECT 1 FROM "PortalUser" AS portal_user
|
|
WHERE portal_user."id" = "PortalSubcontractorAccess"."portalUserId"
|
|
AND portal_user."tenantId" = "PortalSubcontractorAccess"."tenantId"
|
|
AND portal_user."portalId" = "PortalSubcontractorAccess"."portalId"
|
|
AND portal_user."kind" = 'subcontractor'
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
)
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalNotificationPreference_select" ON "PortalNotificationPreference";
|
|
CREATE POLICY "hg_portal_PortalNotificationPreference_select" ON "PortalNotificationPreference"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalUpload_select" ON "PortalUpload";
|
|
CREATE POLICY "hg_portal_PortalUpload_select" ON "PortalUpload"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM "PortalProjectAccess" AS project_access
|
|
JOIN "PortalUser" AS portal_user
|
|
ON portal_user."id" = project_access."portalUserId"
|
|
AND portal_user."tenantId" = project_access."tenantId"
|
|
AND portal_user."portalId" = project_access."portalId"
|
|
WHERE project_access."tenantId" = "PortalUpload"."tenantId"
|
|
AND project_access."portalUserId" = "PortalUpload"."portalUserId"
|
|
AND project_access."projectId" = "PortalUpload"."projectId"
|
|
AND project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND (
|
|
portal_user."kind" = 'customer'
|
|
OR (
|
|
portal_user."kind" = 'subcontractor'
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM "PortalSubcontractorAccess" AS subcontractor
|
|
WHERE subcontractor."tenantId" = project_access."tenantId"
|
|
AND subcontractor."portalId" = project_access."portalId"
|
|
AND subcontractor."portalUserId" = project_access."portalUserId"
|
|
AND subcontractor."projectId" = project_access."projectId"
|
|
AND subcontractor."projectAccessId" = project_access."id"
|
|
AND subcontractor."active" = true
|
|
AND subcontractor."revokedAt" IS NULL
|
|
AND (subcontractor."validFrom" IS NULL OR subcontractor."validFrom" <= CURRENT_TIMESTAMP)
|
|
AND (subcontractor."validUntil" IS NULL OR subcontractor."validUntil" > CURRENT_TIMESTAMP)
|
|
)
|
|
)
|
|
)
|
|
)
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalComplaint_select" ON "PortalComplaint";
|
|
CREATE POLICY "hg_portal_PortalComplaint_select" ON "PortalComplaint"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM "PortalUser" AS portal_user
|
|
WHERE portal_user."id" = "PortalComplaint"."portalUserId"
|
|
AND portal_user."tenantId" = "PortalComplaint"."tenantId"
|
|
AND portal_user."portalId" = "PortalComplaint"."portalId"
|
|
AND portal_user."kind" = 'customer'
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
)
|
|
AND EXISTS (
|
|
SELECT 1 FROM "PortalProjectAccess" AS project_access
|
|
WHERE project_access."tenantId" = "PortalComplaint"."tenantId"
|
|
AND project_access."portalUserId" = "PortalComplaint"."portalUserId"
|
|
AND project_access."projectId" = "PortalComplaint"."projectId"
|
|
AND project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
)
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalDeletionRequest_select" ON "PortalDeletionRequest";
|
|
CREATE POLICY "hg_portal_PortalDeletionRequest_select" ON "PortalDeletionRequest"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PortalGdprExportJob_select" ON "PortalGdprExportJob";
|
|
CREATE POLICY "hg_portal_PortalGdprExportJob_select" ON "PortalGdprExportJob"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND "portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_Projekt_select" ON "Projekt";
|
|
CREATE POLICY "hg_portal_Projekt_select" ON "Projekt"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "archivedAt" IS NULL
|
|
AND EXISTS (
|
|
SELECT 1 FROM "PortalProjectAccess" AS project_access
|
|
JOIN "PortalUser" AS portal_user
|
|
ON portal_user."id" = project_access."portalUserId"
|
|
AND portal_user."tenantId" = project_access."tenantId"
|
|
WHERE project_access."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND project_access."tenantId" = "Projekt"."tenantId"
|
|
AND project_access."projectId" = "Projekt"."id"
|
|
AND project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND (
|
|
portal_user."kind" = 'customer'
|
|
OR (
|
|
portal_user."kind" = 'subcontractor'
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM "PortalSubcontractorAccess" AS subcontractor
|
|
WHERE subcontractor."tenantId" = project_access."tenantId"
|
|
AND subcontractor."portalId" = project_access."portalId"
|
|
AND subcontractor."portalUserId" = project_access."portalUserId"
|
|
AND subcontractor."projectId" = project_access."projectId"
|
|
AND subcontractor."projectAccessId" = project_access."id"
|
|
AND subcontractor."active" = true
|
|
AND subcontractor."revokedAt" IS NULL
|
|
AND (subcontractor."validFrom" IS NULL OR subcontractor."validFrom" <= CURRENT_TIMESTAMP)
|
|
AND (subcontractor."validUntil" IS NULL OR subcontractor."validUntil" > CURRENT_TIMESTAMP)
|
|
)
|
|
)
|
|
)
|
|
)
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_PipelineStage_select" ON "PipelineStage";
|
|
CREATE POLICY "hg_portal_PipelineStage_select" ON "PipelineStage"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "archivedAt" IS NULL
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM "PortalStageVisibility" AS visibility
|
|
JOIN "PortalProjectAccess" AS project_access
|
|
ON project_access."portalId" = visibility."portalId"
|
|
AND project_access."tenantId" = visibility."tenantId"
|
|
JOIN "Projekt" AS project
|
|
ON project."id" = project_access."projectId"
|
|
AND project."tenantId" = project_access."tenantId"
|
|
WHERE visibility."stageId" = "PipelineStage"."id"
|
|
AND visibility."tenantId" = "PipelineStage"."tenantId"
|
|
AND visibility."visible" = true
|
|
AND public.hivegrid_portal_can_read_stage_visibility(visibility."id")
|
|
AND project_access."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
AND project."pipelineId" = "PipelineStage"."pipelineId"
|
|
AND project."archivedAt" IS NULL
|
|
)
|
|
);
|
|
|
|
DROP POLICY IF EXISTS "hg_portal_File_select" ON "File";
|
|
CREATE POLICY "hg_portal_File_select" ON "File"
|
|
FOR SELECT TO hivegrid_portal
|
|
USING (
|
|
"tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND "archivedAt" IS NULL
|
|
AND "scanStatus" = 'clean'
|
|
AND (
|
|
EXISTS (
|
|
SELECT 1
|
|
FROM "PortalProjectDocument" AS project_document
|
|
JOIN "PortalProjectAccess" AS project_access
|
|
ON project_access."portalId" = project_document."portalId"
|
|
AND project_access."projectId" = project_document."projectId"
|
|
AND project_access."tenantId" = project_document."tenantId"
|
|
WHERE project_document."fileId" = "File"."id"
|
|
AND project_document."tenantId" = "File"."tenantId"
|
|
AND project_document."releasedAt" <= CURRENT_TIMESTAMP
|
|
AND project_document."revokedAt" IS NULL
|
|
AND public.hivegrid_portal_can_read_project_document(project_document."id")
|
|
AND project_access."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
)
|
|
OR (
|
|
"createdByUserId" IS NULL
|
|
AND "createdByPortalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND "source" = 'customer_portal'
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM "PortalUpload" AS portal_upload
|
|
JOIN "PortalProjectAccess" AS project_access
|
|
ON project_access."tenantId" = portal_upload."tenantId"
|
|
AND project_access."portalUserId" = portal_upload."portalUserId"
|
|
AND project_access."projectId" = portal_upload."projectId"
|
|
WHERE portal_upload."fileId" = "File"."id"
|
|
AND portal_upload."tenantId" = "File"."tenantId"
|
|
AND portal_upload."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND portal_upload."status" = 'clean'
|
|
AND portal_upload."completedAt" IS NOT NULL
|
|
AND portal_upload."failedAt" IS NULL
|
|
AND project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
AND public.hivegrid_portal_can_read_project_access(project_access."id")
|
|
)
|
|
)
|
|
)
|
|
);
|
|
|
|
GRANT SELECT ("id", "tenantId", "portalId", "kind", "status", "archivedAt", "lastLoginAt", "lastActivityAt") ON "PortalUser" TO hivegrid_portal;
|
|
GRANT UPDATE ("updatedAt", "passwordHash", "status", "emailVerifiedAt", "privacyNoticeAcknowledgedAt", "privacyNoticeAcknowledgedUrl") ON "PortalUser" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "createdAt", "tenantId", "portalUserId", "expiresAt", "lastSeenAt", "revokedAt") ON "PortalSession" TO hivegrid_portal;
|
|
GRANT INSERT ("id", "createdAt", "updatedAt", "tenantId", "portalUserId", "tokenHash", "expiresAt", "lastSeenAt", "ipAddressHash", "userAgent", "origin") ON "PortalSession" TO hivegrid_portal;
|
|
GRANT UPDATE ("updatedAt", "expiresAt", "lastSeenAt", "revokedAt") ON "PortalSession" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "tenantId", "portalUserId", "purpose", "expiresAt", "consumedAt", "revokedAt", "requestedIpHash") ON "PortalToken" TO hivegrid_portal;
|
|
GRANT INSERT ("id", "createdAt", "tenantId", "portalUserId", "purpose", "tokenHash", "expiresAt", "requestedIpHash") ON "PortalToken" TO hivegrid_portal;
|
|
GRANT UPDATE ("consumedAt", "revokedAt") ON "PortalToken" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "tenantId", "portalId", "portalUserId", "projectId", "active", "revokedAt") ON "PortalProjectAccess" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "tenantId", "portalId", "stageId", "visible", "customerLabel") ON "PortalStageVisibility" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "tenantId", "portalId", "projectId", "fileId", "releasedAt", "revokedAt") ON "PortalProjectDocument" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "tenantId", "portalId", "lifecycleMode", "projectAutoCloseMonths", "inactivityDisableMonths", "enabledProjectTypes", "uploadMaxFiles", "uploadMaxFileSizeBytes", "statusEmailsEnabled", "welcomeMessage", "supportEmail", "supportPhone", "imprintUrl", "privacyUrl", "termsUrl") ON "PortalConfiguration" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "tenantId", "portalId", "portalUserId", "projectId", "projectAccessId", "roleLabel", "validFrom", "validUntil", "visibleStageIds", "visibleDocumentTypes", "canSeeOtherSubcontractors", "canUpload", "active", "revokedAt") ON "PortalSubcontractorAccess" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "tenantId", "portalUserId", "eventType", "emailEnabled", "mutedUntil") ON "PortalNotificationPreference" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "createdAt", "tenantId", "portalUserId", "projectId", "fileId", "category", "description", "status", "quotaBytes", "scanCompletedAt", "completedAt", "failedAt", "failureCode") ON "PortalUpload" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "createdAt", "tenantId", "portalUserId", "projectId", "formSubmissionId", "subject", "status", "resolvedAt") ON "PortalComplaint" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "createdAt", "tenantId", "portalUserId", "status", "requestedAt", "confirmedAt", "cancellableUntil", "cancelledAt", "completedAt", "failureCode") ON "PortalDeletionRequest" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "createdAt", "tenantId", "portalUserId", "status", "progressPercent", "resultExpiresAt", "downloadCount", "lastDownloadedAt", "processingStartedAt", "processingFinishedAt", "failureCode") ON "PortalGdprExportJob" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "tenantId", "updatedAt", "projektNummer", "projektname", "pipelineId", "stageId", "archivedAt") ON "Projekt" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "tenantId", "pipelineId", "name", "position", "archivedAt") ON "PipelineStage" TO hivegrid_portal;
|
|
GRANT SELECT ("id", "tenantId", "displayName", "mimeType", "sizeBytes", "scanStatus", "archivedAt") ON "File" TO hivegrid_portal;
|
|
|
|
GRANT SELECT ON "Tenant", "TenantSubscription", "TenantSubscriptionProduct", "TenantProductAcquisition", "SubscriptionProduct", "Portal", "PortalUser", "PortalSession", "PortalToken", "PortalNotificationPreference", "PortalGdprExportJob", "PortalDomainHostnameClaim", "PortalCustomDomain" TO hivegrid_rls_definer;
|
|
GRANT UPDATE ("requestedIpHash", "consumedAt") ON "PortalToken" TO hivegrid_rls_definer;
|
|
GRANT INSERT, UPDATE ON "PortalNotificationPreference" TO hivegrid_rls_definer;
|
|
GRANT INSERT ON "PortalGdprExportJob" TO hivegrid_rls_definer;
|
|
GRANT UPDATE ON "PortalGdprExportJob" TO hivegrid_rls_definer;
|
|
GRANT INSERT, UPDATE ON "PortalDeletionRequest" TO hivegrid_rls_definer;
|
|
GRANT SELECT ON "PortalProjectAccess", "PortalSubcontractorAccess", "PortalConfiguration", "Projekt", "PortalUpload", "FileUpload", "File", "FileEntityLink", "PortalComplaint", "Form", "FormSubmission", "PortalActivityRoutingRule", "PortalServiceInboxItem", "NotificationDelivery" TO hivegrid_rls_definer;
|
|
GRANT INSERT, UPDATE ON "PortalUpload", "FileUpload", "PortalServiceInboxItem" TO hivegrid_rls_definer;
|
|
GRANT SELECT, INSERT ON "Activity" TO hivegrid_rls_definer;
|
|
GRANT INSERT ON "File", "FileEntityLink", "FormSubmission", "NotificationDelivery" TO hivegrid_rls_definer;
|
|
GRANT INSERT, UPDATE ON "PortalComplaint" TO hivegrid_rls_definer;
|
|
GRANT INSERT ("dispatchKey", "priority") ON "OutboxEvent" TO hivegrid_rls_definer;
|
|
GRANT CREATE ON SCHEMA public TO hivegrid_rls_definer;
|
|
SET LOCAL ROLE hivegrid_rls_definer;
|
|
|
|
-- Private invoker helpers centralise the active portal-session and exact
|
|
-- project-access proofs used by the P26b mutation capabilities. They inherit
|
|
-- row_security=off only while called from one of the reviewed privileged
|
|
-- functions below and are never executable by the runtime login directly.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_require_active_context(p_write boolean)
|
|
RETURNS TABLE (
|
|
"tenantId" text,
|
|
"portalId" text,
|
|
"portalUserId" text,
|
|
"portalSessionId" text,
|
|
"portalUserKind" text,
|
|
"origin" text
|
|
)
|
|
LANGUAGE plpgsql
|
|
STABLE
|
|
AS $function$
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_portal'
|
|
OR NULLIF(current_setting('app.user_id', true), '') IS NOT NULL
|
|
OR NULLIF(current_setting('app.tenant_id', true), '') IS NULL
|
|
OR NULLIF(current_setting('app.portal_user_id', true), '') IS NULL
|
|
OR NULLIF(current_setting('app.portal_session_id', true), '') IS NULL THEN
|
|
RAISE EXCEPTION 'Active portal session context is required' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
RETURN QUERY
|
|
SELECT
|
|
portal_session."tenantId",
|
|
portal_user."portalId",
|
|
portal_user."id",
|
|
portal_session."id",
|
|
portal_user."kind"::text,
|
|
portal_session."origin"
|
|
FROM public."PortalSession" AS portal_session
|
|
JOIN public."PortalUser" AS portal_user
|
|
ON portal_user."id" = portal_session."portalUserId"
|
|
AND portal_user."tenantId" = portal_session."tenantId"
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = portal_user."portalId"
|
|
AND portal."tenantId" = portal_user."tenantId"
|
|
JOIN public."Tenant" AS tenant
|
|
ON tenant."id" = portal_user."tenantId"
|
|
WHERE portal_session."id" = NULLIF(current_setting('app.portal_session_id', true), '')
|
|
AND portal_session."tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND portal_session."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND portal_session."revokedAt" IS NULL
|
|
AND portal_session."expiresAt" > CURRENT_TIMESTAMP
|
|
AND COALESCE(portal_session."lastSeenAt", portal_session."createdAt") > CURRENT_TIMESTAMP - INTERVAL '7 days'
|
|
AND NULLIF(btrim(portal_session."origin"), '') IS NOT NULL
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND portal."isPublished" = true
|
|
AND tenant."active" = true
|
|
AND (
|
|
NOT p_write
|
|
OR NOT EXISTS (
|
|
SELECT 1
|
|
FROM public."TenantSubscription" AS subscription
|
|
WHERE subscription."tenantId" = portal_user."tenantId"
|
|
AND (lower(subscription."status") = 'frozen' OR subscription."frozenAt" IS NOT NULL)
|
|
)
|
|
)
|
|
LIMIT 1;
|
|
|
|
IF NOT FOUND THEN
|
|
RAISE EXCEPTION 'Portal session is inactive or write access is frozen' USING ERRCODE = '42501';
|
|
END IF;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_require_active_context(boolean) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_require_active_context(boolean) FROM PUBLIC, hivegrid_portal, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_require_project_access(
|
|
p_project_id text,
|
|
p_write boolean,
|
|
p_require_upload boolean,
|
|
p_customer_only boolean
|
|
)
|
|
RETURNS TABLE (
|
|
"tenantId" text,
|
|
"portalId" text,
|
|
"portalUserId" text,
|
|
"portalUserKind" text,
|
|
"origin" text,
|
|
"projectLeaderUserId" text
|
|
)
|
|
LANGUAGE plpgsql
|
|
STABLE
|
|
AS $function$
|
|
BEGIN
|
|
IF NULLIF(btrim(p_project_id), '') IS NULL OR length(p_project_id) > 191 THEN
|
|
RAISE EXCEPTION 'Invalid portal project identifier' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
RETURN QUERY
|
|
SELECT
|
|
context."tenantId",
|
|
context."portalId",
|
|
context."portalUserId",
|
|
context."portalUserKind",
|
|
context."origin",
|
|
project."projektleiterId"
|
|
FROM public.hivegrid_portal_require_active_context(p_write) AS context
|
|
JOIN public."PortalProjectAccess" AS project_access
|
|
ON project_access."tenantId" = context."tenantId"
|
|
AND project_access."portalId" = context."portalId"
|
|
AND project_access."portalUserId" = context."portalUserId"
|
|
AND project_access."projectId" = p_project_id
|
|
JOIN public."Projekt" AS project
|
|
ON project."id" = project_access."projectId"
|
|
AND project."tenantId" = project_access."tenantId"
|
|
JOIN public."PortalConfiguration" AS configuration
|
|
ON configuration."portalId" = context."portalId"
|
|
AND configuration."tenantId" = context."tenantId"
|
|
WHERE project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
AND project."archivedAt" IS NULL
|
|
AND NULLIF(btrim(configuration."imprintUrl"), '') IS NOT NULL
|
|
AND NULLIF(btrim(configuration."privacyUrl"), '') IS NOT NULL
|
|
AND cardinality(configuration."enabledProjectTypes") > 0
|
|
AND project."projekttyp" = ANY(configuration."enabledProjectTypes")
|
|
AND (NOT p_customer_only OR context."portalUserKind" = 'customer')
|
|
AND (
|
|
context."portalUserKind" = 'customer'
|
|
OR (
|
|
context."portalUserKind" = 'subcontractor'
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."PortalSubcontractorAccess" AS subcontractor
|
|
WHERE subcontractor."tenantId" = context."tenantId"
|
|
AND subcontractor."portalId" = context."portalId"
|
|
AND subcontractor."portalUserId" = context."portalUserId"
|
|
AND subcontractor."projectId" = p_project_id
|
|
AND subcontractor."projectAccessId" = project_access."id"
|
|
AND subcontractor."active" = true
|
|
AND subcontractor."revokedAt" IS NULL
|
|
AND (subcontractor."validFrom" IS NULL OR subcontractor."validFrom" <= CURRENT_TIMESTAMP)
|
|
AND (subcontractor."validUntil" IS NULL OR subcontractor."validUntil" > CURRENT_TIMESTAMP)
|
|
AND (NOT p_require_upload OR subcontractor."canUpload" = true)
|
|
)
|
|
)
|
|
)
|
|
LIMIT 1;
|
|
|
|
IF NOT FOUND THEN
|
|
RAISE EXCEPTION 'Portal project access is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_require_project_access(text,boolean,boolean,boolean) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_require_project_access(text,boolean,boolean,boolean) FROM PUBLIC, hivegrid_portal, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
|
|
-- Lifecycle reads are deliberately narrower than direct PortalUser table
|
|
-- access. Every resolver proves the exact active session GUC; passwordHash is
|
|
-- returned only to the server-side password verifier immediately before a
|
|
-- deletion request is created.
|
|
DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_lifecycle_profile();
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_lifecycle_profile()
|
|
RETURNS TABLE (
|
|
"email" text,
|
|
"firstName" text,
|
|
"lastName" text,
|
|
"phone" text,
|
|
"locale" text,
|
|
"createdAt" timestamp with time zone,
|
|
"lastLoginAt" timestamp with time zone,
|
|
"lastActivityAt" timestamp with time zone,
|
|
"privacyNoticeAcknowledgedAt" timestamp with time zone,
|
|
"privacyNoticeAcknowledgedUrl" text
|
|
)
|
|
LANGUAGE plpgsql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
context_record record;
|
|
BEGIN
|
|
SELECT * INTO context_record FROM public.hivegrid_portal_require_active_context(false);
|
|
RETURN QUERY
|
|
SELECT
|
|
portal_user."email",
|
|
portal_user."firstName",
|
|
portal_user."lastName",
|
|
portal_user."phone",
|
|
portal_user."locale",
|
|
portal_user."createdAt" AT TIME ZONE 'UTC',
|
|
portal_user."lastLoginAt" AT TIME ZONE 'UTC',
|
|
portal_user."lastActivityAt" AT TIME ZONE 'UTC',
|
|
portal_user."privacyNoticeAcknowledgedAt" AT TIME ZONE 'UTC',
|
|
portal_user."privacyNoticeAcknowledgedUrl"
|
|
FROM public."PortalUser" AS portal_user
|
|
WHERE portal_user."id" = context_record."portalUserId"
|
|
AND portal_user."tenantId" = context_record."tenantId"
|
|
LIMIT 1;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_lifecycle_profile() OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_lifecycle_profile() FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_lifecycle_profile() TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_deletion_password_hash()
|
|
RETURNS TABLE ("passwordHash" text)
|
|
LANGUAGE plpgsql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
context_record record;
|
|
BEGIN
|
|
SELECT * INTO context_record FROM public.hivegrid_portal_require_active_context(true);
|
|
RETURN QUERY
|
|
SELECT portal_user."passwordHash"
|
|
FROM public."PortalUser" AS portal_user
|
|
WHERE portal_user."id" = context_record."portalUserId"
|
|
AND portal_user."tenantId" = context_record."tenantId"
|
|
LIMIT 1;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_deletion_password_hash() OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_deletion_password_hash() FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_deletion_password_hash() TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_request_deletion(
|
|
p_idempotency_key text,
|
|
p_origin text
|
|
)
|
|
RETURNS TABLE (
|
|
"id" text,
|
|
"requestedAt" timestamp with time zone,
|
|
"cancellableUntil" timestamp with time zone
|
|
)
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
context_record record;
|
|
normalized_key text := NULLIF(btrim(p_idempotency_key), '');
|
|
normalized_settings_url text := NULLIF(btrim(p_origin), '');
|
|
deletion_id text;
|
|
portal_email text;
|
|
tenant_slug text;
|
|
requested_at timestamp with time zone := CURRENT_TIMESTAMP;
|
|
cancellable_until timestamp with time zone := CURRENT_TIMESTAMP + INTERVAL '24 hours';
|
|
mail_dispatch_key text;
|
|
BEGIN
|
|
SELECT * INTO context_record FROM public.hivegrid_portal_require_active_context(true);
|
|
IF normalized_key IS NULL OR normalized_key !~ '^[A-Za-z0-9._:-]{1,128}$' THEN
|
|
RAISE EXCEPTION 'Invalid portal deletion idempotency key' USING ERRCODE = '22023';
|
|
END IF;
|
|
SELECT tenant."slug" INTO tenant_slug
|
|
FROM public."Tenant" AS tenant
|
|
WHERE tenant."id" = context_record."tenantId";
|
|
IF normalized_settings_url IS NULL
|
|
OR tenant_slug IS NULL
|
|
OR normalized_settings_url NOT IN (
|
|
context_record."origin" || '/settings',
|
|
context_record."origin" || '/' || tenant_slug || '/settings'
|
|
) THEN
|
|
RAISE EXCEPTION 'Portal deletion settings URL does not match the active session' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
RETURN QUERY
|
|
SELECT
|
|
request."id",
|
|
request."requestedAt" AT TIME ZONE 'UTC',
|
|
request."cancellableUntil" AT TIME ZONE 'UTC'
|
|
FROM public."PortalDeletionRequest" AS request
|
|
WHERE request."tenantId" = context_record."tenantId"
|
|
AND request."portalUserId" = context_record."portalUserId"
|
|
AND request."idempotencyKey" = normalized_key
|
|
LIMIT 1;
|
|
IF FOUND THEN
|
|
RETURN;
|
|
END IF;
|
|
|
|
IF EXISTS (
|
|
SELECT 1
|
|
FROM public."PortalDeletionRequest" AS request
|
|
WHERE request."tenantId" = context_record."tenantId"
|
|
AND request."portalUserId" = context_record."portalUserId"
|
|
AND request."status" IN ('pending', 'processing')
|
|
) THEN
|
|
RETURN;
|
|
END IF;
|
|
|
|
SELECT portal_user."email" INTO portal_email
|
|
FROM public."PortalUser" AS portal_user
|
|
WHERE portal_user."id" = context_record."portalUserId"
|
|
AND portal_user."tenantId" = context_record."tenantId";
|
|
IF portal_email IS NULL THEN
|
|
RAISE EXCEPTION 'Portal deletion subject is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
deletion_id := gen_random_uuid()::text;
|
|
mail_dispatch_key := 'portal-deletion-confirmation:' || deletion_id;
|
|
INSERT INTO public."PortalDeletionRequest" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "portalId", "portalUserId", "status",
|
|
"requestedAt", "confirmedAt", "confirmationEmailSentAt", "cancellableUntil", "idempotencyKey"
|
|
) VALUES (
|
|
deletion_id, requested_at, requested_at, context_record."tenantId", context_record."portalId",
|
|
context_record."portalUserId", 'pending'::public."PortalDeletionRequestStatus", requested_at,
|
|
requested_at, requested_at, cancellable_until, normalized_key
|
|
);
|
|
|
|
INSERT INTO public."OutboxEvent" (
|
|
"id", "tenantId", "eventType", "payload", "dispatchKey", "priority"
|
|
) VALUES (
|
|
gen_random_uuid()::text,
|
|
context_record."tenantId",
|
|
'mail.transactional.send',
|
|
jsonb_build_object(
|
|
'tenantId', context_record."tenantId",
|
|
'to', jsonb_build_array(portal_email),
|
|
'subject', 'Kontolöschung bestätigt',
|
|
'text', 'Deine Kontolöschung ist bestätigt. Du kannst sie innerhalb von 24 Stunden in den Portal-Einstellungen widerrufen.',
|
|
'html', '<p>Deine Kontolöschung ist bestätigt. Du kannst sie innerhalb von 24 Stunden in den Portal-Einstellungen widerrufen.</p>',
|
|
'metadata', jsonb_build_object(
|
|
'source', 'portal-deletion-confirmation',
|
|
'portalUserId', context_record."portalUserId",
|
|
'deletionRequestId', deletion_id,
|
|
'cancelUrl', normalized_settings_url || '?deletion=' || deletion_id,
|
|
'idempotencyKey', mail_dispatch_key
|
|
)
|
|
),
|
|
mail_dispatch_key,
|
|
100
|
|
);
|
|
|
|
INSERT INTO public."OutboxEvent" (
|
|
"id", "tenantId", "eventType", "payload", "dispatchKey", "priority"
|
|
) VALUES (
|
|
gen_random_uuid()::text,
|
|
context_record."tenantId",
|
|
'workflow.trigger.event',
|
|
jsonb_build_object(
|
|
'event', 'portal.lifecycle_changed',
|
|
'data', jsonb_build_object(
|
|
'tenantId', context_record."tenantId",
|
|
'portalUserId', context_record."portalUserId",
|
|
'state', 'deletion_requested',
|
|
'deletionRequestId', deletion_id,
|
|
'cancellableUntil', cancellable_until
|
|
),
|
|
'userId', NULL
|
|
),
|
|
'workflow-trigger:portal-lifecycle:deletion-requested:' || deletion_id,
|
|
100
|
|
);
|
|
|
|
RETURN QUERY
|
|
SELECT
|
|
request."id",
|
|
request."requestedAt" AT TIME ZONE 'UTC',
|
|
request."cancellableUntil" AT TIME ZONE 'UTC'
|
|
FROM public."PortalDeletionRequest" AS request
|
|
WHERE request."id" = deletion_id
|
|
AND request."tenantId" = context_record."tenantId"
|
|
AND request."portalUserId" = context_record."portalUserId"
|
|
LIMIT 1;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_request_deletion(text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_request_deletion(text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_request_deletion(text,text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_cancel_deletion(p_request_id text)
|
|
RETURNS boolean
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
context_record record;
|
|
affected_rows integer := 0;
|
|
BEGIN
|
|
SELECT * INTO context_record FROM public.hivegrid_portal_require_active_context(true);
|
|
IF NULLIF(btrim(p_request_id), '') IS NULL OR length(p_request_id) > 191 THEN
|
|
RAISE EXCEPTION 'Invalid portal deletion request identifier' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
UPDATE public."PortalDeletionRequest" AS request
|
|
SET "status" = 'cancelled'::public."PortalDeletionRequestStatus",
|
|
"cancelledAt" = CURRENT_TIMESTAMP,
|
|
"updatedAt" = CURRENT_TIMESTAMP,
|
|
"failureCode" = NULL
|
|
WHERE request."id" = p_request_id
|
|
AND request."tenantId" = context_record."tenantId"
|
|
AND request."portalUserId" = context_record."portalUserId"
|
|
AND request."status" = 'pending'
|
|
AND request."cancellableUntil" > CURRENT_TIMESTAMP;
|
|
GET DIAGNOSTICS affected_rows = ROW_COUNT;
|
|
|
|
IF affected_rows = 1 THEN
|
|
INSERT INTO public."OutboxEvent" (
|
|
"id", "tenantId", "eventType", "payload", "dispatchKey", "priority"
|
|
) VALUES (
|
|
gen_random_uuid()::text,
|
|
context_record."tenantId",
|
|
'workflow.trigger.event',
|
|
jsonb_build_object(
|
|
'event', 'portal.lifecycle_changed',
|
|
'data', jsonb_build_object(
|
|
'tenantId', context_record."tenantId",
|
|
'portalUserId', context_record."portalUserId",
|
|
'state', 'deletion_cancelled',
|
|
'deletionRequestId', p_request_id
|
|
),
|
|
'userId', NULL
|
|
),
|
|
'workflow-trigger:portal-lifecycle:deletion-cancelled:' || p_request_id,
|
|
100
|
|
);
|
|
END IF;
|
|
RETURN affected_rows = 1;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_cancel_deletion(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_cancel_deletion(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_cancel_deletion(text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_record_gdpr_export_download(p_export_id text)
|
|
RETURNS TABLE (
|
|
"resultBucket" text,
|
|
"resultKey" text,
|
|
"resultSizeBytes" integer,
|
|
"resultExpiresAt" timestamp with time zone
|
|
)
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
context_record record;
|
|
BEGIN
|
|
SELECT * INTO context_record FROM public.hivegrid_portal_require_active_context(false);
|
|
IF NULLIF(btrim(p_export_id), '') IS NULL OR length(p_export_id) > 191 THEN
|
|
RAISE EXCEPTION 'Invalid portal export identifier' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
RETURN QUERY
|
|
UPDATE public."PortalGdprExportJob" AS job
|
|
SET "downloadCount" = job."downloadCount" + 1,
|
|
"lastDownloadedAt" = CURRENT_TIMESTAMP,
|
|
"updatedAt" = CURRENT_TIMESTAMP
|
|
WHERE job."id" = p_export_id
|
|
AND job."tenantId" = context_record."tenantId"
|
|
AND job."portalUserId" = context_record."portalUserId"
|
|
AND job."status" = 'ready'
|
|
AND job."resultExpiresAt" > CURRENT_TIMESTAMP
|
|
AND job."resultBucket" IS NOT NULL
|
|
AND job."resultKey" IS NOT NULL
|
|
RETURNING
|
|
job."resultBucket",
|
|
job."resultKey",
|
|
job."resultSizeBytes",
|
|
job."resultExpiresAt" AT TIME ZONE 'UTC';
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_record_gdpr_export_download(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_record_gdpr_export_download(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_record_gdpr_export_download(text) TO hivegrid_portal;
|
|
|
|
-- Emits exactly one automation trigger for a newly issued portal session.
|
|
-- The caller provides the reviewed semantic audit action rather than the
|
|
-- workflow event name; PostgreSQL maps setup separately and treats every
|
|
-- other session-producing capability as a login. Tenant, portal, user and
|
|
-- origin always come from the exact session row bound to the portal GUCs.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_emit_auth_event(p_session_id text, p_auth_action text)
|
|
RETURNS TABLE ("outboxId" text, "event" text)
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
tenant_id text := NULLIF(current_setting('app.tenant_id', true), '');
|
|
portal_user_id text := NULLIF(current_setting('app.portal_user_id', true), '');
|
|
workflow_event text;
|
|
outbox_id text;
|
|
session_record record;
|
|
BEGIN
|
|
IF session_user <> 'hivegrid_portal'
|
|
OR tenant_id IS NULL
|
|
OR portal_user_id IS NULL
|
|
OR NULLIF(current_setting('app.user_id', true), '') IS NOT NULL
|
|
OR p_session_id !~ '^[A-Za-z0-9_-]{1,191}$' THEN
|
|
RAISE EXCEPTION 'Portal auth-event identity context is required' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
workflow_event := CASE p_auth_action
|
|
WHEN 'customer_portal.user.setup_completed' THEN 'portal.setup_completed'
|
|
WHEN 'customer_portal.user.password_login' THEN 'portal.logged_in'
|
|
WHEN 'customer_portal.user.magic_link_login' THEN 'portal.logged_in'
|
|
WHEN 'customer_portal.user.email_verified' THEN 'portal.logged_in'
|
|
WHEN 'customer_portal.user.password_reset' THEN 'portal.logged_in'
|
|
ELSE NULL
|
|
END;
|
|
IF workflow_event IS NULL THEN
|
|
RAISE EXCEPTION 'Unsupported portal session auth action' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
SELECT
|
|
portal_session."id",
|
|
portal_user."portalId",
|
|
portal_user."emailVerifiedAt",
|
|
portal_session."origin",
|
|
portal_user."privacyNoticeAcknowledgedAt" AT TIME ZONE 'UTC' AS "privacyNoticeAcknowledgedAt",
|
|
portal_user."privacyNoticeAcknowledgedUrl" AS "privacyNoticeAcknowledgedUrl",
|
|
configuration."privacyUrl" AS "canonicalPrivacyUrl"
|
|
INTO session_record
|
|
FROM public."PortalSession" AS portal_session
|
|
JOIN public."PortalUser" AS portal_user
|
|
ON portal_user."id" = portal_session."portalUserId"
|
|
AND portal_user."tenantId" = portal_session."tenantId"
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = portal_user."portalId"
|
|
AND portal."tenantId" = portal_user."tenantId"
|
|
JOIN public."Tenant" AS tenant
|
|
ON tenant."id" = portal_user."tenantId"
|
|
LEFT JOIN public."PortalConfiguration" AS configuration
|
|
ON configuration."portalId" = portal."id"
|
|
AND configuration."tenantId" = portal."tenantId"
|
|
WHERE portal_session."id" = p_session_id
|
|
AND portal_session."tenantId" = tenant_id
|
|
AND portal_session."portalUserId" = portal_user_id
|
|
AND portal_session."createdAt" >= CURRENT_TIMESTAMP - INTERVAL '5 minutes'
|
|
AND portal_session."expiresAt" > CURRENT_TIMESTAMP
|
|
AND portal_session."revokedAt" IS NULL
|
|
AND NULLIF(btrim(portal_session."origin"), '') IS NOT NULL
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND portal."isPublished" = true
|
|
AND tenant."active" = true;
|
|
IF NOT FOUND THEN
|
|
RAISE EXCEPTION 'Portal auth-event session is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
IF workflow_event = 'portal.setup_completed' THEN
|
|
IF session_record."emailVerifiedAt" IS NULL THEN
|
|
RAISE EXCEPTION 'Portal setup event requires verified email' USING ERRCODE = '42501';
|
|
END IF;
|
|
IF session_record."privacyNoticeAcknowledgedAt" IS NULL
|
|
OR session_record."privacyNoticeAcknowledgedAt" > CURRENT_TIMESTAMP
|
|
OR NULLIF(btrim(session_record."privacyNoticeAcknowledgedUrl"), '') IS NULL
|
|
OR session_record."canonicalPrivacyUrl" IS NULL
|
|
OR session_record."canonicalPrivacyUrl" <> btrim(session_record."canonicalPrivacyUrl")
|
|
OR length(session_record."canonicalPrivacyUrl") NOT BETWEEN 9 AND 2048
|
|
OR session_record."canonicalPrivacyUrl" !~ '^https://[^[:space:]#/?@]+([/?][^[:space:]#]*)?$'
|
|
OR session_record."privacyNoticeAcknowledgedUrl" IS DISTINCT FROM session_record."canonicalPrivacyUrl" THEN
|
|
RAISE EXCEPTION 'Portal setup event requires a current privacy acknowledgement' USING ERRCODE = '42501';
|
|
END IF;
|
|
END IF;
|
|
|
|
outbox_id := gen_random_uuid()::text;
|
|
INSERT INTO public."OutboxEvent" ("id", "tenantId", "eventType", "payload", "dispatchKey", "priority")
|
|
VALUES (
|
|
outbox_id,
|
|
tenant_id,
|
|
'workflow.trigger.event',
|
|
jsonb_build_object(
|
|
'event', workflow_event,
|
|
'tenantId', tenant_id,
|
|
'portalId', session_record."portalId",
|
|
'portalUserId', portal_user_id,
|
|
'portalSessionId', p_session_id,
|
|
'origin', session_record."origin",
|
|
'authAction', p_auth_action
|
|
),
|
|
'workflow-trigger:portal-auth:' || p_session_id,
|
|
100
|
|
);
|
|
|
|
IF workflow_event = 'portal.logged_in' THEN
|
|
PERFORM public.hivegrid_portal_record_inbox_event('login', NULL, p_session_id, NULL);
|
|
END IF;
|
|
|
|
RETURN QUERY SELECT outbox_id, workflow_event;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_emit_auth_event(text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_emit_auth_event(text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_emit_auth_event(text,text) TO hivegrid_portal;
|
|
|
|
DROP FUNCTION IF EXISTS public.hivegrid_portal_reserve_upload(text,text,text,text,text,text,text,bigint,text,bigint);
|
|
DROP FUNCTION IF EXISTS public.hivegrid_portal_reserve_upload(text,text,text,text,text,text,text,bigint,text,text,bigint);
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_tenant_storage_capacity_bytes(p_tenant_id text)
|
|
RETURNS bigint
|
|
LANGUAGE plpgsql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
subscription_record record;
|
|
base_product_record record;
|
|
normalized_plan_code text;
|
|
office_seats integer;
|
|
field_seats integer;
|
|
included_office_seats integer;
|
|
included_field_seats integer;
|
|
included_storage_gb bigint;
|
|
storage_per_additional_seat_gb bigint;
|
|
storage_add_on_gb bigint;
|
|
unknown_storage_add_on_count integer;
|
|
BEGIN
|
|
IF session_user NOT IN ('hivegrid_app', 'hivegrid_worker', 'hivegrid_portal')
|
|
OR NULLIF(btrim(p_tenant_id), '') IS NULL THEN
|
|
RETURN 0;
|
|
END IF;
|
|
|
|
SELECT subscription.* INTO subscription_record
|
|
FROM public."TenantSubscription" AS subscription
|
|
WHERE subscription."tenantId" = p_tenant_id;
|
|
IF NOT FOUND
|
|
OR subscription_record."cancelledAt" IS NOT NULL
|
|
OR subscription_record."frozenAt" IS NOT NULL
|
|
OR subscription_record."status" NOT IN ('active', 'trial')
|
|
OR (
|
|
subscription_record."status" = 'trial'
|
|
AND subscription_record."trialEndsAt" IS NOT NULL
|
|
AND subscription_record."trialEndsAt" <= CURRENT_TIMESTAMP
|
|
) THEN
|
|
RETURN 0;
|
|
END IF;
|
|
|
|
SELECT
|
|
tenant_product."planCode",
|
|
tenant_product."seatQuantity",
|
|
tenant_product."officeSeatQuantity",
|
|
tenant_product."fieldSeatQuantity",
|
|
tenant_product."storageAddOnCodes",
|
|
tenant_product."quantity",
|
|
product."code",
|
|
product."lagoPlanCode"
|
|
INTO base_product_record
|
|
FROM public."TenantSubscriptionProduct" AS tenant_product
|
|
JOIN public."SubscriptionProduct" AS product
|
|
ON product."id" = tenant_product."subscriptionProductId"
|
|
WHERE tenant_product."tenantSubscriptionId" = subscription_record."id"
|
|
AND product."kind" = 'base_plan'
|
|
AND tenant_product."cancelledAt" IS NULL
|
|
AND (tenant_product."currentPeriodStart" IS NULL OR tenant_product."currentPeriodStart" <= CURRENT_TIMESTAMP)
|
|
AND (tenant_product."endsAt" IS NULL OR tenant_product."endsAt" > CURRENT_TIMESTAMP)
|
|
ORDER BY
|
|
(
|
|
COALESCE(tenant_product."planCode", product."code", product."lagoPlanCode")
|
|
= subscription_record."planCode"
|
|
) DESC,
|
|
tenant_product."createdAt" DESC
|
|
LIMIT 1;
|
|
IF NOT FOUND THEN
|
|
RETURN 0;
|
|
END IF;
|
|
|
|
normalized_plan_code := COALESCE(
|
|
base_product_record."planCode",
|
|
base_product_record."code",
|
|
base_product_record."lagoPlanCode",
|
|
subscription_record."planCode"
|
|
);
|
|
IF normalized_plan_code = 'starter' THEN
|
|
included_office_seats := 2;
|
|
included_field_seats := 5;
|
|
included_storage_gb := 100;
|
|
storage_per_additional_seat_gb := 10;
|
|
ELSIF normalized_plan_code = 'pro' THEN
|
|
included_office_seats := 5;
|
|
included_field_seats := 15;
|
|
included_storage_gb := 500;
|
|
storage_per_additional_seat_gb := 20;
|
|
ELSIF normalized_plan_code = 'business' THEN
|
|
included_office_seats := 10;
|
|
included_field_seats := 30;
|
|
included_storage_gb := 2000;
|
|
storage_per_additional_seat_gb := 40;
|
|
ELSE
|
|
RETURN 0;
|
|
END IF;
|
|
|
|
office_seats := COALESCE(base_product_record."officeSeatQuantity", subscription_record."officeSeatQuantity", 0);
|
|
field_seats := COALESCE(base_product_record."fieldSeatQuantity", subscription_record."fieldSeatQuantity", 0);
|
|
IF office_seats = 0 AND field_seats = 0 THEN
|
|
office_seats := GREATEST(
|
|
1,
|
|
COALESCE(base_product_record."seatQuantity", base_product_record."quantity", subscription_record."seatQuantity", 1)
|
|
);
|
|
END IF;
|
|
IF office_seats < 0 OR field_seats < 0 OR office_seats > 10000 OR field_seats > 10000 THEN
|
|
RETURN 0;
|
|
END IF;
|
|
|
|
WITH storage_codes AS (
|
|
SELECT DISTINCT code
|
|
FROM unnest(
|
|
COALESCE(subscription_record."storageAddOnCodes", ARRAY[]::text[])
|
|
|| COALESCE(base_product_record."storageAddOnCodes", ARRAY[]::text[])
|
|
|| COALESCE(ARRAY(
|
|
SELECT product."code"
|
|
FROM public."TenantSubscriptionProduct" AS tenant_product
|
|
JOIN public."SubscriptionProduct" AS product
|
|
ON product."id" = tenant_product."subscriptionProductId"
|
|
WHERE tenant_product."tenantSubscriptionId" = subscription_record."id"
|
|
AND product."kind" = 'recurring_add_on'
|
|
AND product."code" LIKE 'storage\_%' ESCAPE '\'
|
|
AND tenant_product."cancelledAt" IS NULL
|
|
AND (tenant_product."currentPeriodStart" IS NULL OR tenant_product."currentPeriodStart" <= CURRENT_TIMESTAMP)
|
|
AND (tenant_product."endsAt" IS NULL OR tenant_product."endsAt" > CURRENT_TIMESTAMP)
|
|
), ARRAY[]::text[])
|
|
) AS code
|
|
)
|
|
SELECT
|
|
COALESCE(sum(CASE code
|
|
WHEN 'storage_100gb' THEN 100
|
|
WHEN 'storage_500gb' THEN 500
|
|
WHEN 'storage_1tb' THEN 1000
|
|
WHEN 'storage_5tb' THEN 5000
|
|
ELSE 0
|
|
END), 0),
|
|
count(*) FILTER (WHERE code NOT IN ('storage_100gb', 'storage_500gb', 'storage_1tb', 'storage_5tb'))
|
|
INTO storage_add_on_gb, unknown_storage_add_on_count
|
|
FROM storage_codes;
|
|
IF unknown_storage_add_on_count > 0 THEN
|
|
RETURN 0;
|
|
END IF;
|
|
|
|
RETURN (
|
|
included_storage_gb
|
|
+ (
|
|
GREATEST(0, office_seats - included_office_seats)
|
|
+ GREATEST(0, field_seats - included_field_seats)
|
|
) * storage_per_additional_seat_gb
|
|
+ storage_add_on_gb
|
|
) * 1073741824;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_tenant_storage_capacity_bytes(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_tenant_storage_capacity_bytes(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_portal, hivegrid_authentik_jit;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_reserve_upload(
|
|
p_upload_id text,
|
|
p_file_upload_id text,
|
|
p_file_id text,
|
|
p_file_entity_link_id text,
|
|
p_project_id text,
|
|
p_filename text,
|
|
p_mime_type text,
|
|
p_size_bytes bigint,
|
|
p_checksum_sha256 text,
|
|
p_idempotency_key text,
|
|
p_quota_limit_bytes bigint
|
|
)
|
|
RETURNS TABLE (
|
|
"uploadId" text,
|
|
"fileUploadId" text,
|
|
"fileId" text,
|
|
"fileEntityLinkId" text,
|
|
"projectLeaderUserId" text,
|
|
"alreadyCompleted" boolean,
|
|
"effectsCompleted" boolean
|
|
)
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
access_record record;
|
|
normalized_mime text := lower(btrim(p_mime_type));
|
|
normalized_key text := NULLIF(btrim(p_idempotency_key), '');
|
|
key_prefix text;
|
|
configured_max_files integer;
|
|
configured_max_bytes integer;
|
|
used_and_reserved_bytes bigint;
|
|
commercial_quota_limit_bytes bigint;
|
|
existing_record record;
|
|
BEGIN
|
|
SELECT * INTO access_record
|
|
FROM public.hivegrid_portal_require_project_access(p_project_id, true, true, false);
|
|
|
|
IF p_upload_id !~ '^[A-Za-z0-9_-]{1,191}$'
|
|
OR p_file_upload_id !~ '^[A-Za-z0-9_-]{1,191}$'
|
|
OR p_file_id !~ '^[A-Za-z0-9_-]{1,191}$'
|
|
OR p_file_entity_link_id !~ '^[A-Za-z0-9_-]{1,191}$'
|
|
OR normalized_key IS NULL
|
|
OR normalized_key !~ '^[A-Za-z0-9._:-]{1,128}$'
|
|
OR NULLIF(btrim(p_filename), '') IS NULL
|
|
OR length(p_filename) > 255
|
|
OR p_filename ~ '[[:cntrl:]]'
|
|
OR p_filename ~ '\.\.[/\\]'
|
|
OR p_size_bytes < 1
|
|
OR p_size_bytes > 104857600
|
|
OR p_checksum_sha256 !~ '^[0-9a-f]{64}$'
|
|
OR p_quota_limit_bytes < p_size_bytes
|
|
OR p_quota_limit_bytes > 1125899906842624 THEN
|
|
RAISE EXCEPTION 'Invalid portal upload reservation' USING ERRCODE = '22023';
|
|
END IF;
|
|
IF normalized_mime NOT IN (
|
|
'image/png', 'image/jpeg', 'image/webp', 'image/heic', 'image/heif', 'application/pdf',
|
|
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
|
|
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
|
|
'audio/mpeg', 'audio/wav', 'audio/x-wav', 'audio/ogg', 'audio/mp4', 'audio/aac', 'audio/flac'
|
|
) THEN
|
|
RAISE EXCEPTION 'Unsupported portal upload type' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
SELECT configuration."uploadMaxFiles", configuration."uploadMaxFileSizeBytes"
|
|
INTO configured_max_files, configured_max_bytes
|
|
FROM public."PortalConfiguration" AS configuration
|
|
WHERE configuration."tenantId" = access_record."tenantId"
|
|
AND configuration."portalId" = access_record."portalId";
|
|
IF configured_max_files < 1 OR configured_max_files > 10
|
|
OR configured_max_bytes < 1 OR configured_max_bytes > 104857600
|
|
OR p_size_bytes > configured_max_bytes THEN
|
|
RAISE EXCEPTION 'Portal upload exceeds configured limits' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
PERFORM pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended(access_record."tenantId", 26026));
|
|
commercial_quota_limit_bytes := public.hivegrid_portal_tenant_storage_capacity_bytes(access_record."tenantId");
|
|
IF commercial_quota_limit_bytes < p_size_bytes THEN
|
|
RAISE EXCEPTION 'Portal upload quota exceeded' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
SELECT upload."id", upload."fileUploadId", upload."fileId", upload."fileEntityLinkId", upload."projectId", upload."portalUserId",
|
|
upload."quotaBytes", upload."requestChecksumSha256", upload."status", upload."completedAt", upload."effectsCompletedAt",
|
|
file_upload."createdByUserId", file_upload."createdByPortalUserId",
|
|
file_upload."originalFilename", file_upload."mimeType", file_upload."totalSizeBytes"
|
|
INTO existing_record
|
|
FROM public."PortalUpload" AS upload
|
|
LEFT JOIN public."FileUpload" AS file_upload
|
|
ON file_upload."id" = upload."fileUploadId"
|
|
AND file_upload."tenantId" = upload."tenantId"
|
|
WHERE upload."tenantId" = access_record."tenantId"
|
|
AND upload."idempotencyKey" = normalized_key;
|
|
IF FOUND THEN
|
|
IF existing_record."portalUserId" <> access_record."portalUserId"
|
|
OR existing_record."projectId" <> p_project_id
|
|
OR existing_record."quotaBytes" <> p_size_bytes
|
|
OR existing_record."requestChecksumSha256" IS DISTINCT FROM p_checksum_sha256
|
|
OR existing_record."createdByUserId" IS NOT NULL
|
|
OR existing_record."createdByPortalUserId" <> access_record."portalUserId"
|
|
OR existing_record."originalFilename" <> btrim(p_filename)
|
|
OR lower(existing_record."mimeType") <> normalized_mime
|
|
OR existing_record."totalSizeBytes" <> p_size_bytes
|
|
OR existing_record."fileUploadId" IS NULL OR existing_record."fileId" IS NULL OR existing_record."fileEntityLinkId" IS NULL
|
|
OR existing_record."status" NOT IN ('reserved', 'uploading', 'scanning', 'clean')
|
|
OR (existing_record."status" = 'clean' AND existing_record."completedAt" IS NULL) THEN
|
|
RAISE EXCEPTION 'Portal upload idempotency collision' USING ERRCODE = '23505';
|
|
END IF;
|
|
RETURN QUERY SELECT existing_record."id", existing_record."fileUploadId", existing_record."fileId",
|
|
existing_record."fileEntityLinkId", access_record."projectLeaderUserId", existing_record."status" = 'clean',
|
|
existing_record."effectsCompletedAt" IS NOT NULL;
|
|
RETURN;
|
|
END IF;
|
|
|
|
key_prefix := regexp_replace(normalized_key, ':[0-9]+$', '');
|
|
IF normalized_key ~ ':[0-9]+$'
|
|
AND split_part(normalized_key, ':', array_length(string_to_array(normalized_key, ':'), 1))::integer >= configured_max_files THEN
|
|
RAISE EXCEPTION 'Portal upload file-count limit exceeded' USING ERRCODE = '22023';
|
|
END IF;
|
|
IF (
|
|
SELECT count(*)
|
|
FROM public."PortalUpload" AS upload
|
|
WHERE upload."tenantId" = access_record."tenantId"
|
|
AND upload."portalUserId" = access_record."portalUserId"
|
|
AND regexp_replace(upload."idempotencyKey", ':[0-9]+$', '') = key_prefix
|
|
) >= configured_max_files THEN
|
|
RAISE EXCEPTION 'Portal upload file-count limit exceeded' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
SELECT
|
|
COALESCE((
|
|
SELECT sum(file."sizeBytes"::bigint)
|
|
FROM public."File" AS file
|
|
WHERE file."tenantId" = access_record."tenantId"
|
|
), 0)
|
|
+ COALESCE((
|
|
SELECT sum(file_upload."totalSizeBytes"::bigint)
|
|
FROM public."FileUpload" AS file_upload
|
|
WHERE file_upload."tenantId" = access_record."tenantId"
|
|
AND file_upload."status" = 'in_progress'
|
|
AND file_upload."expiresAt" > CURRENT_TIMESTAMP
|
|
), 0)
|
|
INTO used_and_reserved_bytes;
|
|
IF used_and_reserved_bytes + p_size_bytes > LEAST(p_quota_limit_bytes, commercial_quota_limit_bytes) THEN
|
|
RAISE EXCEPTION 'Portal upload quota exceeded' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
INSERT INTO public."FileUpload" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "createdByUserId", "createdByPortalUserId",
|
|
"originalFilename", "totalSizeBytes", "mimeType", "totalChunks", "receivedChunks", "status", "targetFileId", "expiresAt"
|
|
) VALUES (
|
|
p_file_upload_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, access_record."tenantId", NULL, access_record."portalUserId",
|
|
btrim(p_filename), p_size_bytes::integer, normalized_mime, 1, 0, 'in_progress', p_file_id, CURRENT_TIMESTAMP + INTERVAL '24 hours'
|
|
);
|
|
INSERT INTO public."PortalUpload" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "portalId", "portalUserId", "projectId", "fileUploadId", "fileId",
|
|
"fileEntityLinkId", "category", "status", "quotaBytes", "requestChecksumSha256", "idempotencyKey"
|
|
) VALUES (
|
|
p_upload_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, access_record."tenantId", access_record."portalId", access_record."portalUserId",
|
|
p_project_id, p_file_upload_id, p_file_id, p_file_entity_link_id, 'attachment', 'reserved', p_size_bytes::integer, p_checksum_sha256, normalized_key
|
|
);
|
|
|
|
RETURN QUERY SELECT p_upload_id, p_file_upload_id, p_file_id, p_file_entity_link_id, access_record."projectLeaderUserId", false, false;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_reserve_upload(text,text,text,text,text,text,text,bigint,text,text,bigint) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_reserve_upload(text,text,text,text,text,text,text,bigint,text,text,bigint) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_reserve_upload(text,text,text,text,text,text,text,bigint,text,text,bigint) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_complete_upload(
|
|
p_upload_id text,
|
|
p_file_upload_id text,
|
|
p_file_id text,
|
|
p_file_entity_link_id text,
|
|
p_project_id text,
|
|
p_filename text,
|
|
p_mime_type text,
|
|
p_size_bytes bigint,
|
|
p_storage_key text,
|
|
p_checksum_sha256 text
|
|
)
|
|
RETURNS TABLE ("completed" boolean)
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
access_record record;
|
|
upload_record record;
|
|
normalized_mime text := lower(btrim(p_mime_type));
|
|
BEGIN
|
|
SELECT * INTO access_record
|
|
FROM public.hivegrid_portal_require_project_access(p_project_id, true, true, false);
|
|
IF NULLIF(btrim(p_filename), '') IS NULL OR length(p_filename) > 255 OR p_filename ~ '[[:cntrl:]]'
|
|
OR p_size_bytes < 1 OR p_size_bytes > 104857600
|
|
OR NULLIF(btrim(p_storage_key), '') IS NULL OR length(p_storage_key) > 1024 OR p_storage_key ~ '[[:cntrl:]]'
|
|
OR p_checksum_sha256 !~ '^[0-9a-f]{64}$' THEN
|
|
RAISE EXCEPTION 'Invalid portal upload completion' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
SELECT upload.* INTO upload_record
|
|
FROM public."PortalUpload" AS upload
|
|
WHERE upload."id" = p_upload_id
|
|
AND upload."tenantId" = access_record."tenantId"
|
|
AND upload."portalId" = access_record."portalId"
|
|
AND upload."portalUserId" = access_record."portalUserId"
|
|
AND upload."projectId" = p_project_id
|
|
AND upload."fileUploadId" = p_file_upload_id
|
|
AND upload."fileId" = p_file_id
|
|
AND upload."fileEntityLinkId" = p_file_entity_link_id
|
|
FOR UPDATE;
|
|
IF NOT FOUND THEN
|
|
RAISE EXCEPTION 'Portal upload reservation was not found' USING ERRCODE = '42501';
|
|
END IF;
|
|
IF upload_record."status" = 'clean' THEN
|
|
IF upload_record."requestChecksumSha256" IS DISTINCT FROM p_checksum_sha256 OR NOT EXISTS (
|
|
SELECT 1
|
|
FROM public."File" AS file
|
|
WHERE file."id" = p_file_id
|
|
AND file."tenantId" = access_record."tenantId"
|
|
AND file."createdByUserId" IS NULL
|
|
AND file."createdByPortalUserId" = access_record."portalUserId"
|
|
AND file."displayName" = btrim(p_filename)
|
|
AND lower(file."mimeType") = normalized_mime
|
|
AND file."sizeBytes" = p_size_bytes
|
|
AND file."storageKey" = btrim(p_storage_key)
|
|
AND file."checksumSha256" = p_checksum_sha256
|
|
AND file."scanStatus" = 'clean'
|
|
AND file."source" = 'customer_portal'
|
|
) THEN
|
|
RAISE EXCEPTION 'Portal upload idempotency collision' USING ERRCODE = '23505';
|
|
END IF;
|
|
RETURN QUERY SELECT true;
|
|
RETURN;
|
|
END IF;
|
|
IF upload_record."status" <> 'reserved' OR upload_record."quotaBytes" <> p_size_bytes
|
|
OR upload_record."requestChecksumSha256" IS DISTINCT FROM p_checksum_sha256 THEN
|
|
RAISE EXCEPTION 'Portal upload reservation is not completable' USING ERRCODE = '55000';
|
|
END IF;
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM public."FileUpload" AS file_upload
|
|
WHERE file_upload."id" = p_file_upload_id
|
|
AND file_upload."tenantId" = access_record."tenantId"
|
|
AND file_upload."createdByUserId" IS NULL
|
|
AND file_upload."createdByPortalUserId" = access_record."portalUserId"
|
|
AND file_upload."targetFileId" = p_file_id
|
|
AND file_upload."status" = 'in_progress'
|
|
AND file_upload."originalFilename" = btrim(p_filename)
|
|
AND lower(file_upload."mimeType") = normalized_mime
|
|
AND file_upload."totalSizeBytes" = p_size_bytes
|
|
) THEN
|
|
RAISE EXCEPTION 'Portal file upload actor contract failed' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
INSERT INTO public."File" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "createdByUserId", "createdByPortalUserId", "displayName", "mimeType",
|
|
"sizeBytes", "storageKey", "checksumSha256", "previewStatus", "scanStatus", "source"
|
|
) VALUES (
|
|
p_file_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, access_record."tenantId", NULL, access_record."portalUserId", btrim(p_filename),
|
|
normalized_mime, p_size_bytes::integer, btrim(p_storage_key), p_checksum_sha256, 'pending', 'clean', 'customer_portal'
|
|
);
|
|
INSERT INTO public."FileEntityLink" (
|
|
"id", "createdAt", "tenantId", "createdByUserId", "createdByPortalUserId", "fileId", "entityType", "entityId", "linkRole"
|
|
) VALUES (
|
|
p_file_entity_link_id, CURRENT_TIMESTAMP, access_record."tenantId", NULL, access_record."portalUserId", p_file_id, 'project', p_project_id, 'customer_portal_upload'
|
|
);
|
|
UPDATE public."FileUpload"
|
|
SET "updatedAt" = CURRENT_TIMESTAMP, "receivedChunks" = 1, "status" = 'completed', "targetFileId" = p_file_id
|
|
WHERE "id" = p_file_upload_id AND "tenantId" = access_record."tenantId";
|
|
UPDATE public."PortalUpload"
|
|
SET "updatedAt" = CURRENT_TIMESTAMP, "status" = 'clean', "scanCompletedAt" = CURRENT_TIMESTAMP,
|
|
"completedAt" = CURRENT_TIMESTAMP, "failedAt" = NULL, "failureCode" = NULL
|
|
WHERE "id" = p_upload_id AND "tenantId" = access_record."tenantId";
|
|
|
|
INSERT INTO public."OutboxEvent" ("id", "tenantId", "eventType", "payload", "dispatchKey", "priority")
|
|
VALUES (
|
|
gen_random_uuid()::text,
|
|
access_record."tenantId",
|
|
'workflow.trigger.event',
|
|
jsonb_build_object(
|
|
'event', 'portal.upload_completed',
|
|
'tenantId', access_record."tenantId",
|
|
'portalId', access_record."portalId",
|
|
'portalUserId', access_record."portalUserId",
|
|
'projectId', p_project_id,
|
|
'uploadId', p_upload_id,
|
|
'fileId', p_file_id
|
|
),
|
|
'workflow-trigger:portal-upload:' || p_upload_id || ':completed',
|
|
100
|
|
);
|
|
|
|
RETURN QUERY SELECT true;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_complete_upload(text,text,text,text,text,text,text,bigint,text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_complete_upload(text,text,text,text,text,text,text,bigint,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_complete_upload(text,text,text,text,text,text,text,bigint,text,text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_fail_upload(p_upload_id text, p_failure_code text)
|
|
RETURNS boolean
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
context_record record;
|
|
affected integer;
|
|
BEGIN
|
|
SELECT * INTO context_record FROM public.hivegrid_portal_require_active_context(true);
|
|
IF p_failure_code NOT IN ('QUOTA_EXCEEDED', 'SCAN_REJECTED', 'STORAGE_FAILED', 'FILE_TYPE_BLOCKED', 'FILE_TOO_LARGE') THEN
|
|
RAISE EXCEPTION 'Unsupported portal upload failure code' USING ERRCODE = '22023';
|
|
END IF;
|
|
UPDATE public."FileUpload" AS file_upload
|
|
SET "updatedAt" = CURRENT_TIMESTAMP, "status" = 'failed', "failureReason" = p_failure_code
|
|
FROM public."PortalUpload" AS upload
|
|
WHERE upload."id" = p_upload_id
|
|
AND upload."tenantId" = context_record."tenantId"
|
|
AND upload."portalId" = context_record."portalId"
|
|
AND upload."portalUserId" = context_record."portalUserId"
|
|
AND upload."status" IN ('reserved', 'uploading', 'scanning')
|
|
AND file_upload."id" = upload."fileUploadId"
|
|
AND file_upload."tenantId" = upload."tenantId";
|
|
UPDATE public."PortalUpload"
|
|
SET "updatedAt" = CURRENT_TIMESTAMP, "status" = 'failed', "failedAt" = CURRENT_TIMESTAMP, "failureCode" = p_failure_code
|
|
WHERE "id" = p_upload_id
|
|
AND "tenantId" = context_record."tenantId"
|
|
AND "portalId" = context_record."portalId"
|
|
AND "portalUserId" = context_record."portalUserId"
|
|
AND "status" IN ('reserved', 'uploading', 'scanning');
|
|
GET DIAGNOSTICS affected = ROW_COUNT;
|
|
RETURN affected > 0;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_fail_upload(text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_fail_upload(text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_fail_upload(text,text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_append_activity(
|
|
p_tenant_id text,
|
|
p_project_id text,
|
|
p_summary_text text,
|
|
p_metadata jsonb
|
|
)
|
|
RETURNS TABLE ("id" text)
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
access_record record;
|
|
activity_id text := gen_random_uuid()::text;
|
|
upload_id text;
|
|
file_id text;
|
|
complaint_id text;
|
|
activity_type text;
|
|
sanitized_metadata jsonb;
|
|
BEGIN
|
|
SELECT * INTO access_record
|
|
FROM public.hivegrid_portal_require_project_access(p_project_id, true, false, false);
|
|
IF p_tenant_id <> access_record."tenantId" OR jsonb_typeof(p_metadata) <> 'object'
|
|
OR NULLIF(btrim(p_summary_text), '') IS NULL OR length(p_summary_text) > 500 OR p_summary_text ~ '[[:cntrl:]]'
|
|
OR p_metadata->>'portalUserId' IS DISTINCT FROM access_record."portalUserId" THEN
|
|
RAISE EXCEPTION 'Invalid portal activity payload' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
upload_id := NULLIF(p_metadata->>'uploadId', '');
|
|
file_id := NULLIF(p_metadata->>'fileId', '');
|
|
complaint_id := NULLIF(p_metadata->>'complaintId', '');
|
|
IF upload_id IS NOT NULL AND complaint_id IS NULL AND file_id IS NOT NULL AND EXISTS (
|
|
SELECT 1 FROM public."PortalUpload" AS upload
|
|
WHERE upload."id" = upload_id AND upload."tenantId" = access_record."tenantId"
|
|
AND upload."portalUserId" = access_record."portalUserId" AND upload."projectId" = p_project_id
|
|
AND upload."fileId" = file_id AND upload."status" = 'clean' AND upload."completedAt" IS NOT NULL
|
|
) THEN
|
|
activity_type := 'file_uploaded';
|
|
sanitized_metadata := jsonb_build_object('portalUserId', access_record."portalUserId", 'uploadId', upload_id, 'fileId', file_id);
|
|
ELSIF complaint_id IS NOT NULL AND upload_id IS NULL AND EXISTS (
|
|
SELECT 1 FROM public."PortalComplaint" AS complaint
|
|
WHERE complaint."id" = complaint_id AND complaint."tenantId" = access_record."tenantId"
|
|
AND complaint."portalUserId" = access_record."portalUserId" AND complaint."projectId" = p_project_id
|
|
) THEN
|
|
activity_type := 'portal_complaint_submitted';
|
|
sanitized_metadata := jsonb_build_object(
|
|
'portalUserId', access_record."portalUserId", 'complaintId', complaint_id,
|
|
'subject', CASE WHEN jsonb_typeof(p_metadata->'subject') = 'string' THEN left(p_metadata->>'subject', 200) ELSE NULL END
|
|
);
|
|
ELSE
|
|
RAISE EXCEPTION 'Portal activity source is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
-- Concurrent effect replays must converge on one Activity row. The source
|
|
-- record is immutable and uniquely identifies the user-facing event.
|
|
PERFORM pg_catalog.pg_advisory_xact_lock(
|
|
pg_catalog.hashtextextended(
|
|
'portal-activity:' || access_record."tenantId" || ':' || COALESCE(upload_id, complaint_id),
|
|
26027
|
|
)
|
|
);
|
|
|
|
SELECT activity."id" INTO activity_id
|
|
FROM public."Activity" AS activity
|
|
WHERE activity."tenantId" = access_record."tenantId"
|
|
AND activity."subjectType" = 'project'
|
|
AND activity."subjectId" = p_project_id
|
|
AND activity."activityType" = activity_type
|
|
AND activity."metadata"->>'portalUserId' = access_record."portalUserId"
|
|
AND (
|
|
(upload_id IS NOT NULL AND activity."metadata"->>'uploadId' = upload_id)
|
|
OR (complaint_id IS NOT NULL AND activity."metadata"->>'complaintId' = complaint_id)
|
|
)
|
|
ORDER BY activity."createdAt", activity."id"
|
|
LIMIT 1;
|
|
IF FOUND THEN
|
|
RETURN QUERY SELECT activity_id;
|
|
RETURN;
|
|
END IF;
|
|
activity_id := gen_random_uuid()::text;
|
|
|
|
INSERT INTO public."Activity" (
|
|
"id", "tenantId", "createdAt", "actorUserId", "actorKind", "activityType", "subjectType", "subjectId", "metadata", "summaryText"
|
|
) VALUES (
|
|
activity_id, access_record."tenantId", CURRENT_TIMESTAMP, NULL, 'system', activity_type, 'project', p_project_id,
|
|
sanitized_metadata, btrim(p_summary_text)
|
|
);
|
|
RETURN QUERY SELECT activity_id;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_append_activity(text,text,text,jsonb) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_append_activity(text,text,text,jsonb) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_append_activity(text,text,text,jsonb) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_notify_project_leader(
|
|
p_tenant_id text,
|
|
p_user_id text,
|
|
p_channel text,
|
|
p_category text,
|
|
p_message_key text,
|
|
p_source_key text,
|
|
p_payload_metadata jsonb
|
|
)
|
|
RETURNS TABLE ("created" boolean)
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
access_record record;
|
|
project_id text := NULLIF(p_payload_metadata->>'projectId', '');
|
|
upload_id text := NULLIF(p_payload_metadata->>'uploadId', '');
|
|
complaint_id text := NULLIF(p_payload_metadata->>'complaintId', '');
|
|
BEGIN
|
|
SELECT * INTO access_record
|
|
FROM public.hivegrid_portal_require_project_access(project_id, true, false, false);
|
|
IF p_tenant_id <> access_record."tenantId" OR p_user_id IS DISTINCT FROM access_record."projectLeaderUserId"
|
|
OR p_channel <> 'IN_APP' OR p_category <> 'customer_portal' OR jsonb_typeof(p_payload_metadata) <> 'object'
|
|
OR NULLIF(btrim(p_source_key), '') IS NULL THEN
|
|
RAISE EXCEPTION 'Invalid portal notification target' USING ERRCODE = '42501';
|
|
END IF;
|
|
IF upload_id IS NOT NULL AND complaint_id IS NULL THEN
|
|
IF p_message_key <> 'customerPortal.notifications.uploadReceived' OR p_source_key <> 'portal-upload:' || upload_id
|
|
OR NOT EXISTS (
|
|
SELECT 1 FROM public."PortalUpload" AS upload
|
|
WHERE upload."id" = upload_id AND upload."tenantId" = access_record."tenantId"
|
|
AND upload."portalUserId" = access_record."portalUserId" AND upload."projectId" = project_id
|
|
AND upload."status" = 'clean' AND upload."completedAt" IS NOT NULL
|
|
) THEN
|
|
RAISE EXCEPTION 'Invalid portal upload notification' USING ERRCODE = '42501';
|
|
END IF;
|
|
ELSIF complaint_id IS NOT NULL AND upload_id IS NULL THEN
|
|
IF p_message_key <> 'customerPortal.notifications.complaintReceived' OR p_source_key <> 'portal-complaint:' || complaint_id
|
|
OR NOT EXISTS (
|
|
SELECT 1 FROM public."PortalComplaint" AS complaint
|
|
WHERE complaint."id" = complaint_id AND complaint."tenantId" = access_record."tenantId"
|
|
AND complaint."portalUserId" = access_record."portalUserId" AND complaint."projectId" = project_id
|
|
) THEN
|
|
RAISE EXCEPTION 'Invalid portal complaint notification' USING ERRCODE = '42501';
|
|
END IF;
|
|
ELSE
|
|
RAISE EXCEPTION 'Portal notification source is unavailable' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
INSERT INTO public."NotificationDelivery" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "userId", "channel", "category", "messageKey", "sourceKey", "status", "payloadMetadata"
|
|
) VALUES (
|
|
gen_random_uuid()::text, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, access_record."tenantId", p_user_id,
|
|
'IN_APP', 'customer_portal', p_message_key, p_source_key, 'PENDING', p_payload_metadata
|
|
) ON CONFLICT ("tenantId", "userId", "channel", "sourceKey") DO NOTHING;
|
|
RETURN QUERY SELECT true;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_notify_project_leader(text,text,text,text,text,text,jsonb) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_notify_project_leader(text,text,text,text,text,text,jsonb) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_notify_project_leader(text,text,text,text,text,text,jsonb) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_record_inbox_event(
|
|
p_kind text,
|
|
p_project_id text,
|
|
p_source_id text,
|
|
p_title text
|
|
)
|
|
RETURNS text
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
access_record record;
|
|
rule_record record;
|
|
inbox_id text := gen_random_uuid()::text;
|
|
inbox_priority integer;
|
|
inbox_source_key text;
|
|
inbox_title_key text;
|
|
BEGIN
|
|
IF p_kind NOT IN ('upload', 'complaint', 'login', 'download') OR p_source_id !~ '^[A-Za-z0-9_-]{1,191}$'
|
|
OR p_title IS NOT NULL AND (length(p_title) > 255 OR p_title ~ '[[:cntrl:]]') THEN
|
|
RAISE EXCEPTION 'Invalid portal inbox event' USING ERRCODE = '22023';
|
|
END IF;
|
|
IF p_kind = 'login' THEN
|
|
IF p_project_id IS NOT NULL THEN
|
|
RAISE EXCEPTION 'Portal login inbox event cannot target a project' USING ERRCODE = '22023';
|
|
END IF;
|
|
SELECT
|
|
portal_session."tenantId" AS "tenantId",
|
|
portal_user."portalId" AS "portalId",
|
|
portal_user."id" AS "portalUserId",
|
|
portal_user."kind"::text AS "portalUserKind"
|
|
INTO access_record
|
|
FROM public."PortalSession" AS portal_session
|
|
JOIN public."PortalUser" AS portal_user
|
|
ON portal_user."id" = portal_session."portalUserId"
|
|
AND portal_user."tenantId" = portal_session."tenantId"
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = portal_user."portalId"
|
|
AND portal."tenantId" = portal_user."tenantId"
|
|
JOIN public."Tenant" AS tenant ON tenant."id" = portal_user."tenantId"
|
|
WHERE portal_session."id" = p_source_id
|
|
AND portal_session."tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND portal_session."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND portal_session."createdAt" >= CURRENT_TIMESTAMP - INTERVAL '5 minutes'
|
|
AND portal_session."expiresAt" > CURRENT_TIMESTAMP
|
|
AND portal_session."revokedAt" IS NULL
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND portal."isPublished" = true
|
|
AND tenant."active" = true;
|
|
IF NOT FOUND THEN
|
|
RAISE EXCEPTION 'Portal login inbox source is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
inbox_priority := 200;
|
|
inbox_title_key := 'customerPortal.inbox.items.login';
|
|
ELSIF p_kind = 'download' THEN
|
|
SELECT project_document."projectId" INTO p_project_id
|
|
FROM public."PortalProjectDocument" AS project_document
|
|
WHERE project_document."id" = p_source_id
|
|
AND public.hivegrid_portal_can_read_project_document(project_document."id");
|
|
IF NOT FOUND THEN
|
|
RAISE EXCEPTION 'Portal download inbox source is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
SELECT * INTO access_record
|
|
FROM public.hivegrid_portal_require_project_access(p_project_id, false, false, false);
|
|
inbox_priority := 100;
|
|
inbox_title_key := 'customerPortal.inbox.items.download';
|
|
ELSE
|
|
SELECT * INTO access_record
|
|
FROM public.hivegrid_portal_require_project_access(p_project_id, true, false, p_kind = 'complaint');
|
|
END IF;
|
|
IF p_kind = 'upload' THEN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM public."PortalUpload" AS upload
|
|
WHERE upload."id" = p_source_id AND upload."tenantId" = access_record."tenantId"
|
|
AND upload."portalUserId" = access_record."portalUserId" AND upload."projectId" = p_project_id
|
|
AND upload."status" = 'clean' AND upload."completedAt" IS NOT NULL
|
|
) THEN RAISE EXCEPTION 'Portal upload inbox source is unavailable' USING ERRCODE = '42501'; END IF;
|
|
inbox_priority := 300;
|
|
inbox_title_key := 'customerPortal.inbox.items.upload';
|
|
ELSIF p_kind = 'complaint' THEN
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM public."PortalComplaint" AS complaint
|
|
WHERE complaint."id" = p_source_id AND complaint."tenantId" = access_record."tenantId"
|
|
AND complaint."portalUserId" = access_record."portalUserId" AND complaint."projectId" = p_project_id
|
|
) THEN RAISE EXCEPTION 'Portal complaint inbox source is unavailable' USING ERRCODE = '42501'; END IF;
|
|
inbox_priority := 400;
|
|
inbox_title_key := 'customerPortal.inbox.items.complaint';
|
|
END IF;
|
|
|
|
SELECT rule."id", CASE WHEN rule."targetKind" = 'user' THEN rule."targetUserId" ELSE NULL END AS owner_id
|
|
INTO rule_record
|
|
FROM public."PortalActivityRoutingRule" AS rule
|
|
WHERE rule."tenantId" = access_record."tenantId"
|
|
AND rule."portalId" = access_record."portalId"
|
|
AND rule."activityType"::text = p_kind
|
|
AND rule."enabled" = true
|
|
AND (NOT (rule."matchConfig" ? 'projectId') OR rule."matchConfig"->>'projectId' = p_project_id)
|
|
AND (NOT (rule."matchConfig" ? 'portalUserKind') OR rule."matchConfig"->>'portalUserKind' = access_record."portalUserKind")
|
|
ORDER BY rule."priority" DESC, rule."id"
|
|
LIMIT 1;
|
|
|
|
inbox_source_key := concat_ws(':', 'portal-inbox', access_record."portalUserId", p_project_id, p_kind,
|
|
floor(extract(epoch FROM CURRENT_TIMESTAMP) / 1800)::bigint::text);
|
|
INSERT INTO public."PortalServiceInboxItem" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "portalId", "portalUserId", "projectId", "kind", "status", "priority",
|
|
"sourceKey", "sourceId", "titleKey", "metadata", "occurredAt", "lastOccurredAt", "bundledCount", "expiresAt", "ownerUserId", "routingRuleId"
|
|
) VALUES (
|
|
inbox_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, access_record."tenantId", access_record."portalId", access_record."portalUserId",
|
|
p_project_id, p_kind::public."PortalServiceInboxKind", 'open', inbox_priority, inbox_source_key, p_source_id, inbox_title_key,
|
|
jsonb_build_object('sourceIds', jsonb_build_array(p_source_id), 'latestTitle', left(COALESCE(p_title, ''), 255)),
|
|
CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, 1, CURRENT_TIMESTAMP + INTERVAL '7 days', rule_record.owner_id, rule_record."id"
|
|
)
|
|
ON CONFLICT ("tenantId", "sourceKey") DO UPDATE SET
|
|
"updatedAt" = CURRENT_TIMESTAMP,
|
|
"lastOccurredAt" = CURRENT_TIMESTAMP,
|
|
"sourceId" = EXCLUDED."sourceId",
|
|
"priority" = GREATEST("PortalServiceInboxItem"."priority", EXCLUDED."priority"),
|
|
"bundledCount" = "PortalServiceInboxItem"."bundledCount" + CASE
|
|
WHEN COALESCE("PortalServiceInboxItem"."metadata"->'sourceIds', '[]'::jsonb) @> jsonb_build_array(p_source_id) THEN 0 ELSE 1 END,
|
|
"metadata" = jsonb_set(
|
|
jsonb_set(COALESCE("PortalServiceInboxItem"."metadata", '{}'::jsonb), '{latestTitle}', to_jsonb(left(COALESCE(p_title, ''), 255))),
|
|
'{sourceIds}',
|
|
COALESCE((
|
|
SELECT jsonb_agg(source_id ORDER BY source_id)
|
|
FROM (
|
|
SELECT DISTINCT source_id
|
|
FROM jsonb_array_elements_text(
|
|
COALESCE("PortalServiceInboxItem"."metadata"->'sourceIds', '[]'::jsonb) || jsonb_build_array(p_source_id)
|
|
) AS source_ids(source_id)
|
|
) AS unique_source_ids
|
|
), '[]'::jsonb)
|
|
),
|
|
"expiresAt" = CURRENT_TIMESTAMP + INTERVAL '7 days',
|
|
"ownerUserId" = COALESCE(EXCLUDED."ownerUserId", "PortalServiceInboxItem"."ownerUserId"),
|
|
"routingRuleId" = COALESCE(EXCLUDED."routingRuleId", "PortalServiceInboxItem"."routingRuleId")
|
|
RETURNING "id" INTO inbox_id;
|
|
RETURN inbox_id;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_record_inbox_event(text,text,text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_record_inbox_event(text,text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_record_inbox_event(text,text,text,text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_mark_effects_completed(p_kind text, p_source_id text)
|
|
RETURNS TABLE ("completed" boolean)
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
context_record record;
|
|
access_record record;
|
|
source_record record;
|
|
expected_activity_type text;
|
|
expected_notification_source text;
|
|
expected_inbox_kind text;
|
|
BEGIN
|
|
IF p_kind NOT IN ('upload', 'complaint') OR p_source_id !~ '^[A-Za-z0-9_-]{1,191}$' THEN
|
|
RAISE EXCEPTION 'Invalid portal effect-completion source' USING ERRCODE = '22023';
|
|
END IF;
|
|
SELECT * INTO context_record FROM public.hivegrid_portal_require_active_context(true);
|
|
|
|
IF p_kind = 'upload' THEN
|
|
SELECT upload."projectId", upload."effectsCompletedAt", project."projektleiterId" AS project_leader_user_id
|
|
INTO source_record
|
|
FROM public."PortalUpload" AS upload
|
|
JOIN public."Projekt" AS project ON project."id" = upload."projectId" AND project."tenantId" = upload."tenantId"
|
|
WHERE upload."id" = p_source_id
|
|
AND upload."tenantId" = context_record."tenantId"
|
|
AND upload."portalId" = context_record."portalId"
|
|
AND upload."portalUserId" = context_record."portalUserId"
|
|
AND upload."status" = 'clean'
|
|
AND upload."completedAt" IS NOT NULL;
|
|
expected_activity_type := 'file_uploaded';
|
|
expected_notification_source := 'portal-upload:' || p_source_id;
|
|
expected_inbox_kind := 'upload';
|
|
ELSE
|
|
SELECT complaint."projectId", complaint."effectsCompletedAt", project."projektleiterId" AS project_leader_user_id
|
|
INTO source_record
|
|
FROM public."PortalComplaint" AS complaint
|
|
JOIN public."Projekt" AS project ON project."id" = complaint."projectId" AND project."tenantId" = complaint."tenantId"
|
|
WHERE complaint."id" = p_source_id
|
|
AND complaint."tenantId" = context_record."tenantId"
|
|
AND complaint."portalId" = context_record."portalId"
|
|
AND complaint."portalUserId" = context_record."portalUserId";
|
|
expected_activity_type := 'portal_complaint_submitted';
|
|
expected_notification_source := 'portal-complaint:' || p_source_id;
|
|
expected_inbox_kind := 'complaint';
|
|
END IF;
|
|
IF NOT FOUND THEN
|
|
RAISE EXCEPTION 'Portal effect-completion source is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
SELECT * INTO access_record
|
|
FROM public.hivegrid_portal_require_project_access(source_record."projectId", true, false, p_kind = 'complaint');
|
|
IF source_record."effectsCompletedAt" IS NOT NULL THEN
|
|
RETURN QUERY SELECT true;
|
|
RETURN;
|
|
END IF;
|
|
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM public."Activity" AS activity
|
|
WHERE activity."tenantId" = context_record."tenantId"
|
|
AND activity."subjectType" = 'project'
|
|
AND activity."subjectId" = source_record."projectId"
|
|
AND activity."activityType" = expected_activity_type
|
|
AND activity."metadata"->>'portalUserId' = context_record."portalUserId"
|
|
AND activity."metadata"->>(CASE WHEN p_kind = 'upload' THEN 'uploadId' ELSE 'complaintId' END) = p_source_id
|
|
) OR NOT EXISTS (
|
|
SELECT 1 FROM public."PortalServiceInboxItem" AS inbox
|
|
WHERE inbox."tenantId" = context_record."tenantId"
|
|
AND inbox."portalUserId" = context_record."portalUserId"
|
|
AND inbox."projectId" = source_record."projectId"
|
|
AND inbox."kind"::text = expected_inbox_kind
|
|
AND COALESCE(inbox."metadata"->'sourceIds', '[]'::jsonb) @> jsonb_build_array(p_source_id)
|
|
) OR (
|
|
source_record.project_leader_user_id IS NOT NULL
|
|
AND NOT EXISTS (
|
|
SELECT 1 FROM public."NotificationDelivery" AS delivery
|
|
WHERE delivery."tenantId" = context_record."tenantId"
|
|
AND delivery."userId" = source_record.project_leader_user_id
|
|
AND delivery."channel" = 'IN_APP'
|
|
AND delivery."category" = 'customer_portal'
|
|
AND delivery."sourceKey" = expected_notification_source
|
|
)
|
|
) THEN
|
|
RAISE EXCEPTION 'Portal auxiliary effects are incomplete' USING ERRCODE = '55000';
|
|
END IF;
|
|
|
|
IF p_kind = 'upload' THEN
|
|
UPDATE public."PortalUpload"
|
|
SET "updatedAt" = CURRENT_TIMESTAMP, "effectsCompletedAt" = CURRENT_TIMESTAMP
|
|
WHERE "id" = p_source_id AND "tenantId" = context_record."tenantId" AND "portalUserId" = context_record."portalUserId"
|
|
AND "effectsCompletedAt" IS NULL;
|
|
ELSE
|
|
UPDATE public."PortalComplaint"
|
|
SET "updatedAt" = CURRENT_TIMESTAMP, "effectsCompletedAt" = CURRENT_TIMESTAMP
|
|
WHERE "id" = p_source_id AND "tenantId" = context_record."tenantId" AND "portalUserId" = context_record."portalUserId"
|
|
AND "effectsCompletedAt" IS NULL;
|
|
END IF;
|
|
RETURN QUERY SELECT true;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_mark_effects_completed(text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_mark_effects_completed(text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_mark_effects_completed(text,text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_complaint_form(p_project_id text, p_form_id text)
|
|
RETURNS TABLE ("id" text, "definition" jsonb)
|
|
LANGUAGE plpgsql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
access_record record;
|
|
normalized_form_id text := NULLIF(btrim(p_form_id), '');
|
|
selected_id text;
|
|
selected_definition jsonb;
|
|
selected_priority integer;
|
|
candidate_count integer;
|
|
BEGIN
|
|
SELECT * INTO access_record
|
|
FROM public.hivegrid_portal_require_project_access(p_project_id, false, false, true);
|
|
|
|
IF normalized_form_id IS NOT NULL THEN
|
|
RETURN QUERY
|
|
SELECT form."id", form."definition"
|
|
FROM public."Form" AS form
|
|
WHERE form."id" = normalized_form_id
|
|
AND form."tenantId" = access_record."tenantId"
|
|
AND form."subtype"::text = 'portal_form'
|
|
AND form."status" = 'published'
|
|
AND form."isPublic" = true
|
|
AND form."isEnabled" = true
|
|
AND (form."targetEntityId" IS NULL OR form."targetEntityId" = p_project_id)
|
|
AND (cardinality(form."allowedOrigins") = 0 OR access_record."origin" = ANY(form."allowedOrigins"))
|
|
LIMIT 1;
|
|
RETURN;
|
|
END IF;
|
|
|
|
SELECT form."id", form."definition", CASE WHEN form."targetEntityId" = p_project_id THEN 1 ELSE 0 END
|
|
INTO selected_id, selected_definition, selected_priority
|
|
FROM public."Form" AS form
|
|
WHERE form."tenantId" = access_record."tenantId"
|
|
AND form."subtype"::text = 'portal_form'
|
|
AND form."status" = 'published'
|
|
AND form."isPublic" = true
|
|
AND form."isEnabled" = true
|
|
AND (form."targetEntityId" IS NULL OR form."targetEntityId" = p_project_id)
|
|
AND (cardinality(form."allowedOrigins") = 0 OR access_record."origin" = ANY(form."allowedOrigins"))
|
|
ORDER BY CASE WHEN form."targetEntityId" = p_project_id THEN 1 ELSE 0 END DESC, form."id"
|
|
LIMIT 1;
|
|
IF selected_id IS NULL THEN RETURN; END IF;
|
|
SELECT count(*) INTO candidate_count
|
|
FROM public."Form" AS form
|
|
WHERE form."tenantId" = access_record."tenantId"
|
|
AND form."subtype"::text = 'portal_form' AND form."status" = 'published' AND form."isPublic" = true AND form."isEnabled" = true
|
|
AND (form."targetEntityId" IS NULL OR form."targetEntityId" = p_project_id)
|
|
AND (cardinality(form."allowedOrigins") = 0 OR access_record."origin" = ANY(form."allowedOrigins"))
|
|
AND CASE WHEN form."targetEntityId" = p_project_id THEN 1 ELSE 0 END = selected_priority;
|
|
IF candidate_count <> 1 THEN
|
|
RAISE EXCEPTION 'Ambiguous portal complaint form configuration' USING ERRCODE = '21000';
|
|
END IF;
|
|
RETURN QUERY SELECT selected_id, selected_definition;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_complaint_form(text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_complaint_form(text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_complaint_form(text,text) TO hivegrid_portal;
|
|
|
|
DROP FUNCTION IF EXISTS public.hivegrid_portal_submit_complaint(text,text,text,text,jsonb,text,text);
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_submit_complaint(
|
|
p_complaint_id text,
|
|
p_submission_id text,
|
|
p_project_id text,
|
|
p_form_id text,
|
|
p_values jsonb,
|
|
p_subject text,
|
|
p_idempotency_key text
|
|
)
|
|
RETURNS TABLE ("complaintId" text, "submissionId" text, "projectLeaderUserId" text, "effectsCompleted" boolean)
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
access_record record;
|
|
form_record record;
|
|
existing_record record;
|
|
normalized_key text := NULLIF(btrim(p_idempotency_key), '');
|
|
normalized_subject text := NULLIF(btrim(p_subject), '');
|
|
BEGIN
|
|
SELECT * INTO access_record
|
|
FROM public.hivegrid_portal_require_project_access(p_project_id, true, false, true);
|
|
IF p_complaint_id !~ '^[A-Za-z0-9_-]{1,191}$' OR p_submission_id !~ '^[A-Za-z0-9_-]{1,191}$'
|
|
OR NULLIF(btrim(p_form_id), '') IS NULL OR length(p_form_id) > 191
|
|
OR jsonb_typeof(p_values) <> 'object' OR octet_length(p_values::text) > 262144
|
|
OR normalized_key IS NULL OR normalized_key !~ '^[A-Za-z0-9._:-]{1,128}$'
|
|
OR length(COALESCE(normalized_subject, '')) > 200 OR COALESCE(normalized_subject, '') ~ '[[:cntrl:]]' THEN
|
|
RAISE EXCEPTION 'Invalid portal complaint submission' USING ERRCODE = '22023';
|
|
END IF;
|
|
|
|
SELECT form.* INTO form_record
|
|
FROM public."Form" AS form
|
|
WHERE form."id" = p_form_id
|
|
AND form."tenantId" = access_record."tenantId"
|
|
AND form."subtype"::text = 'portal_form'
|
|
AND form."status" = 'published'
|
|
AND form."isPublic" = true
|
|
AND form."isEnabled" = true
|
|
AND (form."targetEntityId" IS NULL OR form."targetEntityId" = p_project_id)
|
|
AND (cardinality(form."allowedOrigins") = 0 OR access_record."origin" = ANY(form."allowedOrigins"));
|
|
IF NOT FOUND THEN
|
|
RAISE EXCEPTION 'Portal complaint form is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
SELECT submission."id" AS submission_id, complaint."id" AS complaint_id,
|
|
submission."createdByPortalUserId", submission."projectId", submission."payload", complaint."portalUserId" AS complaint_portal_user_id,
|
|
complaint."projectId" AS complaint_project_id, complaint."subject", complaint."effectsCompletedAt"
|
|
INTO existing_record
|
|
FROM public."FormSubmission" AS submission
|
|
LEFT JOIN public."PortalComplaint" AS complaint ON complaint."formSubmissionId" = submission."id"
|
|
WHERE submission."formId" = p_form_id AND submission."idempotencyKey" = normalized_key;
|
|
IF FOUND THEN
|
|
IF existing_record."createdByPortalUserId" <> access_record."portalUserId"
|
|
OR existing_record."projectId" <> p_project_id
|
|
OR existing_record.complaint_id IS NULL
|
|
OR existing_record.complaint_portal_user_id <> access_record."portalUserId"
|
|
OR existing_record.complaint_project_id <> p_project_id
|
|
OR existing_record."payload" <> jsonb_build_object('values', p_values)
|
|
OR existing_record."subject" IS DISTINCT FROM normalized_subject THEN
|
|
RAISE EXCEPTION 'Portal complaint idempotency collision' USING ERRCODE = '23505';
|
|
END IF;
|
|
RETURN QUERY SELECT existing_record.complaint_id, existing_record.submission_id, access_record."projectLeaderUserId",
|
|
existing_record."effectsCompletedAt" IS NOT NULL;
|
|
RETURN;
|
|
END IF;
|
|
|
|
INSERT INTO public."FormSubmission" (
|
|
"id", "formId", "tenantId", "createdByUserId", "createdByPortalUserId", "projectId", "payload", "sourceOrigin",
|
|
"status", "idempotencyKey", "gdprAccepted", "createdAt", "updatedAt"
|
|
) VALUES (
|
|
p_submission_id, p_form_id, access_record."tenantId", NULL, access_record."portalUserId", p_project_id,
|
|
jsonb_build_object('values', p_values), access_record."origin", 'received', normalized_key, true, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP
|
|
);
|
|
INSERT INTO public."PortalComplaint" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "portalId", "portalUserId", "projectId", "formSubmissionId", "subject", "status"
|
|
) VALUES (
|
|
p_complaint_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, access_record."tenantId", access_record."portalId", access_record."portalUserId",
|
|
p_project_id, p_submission_id, normalized_subject, 'open'
|
|
);
|
|
INSERT INTO public."OutboxEvent" ("id", "tenantId", "eventType", "payload", "dispatchKey", "priority")
|
|
VALUES (
|
|
gen_random_uuid()::text, access_record."tenantId", 'form.submission.process',
|
|
jsonb_build_object(
|
|
'submissionId', p_submission_id, 'formId', p_form_id, 'tenantId', access_record."tenantId",
|
|
'targetType', form_record."targetType", 'targetEntityId', form_record."targetEntityId",
|
|
'fieldMapping', form_record."fieldMapping", 'webhookUrl', form_record."webhookUrl",
|
|
'notifyEmails', to_jsonb(form_record."notifyEmails"), 'values', p_values, 'files', '[]'::jsonb
|
|
),
|
|
'form-submission:' || p_submission_id, 100
|
|
);
|
|
INSERT INTO public."OutboxEvent" ("id", "tenantId", "eventType", "payload", "dispatchKey", "priority")
|
|
VALUES (
|
|
gen_random_uuid()::text,
|
|
access_record."tenantId",
|
|
'workflow.trigger.event',
|
|
jsonb_build_object(
|
|
'event', 'portal.complaint_submitted',
|
|
'tenantId', access_record."tenantId",
|
|
'portalId', access_record."portalId",
|
|
'portalUserId', access_record."portalUserId",
|
|
'projectId', p_project_id,
|
|
'complaintId', p_complaint_id,
|
|
'submissionId', p_submission_id,
|
|
'formId', p_form_id
|
|
),
|
|
'workflow-trigger:portal-complaint:' || p_complaint_id || ':submitted',
|
|
100
|
|
);
|
|
RETURN QUERY SELECT p_complaint_id, p_submission_id, access_record."projectLeaderUserId", false;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_submit_complaint(text,text,text,text,jsonb,text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_submit_complaint(text,text,text,text,jsonb,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_submit_complaint(text,text,text,text,jsonb,text,text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_upsert_notification_preference(
|
|
p_event_type text,
|
|
p_email_enabled boolean,
|
|
p_muted_until timestamp with time zone
|
|
)
|
|
RETURNS text
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
tenant_id text := NULLIF(current_setting('app.tenant_id', true), '');
|
|
portal_user_id text := NULLIF(current_setting('app.portal_user_id', true), '');
|
|
preference_id text;
|
|
BEGIN
|
|
PERFORM 1 FROM public.hivegrid_portal_require_active_context(true);
|
|
IF session_user <> 'hivegrid_portal'
|
|
OR tenant_id IS NULL
|
|
OR portal_user_id IS NULL
|
|
OR NULLIF(current_setting('app.user_id', true), '') IS NOT NULL THEN
|
|
RAISE EXCEPTION 'Portal identity context is required' USING ERRCODE = '42501';
|
|
END IF;
|
|
IF p_event_type NOT IN ('stage_changed', 'document_released', 'upload_confirmation', 'status_mail', 'lifecycle') THEN
|
|
RAISE EXCEPTION 'Unsupported portal notification event' USING ERRCODE = '22023';
|
|
END IF;
|
|
IF p_muted_until IS NOT NULL AND p_muted_until > CURRENT_TIMESTAMP + INTERVAL '1 year' THEN
|
|
RAISE EXCEPTION 'Portal notification mute window is too long' USING ERRCODE = '22023';
|
|
END IF;
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM public."PortalUser" AS portal_user
|
|
WHERE portal_user."id" = portal_user_id
|
|
AND portal_user."tenantId" = tenant_id
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
) OR EXISTS (
|
|
SELECT 1 FROM public."TenantSubscription" AS subscription
|
|
WHERE subscription."tenantId" = tenant_id
|
|
AND (lower(subscription."status") = 'frozen' OR subscription."frozenAt" IS NOT NULL)
|
|
) THEN
|
|
RAISE EXCEPTION 'Portal write access is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
INSERT INTO public."PortalNotificationPreference" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "portalUserId", "eventType", "emailEnabled", "mutedUntil"
|
|
) VALUES (
|
|
gen_random_uuid()::text, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, tenant_id, portal_user_id,
|
|
p_event_type::public."PortalNotificationEvent", p_email_enabled, p_muted_until
|
|
)
|
|
ON CONFLICT ("portalUserId", "eventType") DO UPDATE
|
|
SET "updatedAt" = CURRENT_TIMESTAMP,
|
|
"emailEnabled" = EXCLUDED."emailEnabled",
|
|
"mutedUntil" = EXCLUDED."mutedUntil"
|
|
WHERE "PortalNotificationPreference"."tenantId" = tenant_id
|
|
RETURNING "id" INTO preference_id;
|
|
|
|
RETURN preference_id;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_upsert_notification_preference(text,boolean,timestamp with time zone) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_upsert_notification_preference(text,boolean,timestamp with time zone) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_upsert_notification_preference(text,boolean,timestamp with time zone) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_request_gdpr_export(p_idempotency_key text)
|
|
RETURNS text
|
|
LANGUAGE plpgsql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
DECLARE
|
|
tenant_id text := NULLIF(current_setting('app.tenant_id', true), '');
|
|
portal_user_id text := NULLIF(current_setting('app.portal_user_id', true), '');
|
|
normalized_key text := NULLIF(btrim(p_idempotency_key), '');
|
|
export_id text;
|
|
BEGIN
|
|
PERFORM 1 FROM public.hivegrid_portal_require_active_context(true);
|
|
IF session_user <> 'hivegrid_portal'
|
|
OR tenant_id IS NULL
|
|
OR portal_user_id IS NULL
|
|
OR NULLIF(current_setting('app.user_id', true), '') IS NOT NULL THEN
|
|
RAISE EXCEPTION 'Portal identity context is required' USING ERRCODE = '42501';
|
|
END IF;
|
|
IF normalized_key IS NULL OR normalized_key !~ '^[A-Za-z0-9._:-]{1,128}$' THEN
|
|
RAISE EXCEPTION 'Invalid portal export idempotency key' USING ERRCODE = '22023';
|
|
END IF;
|
|
IF NOT EXISTS (
|
|
SELECT 1 FROM public."PortalUser" AS portal_user
|
|
WHERE portal_user."id" = portal_user_id
|
|
AND portal_user."tenantId" = tenant_id
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
) OR EXISTS (
|
|
SELECT 1 FROM public."TenantSubscription" AS subscription
|
|
WHERE subscription."tenantId" = tenant_id
|
|
AND (lower(subscription."status") = 'frozen' OR subscription."frozenAt" IS NOT NULL)
|
|
) THEN
|
|
RAISE EXCEPTION 'Portal export access is unavailable' USING ERRCODE = '42501';
|
|
END IF;
|
|
|
|
SELECT job."id" INTO export_id
|
|
FROM public."PortalGdprExportJob" AS job
|
|
WHERE job."tenantId" = tenant_id
|
|
AND job."portalUserId" = portal_user_id
|
|
AND job."idempotencyKey" = normalized_key;
|
|
IF export_id IS NOT NULL THEN
|
|
RETURN export_id;
|
|
END IF;
|
|
|
|
export_id := gen_random_uuid()::text;
|
|
INSERT INTO public."PortalGdprExportJob" (
|
|
"id", "createdAt", "updatedAt", "tenantId", "portalId", "portalUserId", "status", "progressPercent", "downloadCount", "idempotencyKey"
|
|
)
|
|
SELECT export_id, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, tenant_id, portal_user."portalId", portal_user_id,
|
|
'queued'::public."PortalGdprExportStatus", 0, 0, normalized_key
|
|
FROM public."PortalUser" AS portal_user
|
|
WHERE portal_user."id" = portal_user_id AND portal_user."tenantId" = tenant_id;
|
|
|
|
INSERT INTO public."OutboxEvent" ("id", "tenantId", "eventType", "payload")
|
|
VALUES (
|
|
gen_random_uuid()::text,
|
|
tenant_id,
|
|
'portal.gdpr_export.requested',
|
|
jsonb_build_object('tenantId', tenant_id, 'portalUserId', portal_user_id, 'jobId', export_id)
|
|
);
|
|
RETURN export_id;
|
|
END
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_request_gdpr_export(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_request_gdpr_export(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_request_gdpr_export(text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_gdpr_export(p_export_id text)
|
|
RETURNS TABLE (
|
|
"resultBucket" text,
|
|
"resultKey" text,
|
|
"resultSizeBytes" integer,
|
|
"resultExpiresAt" timestamp with time zone
|
|
)
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
job."resultBucket",
|
|
job."resultKey",
|
|
job."resultSizeBytes",
|
|
job."resultExpiresAt" AT TIME ZONE 'UTC'
|
|
FROM public."PortalGdprExportJob" AS job
|
|
WHERE session_user = 'hivegrid_portal'
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND job."id" = p_export_id
|
|
AND job."tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND job."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND job."status" = 'ready'
|
|
AND job."resultExpiresAt" > CURRENT_TIMESTAMP
|
|
AND job."resultBucket" IS NOT NULL
|
|
AND job."resultKey" IS NOT NULL
|
|
LIMIT 1
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_gdpr_export(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_gdpr_export(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_gdpr_export(text) TO hivegrid_portal;
|
|
|
|
-- The object-store key remains unavailable through direct File SELECT. This
|
|
-- capability returns it only for one released, clean document that belongs to
|
|
-- the exact authenticated portal identity and an unarchived project.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_project_document(p_document_id text)
|
|
RETURNS TABLE (
|
|
"storageKey" text,
|
|
"displayName" text,
|
|
"scanStatus" text
|
|
)
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
file."storageKey",
|
|
file."displayName",
|
|
file."scanStatus"::text
|
|
FROM public."PortalProjectDocument" AS project_document
|
|
JOIN public."File" AS file
|
|
ON file."id" = project_document."fileId"
|
|
AND file."tenantId" = project_document."tenantId"
|
|
JOIN public."Projekt" AS project
|
|
ON project."id" = project_document."projectId"
|
|
AND project."tenantId" = project_document."tenantId"
|
|
JOIN public."PortalProjectAccess" AS project_access
|
|
ON project_access."tenantId" = project_document."tenantId"
|
|
AND project_access."portalId" = project_document."portalId"
|
|
AND project_access."projectId" = project_document."projectId"
|
|
JOIN public."PortalUser" AS portal_user
|
|
ON portal_user."id" = project_access."portalUserId"
|
|
AND portal_user."tenantId" = project_access."tenantId"
|
|
AND portal_user."portalId" = project_access."portalId"
|
|
WHERE session_user = 'hivegrid_portal'
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND project_document."id" = p_document_id
|
|
AND project_document."tenantId" = NULLIF(current_setting('app.tenant_id', true), '')
|
|
AND project_document."releasedAt" <= CURRENT_TIMESTAMP
|
|
AND project_document."revokedAt" IS NULL
|
|
AND file."scanStatus" = 'clean'
|
|
AND file."archivedAt" IS NULL
|
|
AND project."archivedAt" IS NULL
|
|
AND project_access."portalUserId" = NULLIF(current_setting('app.portal_user_id', true), '')
|
|
AND project_access."active" = true
|
|
AND project_access."revokedAt" IS NULL
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
LIMIT 1
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_project_document(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_project_document(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_project_document(text) TO hivegrid_portal;
|
|
|
|
-- Every standard and custom-host resolver re-proves this non-exposed
|
|
-- commercial capability at request time. A published Portal row is not a
|
|
-- durable entitlement: cancellation, refund or freeze removes public access
|
|
-- immediately without relying on an asynchronous unpublish job.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_tenant_has_live_entitlement(
|
|
p_tenant_id text
|
|
)
|
|
RETURNS boolean
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
session_user = 'hivegrid_portal'
|
|
AND EXISTS (
|
|
SELECT 1
|
|
FROM public."TenantSubscription" AS subscription
|
|
WHERE subscription."tenantId" = p_tenant_id
|
|
AND subscription."status" = 'active'
|
|
AND subscription."cancelledAt" IS NULL
|
|
AND subscription."frozenAt" IS NULL
|
|
AND (
|
|
subscription."planCode" = 'business'
|
|
OR EXISTS (
|
|
SELECT 1
|
|
FROM public."TenantProductAcquisition" AS portal_acquisition
|
|
JOIN public."SubscriptionProduct" AS portal_product
|
|
ON portal_product."id" = portal_acquisition."subscriptionProductId"
|
|
AND portal_product."code" = 'customer_portal_monthly'
|
|
WHERE portal_acquisition."tenantId" = subscription."tenantId"
|
|
AND portal_acquisition."status" = 'active'
|
|
AND portal_acquisition."scopeKey" = 'tenant'
|
|
AND portal_acquisition."cancelledAt" IS NULL
|
|
AND portal_acquisition."expiredAt" IS NULL
|
|
AND portal_acquisition."refundedAt" IS NULL
|
|
)
|
|
OR EXISTS (
|
|
SELECT 1
|
|
FROM public."TenantProductAcquisition" AS portal_contract
|
|
JOIN public."SubscriptionProduct" AS contract_product
|
|
ON contract_product."id" = portal_contract."subscriptionProductId"
|
|
AND contract_product."code" = 'customer_portal_enterprise_contract'
|
|
WHERE portal_contract."tenantId" = subscription."tenantId"
|
|
AND portal_contract."status" = 'active'
|
|
AND portal_contract."scopeKey" = 'tenant'
|
|
AND portal_contract."quantity" >= 1
|
|
AND portal_contract."cancelledAt" IS NULL
|
|
AND portal_contract."expiredAt" IS NULL
|
|
AND portal_contract."refundedAt" IS NULL
|
|
)
|
|
)
|
|
)
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_tenant_has_live_entitlement(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_tenant_has_live_entitlement(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_portal, hivegrid_authentik_jit;
|
|
|
|
-- Custom-host resolution additionally re-proves the claim-specific setup or
|
|
-- Enterprise acquisition. Persisted entitlementValidatedAt and
|
|
-- paymentAcquisitionId fields are only historical controller evidence.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_claim_has_live_entitlement(
|
|
p_tenant_id text,
|
|
p_claim_id text,
|
|
p_payment_acquisition_id text
|
|
)
|
|
RETURNS boolean
|
|
LANGUAGE sql
|
|
STABLE
|
|
SET search_path = pg_catalog, public
|
|
AS $function$
|
|
SELECT EXISTS (
|
|
SELECT 1
|
|
FROM public."PortalDomainHostnameClaim" AS entitlement_claim
|
|
WHERE entitlement_claim."id" = p_claim_id
|
|
AND entitlement_claim."tenantId" = p_tenant_id
|
|
AND entitlement_claim."releasedAt" IS NULL
|
|
AND entitlement_claim."billingScopeKey" IS NOT NULL
|
|
AND public.hivegrid_portal_tenant_has_live_entitlement(entitlement_claim."tenantId")
|
|
AND (
|
|
EXISTS (
|
|
SELECT 1
|
|
FROM public."TenantProductAcquisition" AS setup_acquisition
|
|
JOIN public."SubscriptionProduct" AS setup_product
|
|
ON setup_product."id" = setup_acquisition."subscriptionProductId"
|
|
AND setup_product."code" = 'customer_portal_domain_setup'
|
|
WHERE setup_acquisition."id" = p_payment_acquisition_id
|
|
AND setup_acquisition."tenantId" = entitlement_claim."tenantId"
|
|
AND setup_acquisition."status" = 'active'
|
|
AND setup_acquisition."scopeKey" = entitlement_claim."billingScopeKey"
|
|
AND setup_acquisition."cancelledAt" IS NULL
|
|
AND setup_acquisition."expiredAt" IS NULL
|
|
AND setup_acquisition."refundedAt" IS NULL
|
|
)
|
|
OR EXISTS (
|
|
SELECT 1
|
|
FROM public."TenantProductAcquisition" AS domain_contract
|
|
JOIN public."SubscriptionProduct" AS domain_contract_product
|
|
ON domain_contract_product."id" = domain_contract."subscriptionProductId"
|
|
AND domain_contract_product."code" = 'customer_portal_enterprise_contract'
|
|
WHERE domain_contract."id" = p_payment_acquisition_id
|
|
AND domain_contract."tenantId" = entitlement_claim."tenantId"
|
|
AND domain_contract."status" = 'active'
|
|
AND domain_contract."scopeKey" = 'tenant'
|
|
AND domain_contract."quantity" >= 1
|
|
AND entitlement_claim."billingScopeKey" = 'enterprise-contract:' || domain_contract."id"
|
|
AND domain_contract."cancelledAt" IS NULL
|
|
AND domain_contract."expiredAt" IS NULL
|
|
AND domain_contract."refundedAt" IS NULL
|
|
)
|
|
)
|
|
)
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_claim_has_live_entitlement(text,text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_claim_has_live_entitlement(text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_portal, hivegrid_authentik_jit;
|
|
|
|
-- Compatibility helper retained for already-published resolver bodies. The
|
|
-- customer portal is a core feature now; entitlements, tenant state and
|
|
-- identity remain the authoritative access controls.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_customer_feature_enabled()
|
|
RETURNS boolean
|
|
LANGUAGE sql
|
|
IMMUTABLE
|
|
SECURITY INVOKER
|
|
SET search_path = pg_catalog, public
|
|
AS $function$
|
|
SELECT true
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_customer_feature_enabled() OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_customer_feature_enabled() FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_portal, hivegrid_authentik_jit;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_customer_feature_status()
|
|
RETURNS boolean
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT session_user = 'hivegrid_portal'
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_customer_feature_status() OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_customer_feature_status() FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_customer_feature_status() TO hivegrid_portal;
|
|
|
|
-- Custom-host resolution runs before portal authentication, so it cannot use
|
|
-- tenant or portal-user GUCs. The global hostname claim is the sole lookup key;
|
|
-- every operational and ownership edge is re-proved inside this capability.
|
|
-- Unknown, pending, disabled, stale-generation, or released bindings return no
|
|
-- row and therefore follow the public router's 404 path.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_custom_hostname(p_hostname text)
|
|
RETURNS TABLE (
|
|
"tenantId" text,
|
|
"portalId" text,
|
|
"tenantSlug" text,
|
|
"tenantActive" boolean,
|
|
hostname text,
|
|
"activeOrigin" text,
|
|
generation integer
|
|
)
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
tenant."id",
|
|
portal."id",
|
|
tenant."slug",
|
|
tenant."active",
|
|
claim."hostname",
|
|
domain."activeOrigin",
|
|
domain."generation"
|
|
FROM public."PortalDomainHostnameClaim" AS claim
|
|
JOIN public."PortalCustomDomain" AS domain
|
|
ON domain."claimId" = claim."id"
|
|
AND domain."tenantId" = claim."tenantId"
|
|
AND domain."portalId" = claim."portalId"
|
|
AND domain."generation" = claim."generation"
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = domain."portalId"
|
|
AND portal."tenantId" = domain."tenantId"
|
|
JOIN public."Tenant" AS tenant
|
|
ON tenant."id" = portal."tenantId"
|
|
WHERE session_user = 'hivegrid_portal'
|
|
AND public.hivegrid_portal_customer_feature_enabled()
|
|
AND p_hostname IS NOT NULL
|
|
AND p_hostname = lower(btrim(p_hostname))
|
|
AND length(p_hostname) BETWEEN 4 AND 253
|
|
AND p_hostname ~ '^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])$'
|
|
AND p_hostname ~ '[.]'
|
|
AND p_hostname !~ '^[0-9.]+$'
|
|
AND p_hostname NOT LIKE '%.localhost'
|
|
AND p_hostname NOT LIKE 'localhost.%'
|
|
AND claim."hostname" = p_hostname
|
|
AND claim."hostname" = lower(btrim(claim."hostname"))
|
|
AND claim."dnsStatus" = 'verified'
|
|
AND claim."verifiedAt" IS NOT NULL
|
|
AND claim."releasedAt" IS NULL
|
|
AND claim."cooldownUntil" IS NULL
|
|
AND domain."status" = 'active'
|
|
AND domain."activeOrigin" = 'https://' || claim."hostname"
|
|
AND domain."lastHealthAckAt" IS NOT NULL
|
|
AND domain."provisionedAt" IS NOT NULL
|
|
AND domain."tlsObservedAt" IS NOT NULL
|
|
AND domain."disabledAt" IS NULL
|
|
AND domain."deprovisioningStartedAt" IS NULL
|
|
AND domain."deprovisionedAt" IS NULL
|
|
AND domain."releasedAt" IS NULL
|
|
AND domain."cooldownUntil" IS NULL
|
|
AND domain."killSwitchEnabled" = false
|
|
AND public.hivegrid_portal_claim_has_live_entitlement(
|
|
domain."tenantId",
|
|
domain."claimId",
|
|
domain."paymentAcquisitionId"
|
|
)
|
|
AND portal."isPublished" = true
|
|
AND tenant."active" = true
|
|
AND tenant."slug" = lower(btrim(tenant."slug"))
|
|
AND tenant."slug" ~ '^[a-z0-9][a-z0-9-]{1,62}$'
|
|
AND (
|
|
SELECT COUNT(*)
|
|
FROM public."Tenant" AS slug_peer
|
|
WHERE slug_peer."active" = true
|
|
AND lower(slug_peer."slug") = lower(tenant."slug")
|
|
) = 1
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_custom_hostname(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_custom_hostname(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_custom_hostname(text) TO hivegrid_portal;
|
|
|
|
-- The controller must prove the exact custom-host router and SNI certificate
|
|
-- before the binding can become active. This narrower resolver exposes only
|
|
-- /healthz eligibility for a DNS-verified, entitled and already-dispatched
|
|
-- generation; it does not make routes, auth or assets reachable.
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_custom_hostname_health(p_hostname text)
|
|
RETURNS TABLE (
|
|
"tenantId" text,
|
|
"portalId" text,
|
|
"tenantSlug" text,
|
|
"tenantActive" boolean,
|
|
hostname text,
|
|
"activeOrigin" text,
|
|
generation integer
|
|
)
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
tenant."id",
|
|
portal."id",
|
|
tenant."slug",
|
|
tenant."active",
|
|
claim."hostname",
|
|
'https://' || claim."hostname",
|
|
domain."generation"
|
|
FROM public."PortalDomainHostnameClaim" AS claim
|
|
JOIN public."PortalCustomDomain" AS domain
|
|
ON domain."claimId" = claim."id"
|
|
AND domain."tenantId" = claim."tenantId"
|
|
AND domain."portalId" = claim."portalId"
|
|
AND domain."generation" = claim."generation"
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = domain."portalId"
|
|
AND portal."tenantId" = domain."tenantId"
|
|
JOIN public."Tenant" AS tenant
|
|
ON tenant."id" = portal."tenantId"
|
|
WHERE session_user = 'hivegrid_portal'
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND NULLIF(current_setting('app.tenant_id', true), '') IS NULL
|
|
AND NULLIF(current_setting('app.portal_user_id', true), '') IS NULL
|
|
AND NULLIF(current_setting('app.portal_session_id', true), '') IS NULL
|
|
AND p_hostname IS NOT NULL
|
|
AND p_hostname = lower(btrim(p_hostname))
|
|
AND length(p_hostname) BETWEEN 4 AND 253
|
|
AND p_hostname ~ '^[a-z0-9](?:[a-z0-9.-]*[a-z0-9])$'
|
|
AND p_hostname ~ '[.]'
|
|
AND p_hostname !~ '^[0-9.]+$'
|
|
AND p_hostname NOT LIKE '%.localhost'
|
|
AND p_hostname NOT LIKE 'localhost.%'
|
|
AND claim."hostname" = p_hostname
|
|
AND claim."dnsStatus" = 'verified'
|
|
AND claim."verifiedAt" IS NOT NULL
|
|
AND claim."releasedAt" IS NULL
|
|
AND claim."cooldownUntil" IS NULL
|
|
AND domain."status" IN ('provisioning', 'active', 'degraded')
|
|
AND domain."entitlementValidatedAt" IS NOT NULL
|
|
AND domain."paymentAcquisitionId" IS NOT NULL
|
|
AND domain."controllerCommandId" IS NOT NULL
|
|
AND domain."controllerContentHash" IS NOT NULL
|
|
AND domain."disabledAt" IS NULL
|
|
AND domain."deprovisioningStartedAt" IS NULL
|
|
AND domain."deprovisionedAt" IS NULL
|
|
AND domain."releasedAt" IS NULL
|
|
AND domain."cooldownUntil" IS NULL
|
|
AND domain."killSwitchEnabled" = false
|
|
AND public.hivegrid_portal_claim_has_live_entitlement(
|
|
domain."tenantId",
|
|
domain."claimId",
|
|
domain."paymentAcquisitionId"
|
|
)
|
|
AND portal."isPublished" = true
|
|
AND tenant."active" = true
|
|
AND tenant."slug" = lower(btrim(tenant."slug"))
|
|
AND tenant."slug" ~ '^[a-z0-9][a-z0-9-]{1,62}$'
|
|
AND (
|
|
SELECT COUNT(*)
|
|
FROM public."Tenant" AS slug_peer
|
|
WHERE slug_peer."active" = true
|
|
AND lower(slug_peer."slug") = lower(tenant."slug")
|
|
) = 1
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_custom_hostname_health(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_custom_hostname_health(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_custom_hostname_health(text) TO hivegrid_portal;
|
|
|
|
DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_tenant_slug(text);
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_tenant_slug(p_tenant_slug text)
|
|
RETURNS TABLE (
|
|
"tenantId" text,
|
|
"portalId" text,
|
|
"tenantSlug" text,
|
|
"tenantName" text,
|
|
"portalTitle" text,
|
|
"imprintUrl" text,
|
|
"privacyUrl" text,
|
|
"termsUrl" text,
|
|
"tenantActive" boolean,
|
|
"tenantFrozen" boolean
|
|
)
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
WITH active_slug_matches AS (
|
|
SELECT
|
|
tenant.*,
|
|
COUNT(*) OVER () AS slug_match_count
|
|
FROM public."Tenant" AS tenant
|
|
WHERE tenant."active" = true
|
|
AND lower(tenant."slug") = lower(btrim(p_tenant_slug))
|
|
),
|
|
canonical_tenant AS (
|
|
SELECT tenant.*
|
|
FROM active_slug_matches AS tenant
|
|
WHERE tenant.slug_match_count = 1
|
|
AND tenant."slug" = lower(btrim(tenant."slug"))
|
|
AND tenant."slug" ~ '^[a-z0-9][a-z0-9-]{1,62}$'
|
|
)
|
|
SELECT
|
|
tenant."id",
|
|
portal."id",
|
|
tenant."slug",
|
|
tenant."name",
|
|
portal."title",
|
|
configuration."imprintUrl",
|
|
configuration."privacyUrl",
|
|
configuration."termsUrl",
|
|
tenant."active",
|
|
EXISTS (
|
|
SELECT 1
|
|
FROM public."TenantSubscription" AS subscription
|
|
WHERE subscription."tenantId" = tenant."id"
|
|
AND (lower(subscription."status") = 'frozen' OR subscription."frozenAt" IS NOT NULL)
|
|
)
|
|
FROM canonical_tenant AS tenant
|
|
JOIN public."Portal" AS portal ON portal."tenantId" = tenant."id"
|
|
JOIN public."PortalConfiguration" AS configuration
|
|
ON configuration."portalId" = portal."id"
|
|
AND configuration."tenantId" = portal."tenantId"
|
|
WHERE public.hivegrid_portal_customer_feature_enabled()
|
|
AND public.hivegrid_portal_tenant_has_live_entitlement(tenant."id")
|
|
AND portal."isPublished" = true
|
|
AND configuration."imprintUrl" = btrim(configuration."imprintUrl")
|
|
AND length(configuration."imprintUrl") BETWEEN 9 AND 2048
|
|
AND configuration."imprintUrl" ~ '^https://[^[:space:]#/?@]+([/?][^[:space:]#]*)?$'
|
|
AND configuration."privacyUrl" = btrim(configuration."privacyUrl")
|
|
AND length(configuration."privacyUrl") BETWEEN 9 AND 2048
|
|
AND configuration."privacyUrl" ~ '^https://[^[:space:]#/?@]+([/?][^[:space:]#]*)?$'
|
|
AND (
|
|
configuration."termsUrl" IS NULL
|
|
OR (
|
|
configuration."termsUrl" = btrim(configuration."termsUrl")
|
|
AND length(configuration."termsUrl") BETWEEN 9 AND 2048
|
|
AND configuration."termsUrl" ~ '^https://[^[:space:]#/?@]+([/?][^[:space:]#]*)?$'
|
|
)
|
|
)
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_tenant_slug(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_tenant_slug(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_tenant_slug(text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_user_email(p_tenant_slug text, p_email_normalized text)
|
|
RETURNS TABLE (
|
|
"tenantId" text,
|
|
"portalId" text,
|
|
"portalUserId" text,
|
|
"email" text,
|
|
"emailNormalized" text,
|
|
"firstName" text,
|
|
"lastName" text,
|
|
"passwordHash" text,
|
|
"status" text,
|
|
"locale" text,
|
|
"emailVerifiedAt" timestamp with time zone,
|
|
"authRequireEmailVerification" boolean
|
|
)
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
WITH active_slug_matches AS (
|
|
SELECT
|
|
tenant.*,
|
|
COUNT(*) OVER () AS slug_match_count
|
|
FROM public."Tenant" AS tenant
|
|
WHERE tenant."active" = true
|
|
AND lower(tenant."slug") = lower(btrim(p_tenant_slug))
|
|
),
|
|
canonical_tenant AS (
|
|
SELECT tenant.*
|
|
FROM active_slug_matches AS tenant
|
|
WHERE tenant.slug_match_count = 1
|
|
AND tenant."slug" = lower(btrim(tenant."slug"))
|
|
AND tenant."slug" ~ '^[a-z0-9][a-z0-9-]{1,62}$'
|
|
)
|
|
SELECT
|
|
portal_user."tenantId",
|
|
portal_user."portalId",
|
|
portal_user."id",
|
|
portal_user."email",
|
|
portal_user."emailNormalized",
|
|
portal_user."firstName",
|
|
portal_user."lastName",
|
|
portal_user."passwordHash",
|
|
portal_user."status"::text,
|
|
portal_user."locale",
|
|
portal_user."emailVerifiedAt",
|
|
portal."authRequireEmailVerification"
|
|
FROM canonical_tenant AS tenant
|
|
JOIN public."Portal" AS portal ON portal."tenantId" = tenant."id"
|
|
JOIN public."PortalUser" AS portal_user
|
|
ON portal_user."portalId" = portal."id"
|
|
AND portal_user."tenantId" = portal."tenantId"
|
|
WHERE portal_user."emailNormalized" = lower(trim(p_email_normalized))
|
|
AND public.hivegrid_portal_tenant_has_live_entitlement(tenant."id")
|
|
AND portal."isPublished" = true
|
|
AND portal_user."status" IN ('invited', 'active')
|
|
AND portal_user."archivedAt" IS NULL
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_user_email(text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_user_email(text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_user_email(text,text) TO hivegrid_portal;
|
|
|
|
DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_session(text);
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_session(p_token_hash text)
|
|
RETURNS TABLE (
|
|
"tenantId" text,
|
|
"portalId" text,
|
|
"portalUserId" text,
|
|
"portalSessionId" text,
|
|
"tenantSlug" text,
|
|
"tenantFrozen" boolean,
|
|
"portalTitle" text,
|
|
"viewerFirstName" text,
|
|
"viewerLastName" text,
|
|
"viewerLocale" text,
|
|
"expiresAt" timestamp with time zone,
|
|
"origin" text
|
|
)
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
session."tenantId",
|
|
portal_user."portalId",
|
|
session."portalUserId",
|
|
session."id",
|
|
tenant."slug",
|
|
EXISTS (
|
|
SELECT 1
|
|
FROM public."TenantSubscription" AS subscription
|
|
WHERE subscription."tenantId" = tenant."id"
|
|
AND (lower(subscription."status") = 'frozen' OR subscription."frozenAt" IS NOT NULL)
|
|
),
|
|
portal."title",
|
|
portal_user."firstName",
|
|
portal_user."lastName",
|
|
portal_user."locale",
|
|
session."expiresAt" AT TIME ZONE 'UTC',
|
|
session."origin"
|
|
FROM public."PortalSession" AS session
|
|
JOIN public."PortalUser" AS portal_user
|
|
ON portal_user."id" = session."portalUserId"
|
|
AND portal_user."tenantId" = session."tenantId"
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = portal_user."portalId"
|
|
AND portal."tenantId" = portal_user."tenantId"
|
|
JOIN public."Tenant" AS tenant ON tenant."id" = session."tenantId"
|
|
WHERE session."tokenHash" = p_token_hash
|
|
AND public.hivegrid_portal_tenant_has_live_entitlement(tenant."id")
|
|
AND session."expiresAt" > CURRENT_TIMESTAMP
|
|
AND COALESCE(session."lastSeenAt", session."createdAt") > CURRENT_TIMESTAMP - INTERVAL '7 days'
|
|
AND session."revokedAt" IS NULL
|
|
AND NULLIF(btrim(session."origin"), '') IS NOT NULL
|
|
AND portal_user."status" = 'active'
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND portal."isPublished" = true
|
|
AND tenant."active" = true
|
|
AND tenant."slug" = lower(btrim(tenant."slug"))
|
|
AND tenant."slug" ~ '^[a-z0-9][a-z0-9-]{1,62}$'
|
|
AND (
|
|
SELECT COUNT(*)
|
|
FROM public."Tenant" AS slug_peer
|
|
WHERE slug_peer."active" = true
|
|
AND lower(slug_peer."slug") = lower(tenant."slug")
|
|
) = 1
|
|
LIMIT 1
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_session(text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_session(text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_session(text) TO hivegrid_portal;
|
|
|
|
DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_token(text,text);
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_resolve_token(p_token_hash text, p_purpose text, p_requested_ip_hash text)
|
|
RETURNS TABLE (
|
|
"tenantId" text,
|
|
"portalId" text,
|
|
"portalUserId" text,
|
|
"portalTokenId" text,
|
|
"emailNormalized" text,
|
|
"purpose" text,
|
|
"expiresAt" timestamp with time zone
|
|
)
|
|
LANGUAGE sql
|
|
STABLE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
SELECT
|
|
token."tenantId",
|
|
portal_user."portalId",
|
|
token."portalUserId",
|
|
token."id",
|
|
portal_user."emailNormalized",
|
|
token."purpose"::text,
|
|
token."expiresAt" AT TIME ZONE 'UTC'
|
|
FROM public."PortalToken" AS token
|
|
JOIN public."PortalUser" AS portal_user
|
|
ON portal_user."id" = token."portalUserId"
|
|
AND portal_user."tenantId" = token."tenantId"
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = portal_user."portalId"
|
|
AND portal."tenantId" = portal_user."tenantId"
|
|
JOIN public."Tenant" AS tenant ON tenant."id" = token."tenantId"
|
|
WHERE token."tokenHash" = p_token_hash
|
|
AND public.hivegrid_portal_tenant_has_live_entitlement(tenant."id")
|
|
AND token."purpose"::text = lower(trim(p_purpose))
|
|
AND p_requested_ip_hash ~ '^[a-f0-9]{64}$'
|
|
AND (
|
|
token."requestedIpHash" = p_requested_ip_hash
|
|
OR (token."purpose"::text = 'setup' AND token."requestedIpHash" IS NULL)
|
|
)
|
|
AND token."expiresAt" > CURRENT_TIMESTAMP
|
|
AND token."consumedAt" IS NULL
|
|
AND token."revokedAt" IS NULL
|
|
AND (
|
|
(token."purpose"::text = 'setup' AND portal_user."status" = 'invited')
|
|
OR (token."purpose"::text <> 'setup' AND portal_user."status" = 'active')
|
|
)
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND portal."isPublished" = true
|
|
AND tenant."active" = true
|
|
AND tenant."slug" = lower(btrim(tenant."slug"))
|
|
AND tenant."slug" ~ '^[a-z0-9][a-z0-9-]{1,62}$'
|
|
AND (
|
|
SELECT COUNT(*)
|
|
FROM public."Tenant" AS slug_peer
|
|
WHERE slug_peer."active" = true
|
|
AND lower(slug_peer."slug") = lower(tenant."slug")
|
|
) = 1
|
|
LIMIT 1
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_resolve_token(text,text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_resolve_token(text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_resolve_token(text,text,text) TO hivegrid_portal;
|
|
|
|
CREATE OR REPLACE FUNCTION public.hivegrid_portal_consume_token(
|
|
p_token_hash text,
|
|
p_token_id text,
|
|
p_purpose text,
|
|
p_requested_ip_hash text,
|
|
p_expected_tenant_id text,
|
|
p_expected_portal_id text
|
|
)
|
|
RETURNS boolean
|
|
LANGUAGE sql
|
|
VOLATILE
|
|
SECURITY DEFINER
|
|
SET search_path = pg_catalog, public
|
|
SET row_security = off
|
|
AS $function$
|
|
WITH consumed AS (
|
|
UPDATE public."PortalToken" AS token
|
|
SET
|
|
"requestedIpHash" = p_requested_ip_hash,
|
|
"consumedAt" = CURRENT_TIMESTAMP
|
|
FROM public."PortalUser" AS portal_user
|
|
JOIN public."Portal" AS portal
|
|
ON portal."id" = portal_user."portalId"
|
|
AND portal."tenantId" = portal_user."tenantId"
|
|
JOIN public."Tenant" AS tenant
|
|
ON tenant."id" = portal_user."tenantId"
|
|
WHERE session_user = 'hivegrid_portal'
|
|
AND NULLIF(current_setting('app.user_id', true), '') IS NULL
|
|
AND NULLIF(current_setting('app.tenant_id', true), '') = p_expected_tenant_id
|
|
AND NULLIF(current_setting('app.portal_user_id', true), '') = token."portalUserId"
|
|
AND token."id" = p_token_id
|
|
AND token."tokenHash" = p_token_hash
|
|
AND token."tenantId" = p_expected_tenant_id
|
|
AND token."portalUserId" = portal_user."id"
|
|
AND token."tenantId" = portal_user."tenantId"
|
|
AND public.hivegrid_portal_tenant_has_live_entitlement(tenant."id")
|
|
AND token."purpose"::text = lower(trim(p_purpose))
|
|
AND p_requested_ip_hash ~ '^[a-f0-9]{64}$'
|
|
AND (
|
|
token."requestedIpHash" = p_requested_ip_hash
|
|
OR (token."purpose"::text = 'setup' AND token."requestedIpHash" IS NULL)
|
|
)
|
|
AND token."expiresAt" > CURRENT_TIMESTAMP
|
|
AND token."consumedAt" IS NULL
|
|
AND token."revokedAt" IS NULL
|
|
AND portal."id" = p_expected_portal_id
|
|
AND (
|
|
(token."purpose"::text = 'setup' AND portal_user."status" = 'invited')
|
|
OR (token."purpose"::text <> 'setup' AND portal_user."status" = 'active')
|
|
)
|
|
AND portal_user."archivedAt" IS NULL
|
|
AND portal."isPublished" = true
|
|
AND tenant."active" = true
|
|
AND tenant."slug" = lower(btrim(tenant."slug"))
|
|
AND tenant."slug" ~ '^[a-z0-9][a-z0-9-]{1,62}$'
|
|
AND (
|
|
SELECT COUNT(*)
|
|
FROM public."Tenant" AS slug_peer
|
|
WHERE slug_peer."active" = true
|
|
AND lower(slug_peer."slug") = lower(tenant."slug")
|
|
) = 1
|
|
RETURNING 1
|
|
)
|
|
SELECT EXISTS (SELECT 1 FROM consumed)
|
|
$function$;
|
|
ALTER FUNCTION public.hivegrid_portal_consume_token(text,text,text,text,text,text) OWNER TO hivegrid_rls_definer;
|
|
REVOKE ALL ON FUNCTION public.hivegrid_portal_consume_token(text,text,text,text,text,text) FROM PUBLIC, hivegrid_app, hivegrid_worker, hivegrid_authentik_jit;
|
|
GRANT EXECUTE ON FUNCTION public.hivegrid_portal_consume_token(text,text,text,text,text,text) TO hivegrid_portal;
|
|
|
|
RESET ROLE;
|
|
REVOKE CREATE ON SCHEMA public FROM hivegrid_rls_definer;
|
|
|
|
COMMIT;
|
|
|
|
-- Inverse merge SQL (execute only during an approved rollback):
|
|
-- REVOKE ALL PRIVILEGES ON ALL TABLES IN SCHEMA public FROM hivegrid_portal;
|
|
-- REVOKE INSERT ("id", "tenantId", "eventType", "payload") ON "OutboxEvent" FROM hivegrid_rls_definer;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_resolve_custom_hostname(text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_resolve_custom_hostname_health(text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_resolve_tenant_slug(text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_resolve_project_document(text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_resolve_user_email(text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_resolve_session(text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_resolve_token(text,text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_consume_token(text,text,text,text,text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_can_read_stage_visibility(text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_can_read_project_document(text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_append_audit(text,text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_append_setup_denial_audit(text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_emit_auth_event(text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_reserve_upload(text,text,text,text,text,text,text,bigint,text,text,bigint) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_complete_upload(text,text,text,text,text,text,text,bigint,text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_fail_upload(text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_append_activity(text,text,text,jsonb) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_notify_project_leader(text,text,text,text,text,text,jsonb) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_record_inbox_event(text,text,text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_mark_effects_completed(text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_resolve_complaint_form(text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_submit_complaint(text,text,text,text,jsonb,text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_resolve_lifecycle_profile() FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_resolve_deletion_password_hash() FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_request_deletion(text,text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_cancel_deletion(text) FROM hivegrid_portal;
|
|
-- REVOKE EXECUTE ON FUNCTION public.hivegrid_portal_record_gdpr_export_download(text) FROM hivegrid_portal;
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_tenant_slug(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_custom_hostname(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_custom_hostname_health(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_claim_has_live_entitlement(text,text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_tenant_has_live_entitlement(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_project_document(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_user_email(text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_session(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_token(text,text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_consume_token(text,text,text,text,text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_can_read_stage_visibility(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_can_read_project_document(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_append_audit(text,text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_append_setup_denial_audit(text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_emit_auth_event(text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_reserve_upload(text,text,text,text,text,text,text,bigint,text,text,bigint);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_tenant_storage_capacity_bytes(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_complete_upload(text,text,text,text,text,text,text,bigint,text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_fail_upload(text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_append_activity(text,text,text,jsonb);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_notify_project_leader(text,text,text,text,text,text,jsonb);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_record_inbox_event(text,text,text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_mark_effects_completed(text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_complaint_form(text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_submit_complaint(text,text,text,text,jsonb,text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_lifecycle_profile();
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_resolve_deletion_password_hash();
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_request_deletion(text,text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_cancel_deletion(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_record_gdpr_export_download(text);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_require_project_access(text,boolean,boolean,boolean);
|
|
-- DROP FUNCTION IF EXISTS public.hivegrid_portal_require_active_context(boolean);
|
|
-- REVOKE UPDATE ("privacyNoticeAcknowledgedAt", "privacyNoticeAcknowledgedUrl") ON "PortalUser" FROM hivegrid_portal;
|
|
-- REVOKE UPDATE ("requestedIpHash", "consumedAt") ON "PortalToken" FROM hivegrid_rls_definer;
|
|
-- DROP INDEX IF EXISTS "PortalToken_one_live_setup_per_user_key";
|
|
-- ALTER TABLE "PortalToken" DROP CONSTRAINT IF EXISTS "PortalToken_requestedIpHash_binding_check";
|
|
-- ALTER TABLE "PortalUser" DROP CONSTRAINT IF EXISTS "PortalUser_privacyAcknowledgement_pair_check";
|
|
-- DROP each hg_portal_* policy above; core app/worker policies remain intact.
|