All files / services/shared/validation/src org-auth.js

18.03% Statements 22/122
100% Branches 2/2
0% Functions 0/7
18.03% Lines 22/122

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 1233x 3x 3x 3x 3x 3x 3x                               3x                             3x                       3x                           3x       3x                                           3x                                               3x 3x 3x 3x 3x 3x 3x 3x 3x  
const axios = require('axios');
 
const CONFIG_SERVICE_URL = process.env.CONFIG_SERVICE_URL || 'http://config-service:8000';
const CONFIG_PREFIX = 'config:';
 
let redisClient = null;
 
function getRedis() {
  if (redisClient) return redisClient;
  try {
    const Redis = require('ioredis');
    const redisUrl = process.env.REDIS_URL || 'redis://redis:6379';
    redisClient = new Redis(redisUrl, {
      retryStrategy: (times) => Math.min(times * 50, 2000),
      maxRetriesPerRequest: 1,
      lazyConnect: true
    });
  } catch (e) {
    console.error('[org-auth] Redis not available:', e.message);
  }
  return redisClient;
}
 
async function getUserOrganizations(userId, token) {
  try {
    const response = await axios.get(
      `${CONFIG_SERVICE_URL}/users/${userId}/organizations`,
      { headers: { 'Authorization': `Bearer ${token}` }, timeout: 5000 }
    );
    if (response.data?.success) {
      return response.data.data.organizations.map(o => o.id);
    }
  } catch (error) {
    console.error(`[org-auth] Error fetching orgs for user ${userId}:`, error.message);
  }
  return [];
}
 
async function getConfigFromRedis(configId) {
  try {
    const redis = getRedis();
    const key = `${CONFIG_PREFIX}${configId}`;
    const data = await redis.get(key);
    if (data) return JSON.parse(data);
  } catch (error) {
    console.error('[org-auth] Redis error:', error.message);
  }
  return null;
}
 
function extractUserId(req) {
  const authHeader = req.headers['authorization'];
  if (!authHeader) return null;
  const token = authHeader.split(' ')[1];
  if (!token) return null;
  try {
    const base64Payload = token.split('.')[1];
    const padding = 4 - base64Payload.length % 4;
    const base64 = padding < 4 ? base64Payload + '='.repeat(padding) : base64Payload;
    const payload = JSON.parse(Buffer.from(base64, 'base64').toString('utf-8'));
    return payload.userId || null;
  } catch { return null; }
}
 
function extractOrganizationId(req) {
  return req.params.organizationId || req.body?.organizationId || null;
}
 
async function resolveOrgFromRequest(req) {
  const authHeader = req.headers['authorization'];
  const configId = req.headers['x-config-id'];

  if (authHeader) {
    const userId = extractUserId(req);
    if (!userId) return { method: null, userId: null, organizationId: null };
    const token = authHeader.split(' ')[1];
    const orgs = await getUserOrganizations(userId, token);
    return { method: 'jwt', userId, organizationId: null, organizations: orgs };
  }

  if (configId) {
    const config = await getConfigFromRedis(configId);
    if (config) {
      return { method: 'config-id', userId: config.userId || null, organizationId: config.organizationId || null };
    }
  }

  return { method: null, userId: null, organizationId: null };
}
 
async function checkOrgAccess(resourceOrgId, req) {
  const authHeader = req.headers['authorization'];
  const configId = req.headers['x-config-id'];

  if (!authHeader && !configId) return false;
  if (!resourceOrgId) return false;

  if (authHeader) {
    const userId = extractUserId(req);
    if (!userId) return false;
    const token = authHeader.split(' ')[1];
    const orgs = await getUserOrganizations(userId, token);
    return orgs.includes(resourceOrgId);
  }

  if (configId) {
    const config = await getConfigFromRedis(configId);
    if (!config) return false;
    return config.organizationId === resourceOrgId;
  }

  return false;
}
 
module.exports = {
  getUserOrganizations,
  getConfigFromRedis,
  extractUserId,
  extractOrganizationId,
  resolveOrgFromRequest,
  checkOrgAccess
};