UNPKG

stackpress

Version:

Incept is a content management framework.

61 lines (60 loc) 1.64 kB
import { isObject } from '@stackpress/ingest/helpers'; import Exception from '../Exception.js'; export function authorize(req, res) { const authorization = req.headers.get('authorization'); if (!authorization) { unauthorized(res); return false; } const [, token] = authorization.split(' '); if (!token || !token.trim().length) { unauthorized(res); return false; } const [id, secret] = token.split(':'); if (!id || !id.trim().length) { unauthorized(res); return false; } if (req.method.toUpperCase() !== 'GET' && (!secret || !secret?.trim().length)) { unauthorized(res); return false; } return { token: token.trim(), id: id.trim(), secret: secret?.trim() || '' }; } ; export function unauthorized(res) { res.setError(Exception .for('Unauthorized') .withCode(401) .toResponse()); } ; export function validData(assert, data) { for (const [key, value] of Object.entries(assert)) { if (typeof data[key] === 'undefined') return false; if (Array.isArray(value)) { if (!Array.isArray(data[key])) return false; if (!value.every(item => data[key].includes(item))) return false; } else if (isObject(value)) { if (!isObject(data[key])) return false; if (!validData(value, data[key])) return false; } else if (data[key] !== value) { return false; } } return true; } ;