All files / src/routes admin-audit-log.js

92.85% Statements 78/84
75.29% Branches 64/85
70% Functions 7/10
95.94% Lines 71/74

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164              69x 69x 69x   69x       69x 5x 5x   4x         3x 3x 3x 4x 4x 4x   3x   3x 3x 4x                       3x 3x 3x   1x 1x           69x 25x 25x         24x 24x 24x 24x 24x 24x 24x 24x             24x         23x 23x 23x 23x 32x 32x 32x   23x   23x           23x 2x 2x                   23x     4x 2x 2x 1x 1x     23x 1x   23x                     23x 5x 5x 4x     23x 4x 4x 3x           23x 23x 23x   23x   1x 1x       69x  
/**
 * Admin audit log routes.
 *
 * GET  /admin/audit-log        -> list entries, filterable and paginated
 * GET  /admin/audit-log/export -> CSV export
 */
 
const router = require('express').Router();
const { db } = require('../utils/firebase');
const log = require('../utils/log');
 
const { requireAdmin } = require('../middleware/auth'); // shared — live claim check
 
// ─── GET /admin/audit-log/export ────────────────────────────────
 
router.get('/admin/audit-log/export', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const [auditSnap, adminSnap, modSnap] = await Promise.all([
      db.collection('auditLog').orderBy('timestamp', 'desc').get(),
      db.collection('adminAuditLog').orderBy('timestamp', 'desc').get(),
      db.collection('moderationLog').orderBy('timestamp', 'desc').get(),
    ]);
    const seen = new Set();
    const entries = [];
    for (const d of [...adminSnap.docs, ...auditSnap.docs, ...modSnap.docs]) {
      Iif (seen.has(d.id)) continue;
      seen.add(d.id);
      entries.push(d.data());
    }
    entries.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
 
    const csv = ['adminUid,actionType,targetType,targetId,details,timestamp'];
    for (const e of entries) {
      csv.push(
        [
          e.adminUid || '',
          e.actionType || e.action || '',
          e.targetType || '',
          e.targetId || '',
          JSON.stringify(e.details || {}),
          e.timestamp || '',
        ].join(','),
      );
    }
 
    res.set('Content-Type', 'text/csv');
    res.set('Content-Disposition', 'attachment; filename=audit-log.csv');
    res.send(csv.join('\n'));
  } catch (err) {
    log.error('audit-log', 'Export failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── GET /admin/audit-log ───────────────────────────────────────
 
router.get('/admin/audit-log', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    // Accept both canonical and shortened query param names so the admin
    // panel frontend (which uses `action`, `admin`, `target`, `start`, `end`)
    // and the test infra can both call this endpoint.
    const adminUid = req.query.adminUid || req.query.admin;
    const actionType = req.query.actionType || req.query.action;
    const targetType = req.query.targetType;
    const targetId = req.query.target;
    const from = req.query.from || req.query.start;
    const to = req.query.to || req.query.end;
    const page = parseInt(req.query.page, 10) || 1;
    const pageSize = Math.min(parseInt(req.query.pageSize, 10) || 50, 100);
 
    // Query all three audit collections so every admin action is visible
    // regardless of which collection it was written to:
    //   - auditLog: merge actions, legacy entries
    //   - adminAuditLog: canonical admin actions
    //   - moderationLog: suggestion approve/reject/overturn/edit actions
    const [auditSnap, adminSnap, modSnap] = await Promise.all([
      db.collection('auditLog').orderBy('timestamp', 'desc').get(),
      db.collection('adminAuditLog').orderBy('timestamp', 'desc').get(),
      db.collection('moderationLog').orderBy('timestamp', 'desc').get(),
    ]);
    const totalSize = Math.max(auditSnap.size || 0, adminSnap.size || 0, modSnap.size || 0);
    const seen = new Set();
    const merged = [];
    for (const d of [...adminSnap.docs, ...auditSnap.docs, ...modSnap.docs]) {
      Iif (seen.has(d.id)) continue;
      seen.add(d.id);
      merged.push({ id: d.id, ...d.data() });
    }
    merged.sort((a, b) => (b.timestamp || 0) - (a.timestamp || 0));
 
    let entries = merged;
 
    // Apply filters client-side (Firestore limitation with multiple inequalities).
    // Admin filter uses case-insensitive substring match across both
    // adminUid and adminName so searching for "admin" matches entries
    // with adminUid="admin1" or adminName="admin".
    if (adminUid) {
      const needle = adminUid.toLowerCase();
      entries = entries.filter(
        (e) =>
          String(e.adminUid || '')
            .toLowerCase()
            .includes(needle) ||
          String(e.adminName || '')
            .toLowerCase()
            .includes(needle),
      );
    }
    if (actionType) {
      // Match either the exact action or any action whose last segment
      // matches (e.g. "suggestion_approve" matches "approve" filter).
      entries = entries.filter((e) => {
        const act = e.actionType || e.action || '';
        if (act === actionType) return true;
        const tail = act.split('_').pop();
        return tail === actionType;
      });
    }
    if (targetType) {
      entries = entries.filter((e) => e.targetType === targetType);
    }
    Iif (targetId) {
      // `target` query param is overloaded: the UI's filter dropdown can send
      // a target TYPE (e.g. "suggestion") or a specific target ID substring.
      // Match either: exact targetType OR substring id.
      entries = entries.filter(
        (e) =>
          e.targetType === targetId ||
          String(e.targetId || '').includes(targetId) ||
          String(e.target || '').includes(targetId),
      );
    }
    if (from) {
      const fromTs = new Date(from).getTime();
      if (!isNaN(fromTs)) {
        entries = entries.filter((e) => (e.timestamp || 0) >= fromTs);
      }
    }
    if (to) {
      const toTs = new Date(to).getTime() + 86400000;
      if (!isNaN(toTs)) {
        entries = entries.filter((e) => (e.timestamp || 0) <= toTs);
      }
    }
 
    // Use snap.size for total when available (supports large collections
    // where not all docs are returned in the docs array)
    const total = Math.max(totalSize, entries.length);
    const offset = (page - 1) * pageSize;
    const paged = entries.slice(offset, offset + pageSize);
 
    res.json({ entries: paged, total, page, pageSize });
  } catch (err) {
    log.error('audit-log', 'List failed', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;