UNPKG

@schamane/small-graphql-mongoose-middleware

Version:

![Check Code](https://github.com/schamane/small-graphql-mongoose-middleware/workflows/Check%20Code/badge.svg)

49 lines (48 loc) 1.88 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.onlyWithAdminRole = exports.authenticated = exports.assertRole = exports.hasRole = void 0; const apollo_server_express_1 = require("apollo-server-express"); const lodash_1 = require("lodash"); const validContext = (ctx) => !(0, lodash_1.isNil)(ctx.id); const hasRole = (ctx, group) => { if (!validContext(ctx) || !ctx.groups) { // eslint-disable-next-line no-console console.error('GrapqhlContext for user', JSON.stringify(ctx.id), JSON.stringify(ctx.groups)); throw new apollo_server_express_1.AuthenticationError(`No user context!`); } return (0, lodash_1.includes)(ctx.groups, group); }; exports.hasRole = hasRole; const assertRole = (ctx) => { if (!validContext(ctx)) { throw new apollo_server_express_1.AuthenticationError(`No user context!`); } }; exports.assertRole = assertRole; // eslint-disable-next-line @typescript-eslint/no-explicit-any const authenticated = (next) => (...args) => { if (!validContext(args[2])) { throw new apollo_server_express_1.AuthenticationError(`Forbidden`); } return next(...args); }; exports.authenticated = authenticated; const onlyWithAdminRole = (next, group = 'admin') => (...args) => { const context = args[2]; if (!(0, lodash_1.includes)(context.groups, group)) { throw new apollo_server_express_1.AuthenticationError(`Missing admin permissions!`); } return next(...args); }; exports.onlyWithAdminRole = onlyWithAdminRole; /* for express export const onlyAdminAccess = (req: Request, res: Response, done: () => void): void => { const isAdmin = (request: Request): boolean => includes(request.user.groups, ACCESS_ROLES.ADMIN); if (!isAdmin(req)) { res.statusCode = 403; return; } done(); }; */ //# sourceMappingURL=graphql-auth.js.map