verae-fleet/src/iam-gate.js

35 lines
1.5 KiB
JavaScript

export function iamBase() {
return (process.env.STAFF_IAM_URL || '').replace(/\/$/, '');
}
export async function iamCheck(req, permission) {
const base = iamBase();
if (!base) {
if (process.env.STAFF_AUTH === '1') {
const login = (process.env.STAFF_SESSION_URL || 'http://127.0.0.1:3027').replace(/\/$/, '');
const r = await fetch(`${login}/check`, { headers: { cookie: req.headers.cookie || '' } }).catch(() => null);
return { ok: Boolean(r && r.ok) };
}
return { ok: true, skipped: true };
}
const q = permission ? `?permission=${encodeURIComponent(permission)}` : '';
const r = await fetch(`${base}/check${q}`, {
headers: { cookie: req.headers.cookie || '', authorization: req.headers.authorization || '' },
}).catch(() => null);
if (!r) return { ok: false, status: 502 };
const body = await r.json().catch(() => ({}));
return { ok: r.ok, status: r.status, ...body };
}
export async function denyOrRedirect(req, res, json, { permission, html }) {
const out = await iamCheck(req, permission);
if (out.ok) return true;
const login = iamBase() || (process.env.STAFF_SESSION_URL || 'http://127.0.0.1:3028').replace(/\/$/, '');
if (html) {
res.writeHead(302, { location: `${login}/login?next=${encodeURIComponent('http://' + (req.headers.host || '127.0.0.1') + '/')}` });
res.end();
return false;
}
json(out.status === 403 ? 403 : 401, { error: out.reason || 'unauthorized', permission });
return false;
}