@sphereon/ssi-express-support
Version:
148 lines • 7.42 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkAuth = exports.isUserAuthenticated = exports.isUserNotAuthenticated = exports.checkAuthorizationOnly = exports.checkAuthenticationOnly = exports.checkUserIsInRole = void 0;
exports.copyGlobalAuthToEndpoint = copyGlobalAuthToEndpoint;
exports.copyGlobalAuthToEndpoints = copyGlobalAuthToEndpoints;
const passport_1 = __importDefault(require("passport"));
const express_utils_1 = require("./express-utils");
const types_1 = require("./types");
const checkUserIsInRole = (opts) => (req, res, next) => {
if (!(opts === null || opts === void 0 ? void 0 : opts.roles) || opts.roles.length === 0) {
return next();
}
const roles = Array.isArray(opts.roles) ? opts.roles : [opts.roles];
if (!(req === null || req === void 0 ? void 0 : req.user) || !('role' in req.user)) {
return res.status(401).end();
}
// @ts-ignore
const hasRole = roles.find((role) => req.user.role.toLowerCase() === role.toLowerCase());
if (!hasRole) {
return res.status(403).end();
}
return next();
};
exports.checkUserIsInRole = checkUserIsInRole;
const checkAuthenticationImpl = (req, res, next, opts) => {
var _a, _b, _c, _d, _e, _f;
const defaultCallback = (err, user, _info, _status) => {
if (err) {
const message = 'message' in err ? err.message : err;
console.log('Authentication failed, error: ' + JSON.stringify(message));
return next({ statusCode: 403, message });
}
else if (!user) {
console.log('Authentication failed, no user object present in request. Redirecting to /login');
// todo: configuration option
return res.redirect('/authentication/login');
}
if (options.session) {
req.logIn(user, function (err) {
if (err) {
return next(err);
}
});
}
/* /!*if (options.session) {
req.logIn(user, function (err) {
if (err) {
return next(err)
}
return res.redirect('/')
})
}*!/*/
return next();
};
if (!opts || !opts.authentication || opts.authentication.enabled === false) {
return next();
}
if (!opts.authentication.strategy) {
console.log(`Authentication enabled, but no strategy configured. All auth request will be denied!`);
return res.status(401).end();
}
const options = Object.assign(Object.assign({}, (_a = opts === null || opts === void 0 ? void 0 : opts.authentication) === null || _a === void 0 ? void 0 : _a.strategyOptions), { authInfo: ((_b = opts === null || opts === void 0 ? void 0 : opts.authentication) === null || _b === void 0 ? void 0 : _b.authInfo) !== false, session: ((_c = opts === null || opts === void 0 ? void 0 : opts.authentication) === null || _c === void 0 ? void 0 : _c.session) !== false });
const callback = (_e = (_d = opts === null || opts === void 0 ? void 0 : opts.authentication) === null || _d === void 0 ? void 0 : _d.callback) !== null && _e !== void 0 ? _e : (((_f = opts === null || opts === void 0 ? void 0 : opts.authentication) === null || _f === void 0 ? void 0 : _f.useDefaultCallback) ? defaultCallback : undefined);
passport_1.default.authenticate(opts.authentication.strategy, options, callback).call(this, req, res, next);
};
const checkAuthorizationImpl = (req, res, next, opts) => {
if (!opts || !opts.authentication || !opts.authorization || opts.authentication.enabled === false || (opts === null || opts === void 0 ? void 0 : opts.authorization.enabled) === false) {
return next();
}
/*if (!req.isAuthenticated()) {
return sendErrorResponse(res, 403, 'Authorization with an unauthenticated request is not possible')
}*/
const authorization = opts.authorization;
if (!authorization.enforcer && (!authorization.requireUserInRoles || authorization.requireUserInRoles.length === 0)) {
console.log(`Authorization enabled for endpoint, but no enforcer or roles supplied`);
return res.status(401).end();
}
if (authorization.requireUserInRoles && authorization.requireUserInRoles.length > 0) {
(0, exports.checkUserIsInRole)({ roles: authorization.requireUserInRoles });
}
if (authorization.enforcer) {
const enforcer = authorization.enforcer;
const permitted = enforcer.enforceSync(req.user, opts.resource, opts.operation);
if (!permitted) {
console.log(`Access to ${opts.resource} and op ${opts.operation} not allowed for ${req.user}`);
return res.status(403).end();
}
}
return next();
};
const checkAuthenticationOnly = (opts) => (req, res, next) => {
// executeRequestHandlers(req, res, next, opts)
return checkAuthenticationImpl(req, res, next, opts);
};
exports.checkAuthenticationOnly = checkAuthenticationOnly;
const checkAuthorizationOnly = (opts) => (req, res, next) => {
// executeRequestHandlers(req, res, next, opts)
return checkAuthorizationImpl(req, res, next, opts);
};
exports.checkAuthorizationOnly = checkAuthorizationOnly;
const isUserNotAuthenticated = (req, res, next) => {
if (!req.user) {
next();
}
};
exports.isUserNotAuthenticated = isUserNotAuthenticated;
const isUserAuthenticated = (req, res, next) => {
if (!req.user) {
return (0, express_utils_1.sendErrorResponse)(res, 401, 'Authentication required');
}
else {
return next();
}
};
exports.isUserAuthenticated = isUserAuthenticated;
const checkAuth = (opts) => {
const handlers = [];
handlers.push((0, exports.checkAuthenticationOnly)(opts));
handlers.push((0, exports.checkAuthorizationOnly)(opts));
(opts === null || opts === void 0 ? void 0 : opts.handlers) && handlers.push(...opts.handlers);
return handlers;
};
exports.checkAuth = checkAuth;
function copyGlobalAuthToEndpoint(args) {
var _a, _b, _c;
const opts = args === null || args === void 0 ? void 0 : args.opts;
const key = args === null || args === void 0 ? void 0 : args.key;
if (!opts || !key || !(0, types_1.hasEndpointOpts)(opts)) {
return;
}
if (key === 'basePath') {
// make sure to not copy base path over, as we use these at the global router, and this would repeat the path
return;
}
if ((_a = opts.endpointOpts) === null || _a === void 0 ? void 0 : _a.globalAuth) {
if (((_b = opts.endpointOpts[key]) === null || _b === void 0 ? void 0 : _b.disableGlobalAuth) === true) {
return;
}
opts.endpointOpts[key] = Object.assign(Object.assign({}, opts.endpointOpts[key]), { endpoint: Object.assign(Object.assign({}, opts.endpointOpts.globalAuth), (_c = opts.endpointOpts[key]) === null || _c === void 0 ? void 0 : _c.endpoint) });
}
}
function copyGlobalAuthToEndpoints(args) {
args === null || args === void 0 ? void 0 : args.keys.forEach((key) => copyGlobalAuthToEndpoint({ opts: args === null || args === void 0 ? void 0 : args.opts, key }));
}
//# sourceMappingURL=auth-utils.js.map