From 4210c9b38f9053f6720a6bebaadefd24c542eaa9 Mon Sep 17 00:00:00 2001
From: Arda Serdar Pektezol <1669855+pektezol@users.noreply.github.com>
Date: Thu, 31 Oct 2024 22:06:00 +0300
Subject: backend: better auth check, audit logging

---
 backend/database/functions.sql | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

(limited to 'backend/database/functions.sql')

diff --git a/backend/database/functions.sql b/backend/database/functions.sql
index ca33a60..6a6f6d2 100644
--- a/backend/database/functions.sql
+++ b/backend/database/functions.sql
@@ -1,3 +1,17 @@
+CREATE OR REPLACE FUNCTION log_audit() RETURNS TRIGGER AS $$
+BEGIN
+    INSERT INTO audit (table_name, operation_type, old_data, new_data, changed_by)
+    VALUES (
+        TG_TABLE_NAME,
+        TG_OP,
+        CASE WHEN TG_OP = 'DELETE' OR TG_OP = 'UPDATE' THEN row_to_json(OLD) ELSE NULL END,
+        CASE WHEN TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN row_to_json(NEW) ELSE NULL END,
+        current_setting('app.user_id')::TEXT
+    );
+    RETURN NULL;
+END;
+$$ LANGUAGE plpgsql;
+
 CREATE OR REPLACE FUNCTION get_rankings_singleplayer()
 RETURNS TABLE (
     steam_id TEXT,
-- 
cgit v1.2.3

