Fix: Use admin client for audit logging to ensure logs are written even without user session
This commit is contained in:
@@ -1,4 +1,5 @@
|
|||||||
import { createClient } from "@/lib/supabase/server"
|
import { createClient } from "@/lib/supabase/server"
|
||||||
|
import { createAdminClient } from "@/lib/supabase/admin"
|
||||||
|
|
||||||
export async function logAction(
|
export async function logAction(
|
||||||
action: string,
|
action: string,
|
||||||
@@ -9,15 +10,30 @@ export async function logAction(
|
|||||||
const supabase = await createClient()
|
const supabase = await createClient()
|
||||||
const { data: { user } } = await supabase.auth.getUser()
|
const { data: { user } } = await supabase.auth.getUser()
|
||||||
|
|
||||||
console.log('Current user for audit log:', user?.id)
|
// Use admin client to bypass RLS policies for insertion
|
||||||
if (!user) {
|
const adminClient = await createAdminClient()
|
||||||
console.error('No user found for audit log')
|
|
||||||
|
if (!adminClient) {
|
||||||
|
console.error("Admin client not available for logging. Check SUPABASE_SERVICE_ROLE_KEY.")
|
||||||
|
// Fallback to regular client if admin not available (might fail due to RLS)
|
||||||
|
try {
|
||||||
|
const { error } = await supabase.from('audit_logs').insert({
|
||||||
|
user_id: user?.id, // Might fail if user is null and RLS requires auth
|
||||||
|
action,
|
||||||
|
entity_type: entityType,
|
||||||
|
entity_id: entityId,
|
||||||
|
details,
|
||||||
|
})
|
||||||
|
if (error) console.error("Audit log error (fallback):", error)
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Audit log exception (fallback):", err)
|
||||||
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const { error } = await supabase.from('audit_logs').insert({
|
const { error } = await adminClient.from('audit_logs').insert({
|
||||||
user_id: user.id,
|
user_id: user?.id || null, // Allow null user_id if action is anonymous/system
|
||||||
action,
|
action,
|
||||||
entity_type: entityType,
|
entity_type: entityType,
|
||||||
entity_id: entityId,
|
entity_id: entityId,
|
||||||
|
|||||||
Reference in New Issue
Block a user