All files / src/routes admin-devices.js

100% Statements 83/83
100% Branches 36/36
100% Functions 9/9
100% Lines 76/76

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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188                    2x 2x 2x 2x 2x 2x       2x 13x 13x   12x 12x 12x   12x 34x     11x 4x 8x                 23x   8x       11x 11x   11x   1x 1x           2x 7x 7x   6x   6x 2x     4x                   4x   3x   1x 1x           2x 4x 4x   3x 3x   2x   2x   1x       1x           2x 4x 4x   3x 3x   2x 1x     1x   1x       1x           2x 10x 10x   9x     9x 8x 1x   7x   7x     7x                   7x 7x 7x 4x 4x 4x         3x 3x       7x   1x       1x       2x  
/**
 * Admin device bindings routes — list, search, get, create, unbind devices.
 *
 * GET    /admin/devices              → List all device bindings (paginated, searchable)
 * POST   /admin/devices              → Create/re-seed a device binding (admin only)
 * GET    /admin/devices/user/:uniqueId → Get all devices for a user
 * GET    /admin/devices/:deviceId    → Get single device binding
 * DELETE /admin/devices/:deviceId    → Unbind device (delete binding)
 */
 
const router = require('express').Router();
const { db } = require('../utils/firebase');
const { requireAdmin } = require('../middleware/auth');
const { generateId, now } = require('../utils/helpers');
const { sendSystemPm } = require('../utils/system-pm');
const log = require('../utils/log');
 
// ─── List all device bindings (paginated + searchable) ──────────
 
router.get('/admin/devices', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const searchQuery = (req.query.q || '').toLowerCase().trim();
    const limit = Math.min(Math.max(Number.parseInt(req.query.limit, 10) || 50, 1), 200);
    const offset = Math.max(Number.parseInt(req.query.offset, 10) || 0, 0);
 
    const snap = await db.collection('deviceBindings').get();
    let devices = snap.docs.map((doc) => ({ id: doc.id, ...doc.data() }));
 
    // In-memory search (Firestore doesn't support full-text search)
    if (searchQuery) {
      devices = devices.filter((device) => {
        const searchable = [
          device.id,
          device.uniqueId,
          device.manufacturer,
          device.model,
          device.lastIp,
          device.isp,
        ]
          .filter(Boolean)
          .map((v) => String(v).toLowerCase())
          .join(' ');
        return searchable.includes(searchQuery);
      });
    }
 
    const total = devices.length;
    const paginated = devices.slice(offset, offset + limit);
 
    res.json({ devices: paginated, total });
  } catch (err) {
    log.error('admin-devices', 'Error listing device bindings', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Create / re-seed a device binding ───────────────────────────
 
router.post('/admin/devices', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const { deviceId, uniqueId, manufacturer, model, lastIp, isp } = req.body;
 
    if (!deviceId || uniqueId === undefined) {
      return res.status(400).json({ error: 'deviceId and uniqueId are required' });
    }
 
    const bindingData = {
      deviceId,
      uniqueId: Number(uniqueId),
      manufacturer: manufacturer || 'Unknown',
      model: model || 'Unknown',
      lastIp: lastIp || null,
      isp: isp || null,
      boundAt: now(),
    };
 
    await db.doc(`deviceBindings/${deviceId}`).set(bindingData);
 
    res.json({ id: deviceId, ...bindingData });
  } catch (err) {
    log.error('admin-devices', 'Error creating device binding', { error: err.message });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Get all devices for a user ─────────────────────────────────
 
router.get('/admin/devices/user/:uniqueId', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const uniqueId = Number(req.params.uniqueId);
    const snap = await db.collection('deviceBindings').where('uniqueId', '==', uniqueId).get();
 
    const devices = snap.docs.map((d) => ({ id: d.id, ...d.data() }));
 
    res.json({ devices });
  } catch (err) {
    log.error('admin-devices', 'Error fetching devices for user', {
      uniqueId: req.params.uniqueId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Get single device binding ──────────────────────────────────
 
router.get('/admin/devices/:deviceId', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const deviceId = req.params.deviceId;
    const snap = await db.doc(`deviceBindings/${deviceId}`).get();
 
    if (!snap.exists) {
      return res.status(404).json({ error: 'Device binding not found' });
    }
 
    res.json({ id: snap.id, ...snap.data() });
  } catch (err) {
    log.error('admin-devices', 'Error fetching device binding', {
      deviceId: req.params.deviceId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
// ─── Unbind device ──────────────────────────────────────────────
 
router.delete('/admin/devices/:deviceId', async (req, res) => {
  try {
    if (await requireAdmin(req, res)) return;
 
    const deviceId = req.params.deviceId;
 
    // Check if binding exists
    const snap = await db.doc(`deviceBindings/${deviceId}`).get();
    if (!snap.exists) {
      return res.status(404).json({ error: 'Device binding not found' });
    }
    const deviceData = snap.data();
 
    await db.doc(`deviceBindings/${deviceId}`).delete();
 
    // Audit log
    await db.doc(`adminAuditLog/${generateId()}`).set({
      adminId: req.auth.uid,
      action: 'UNBIND_DEVICE',
      targetDeviceId: deviceId,
      details: `Unbound device ${deviceId}`,
      createdAt: now(),
    });
 
    // Send system PM to the bound user. Track failure for admin UI's
    // PartialFailureToast — `pms: { failed, total }` is the standard shape.
    let pmFailed = 0;
    let pmTotal = 0;
    if (deviceData.uniqueId) {
      pmTotal = 1;
      try {
        await sendSystemPm(
          deviceData.uniqueId,
          'Your device binding has been reset by a moderator.',
        );
      } catch (e) {
        log.warn('system-pm', 'Failed to send', { error: e.message });
        pmFailed = 1;
      }
    }
 
    res.json({ success: true, pms: { failed: pmFailed, total: pmTotal } });
  } catch (err) {
    log.error('admin-devices', 'Error unbinding device', {
      deviceId: req.params.deviceId,
      error: err.message,
    });
    res.status(500).json({ error: 'Internal server error' });
  }
});
 
module.exports = router;