UNPKG

@restmatic/jwt-session

Version:

Provides Authentication to the RestMatic platform.

156 lines (153 loc) 6.25 kB
"use strict"; /** * @file JWTuser * @author Jim Bulkowski <jim.b@paperelectron.com> * @project jwt-session * @license MIT {@link http://opensource.org/licenses/MIT} */ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const plugin_tools_1 = require("@pomegranate/plugin-tools"); const fp_1 = require("lodash/fp"); //@ts-ignore const mutableExtend = fp_1.extend.convert({ immutable: false }); const tsGenerator = `// Generated by the Pomegranate cli on {{creationDate}} // name: {{name}} export const populateJWTUser = (Controllers, Actions) => { return async (decodedJwt) => { } } `; exports.JWTuser = plugin_tools_1.CreatePlugin('anything') .configuration({ name: 'JWTuser', injectableParam: 'JWTuser', injectableScope: 'global', depends: ['@pomofficial/Redis', '@restmatic/Actions'], provides: ['@restmatic/RouteSecurity'] }) .directories([{ prop: 'main', path: '.' }]) .variables({ redisPrefix: 'fake', key_ttl: 60 }) .hooks({ load: (Injector, PluginLogger, PluginFiles, PluginVariables, Redis, Actions) => __awaiter(this, void 0, void 0, function* () { PluginLogger.log('Creating SessionSecurity methods', 1); let p = yield PluginFiles('main').workingDirectory; let required = require(p); let mw = fp_1.get('populateJWTUser', required); if (!mw) { throw new Error(`JWTuser file does not contain an export on the populateJWTUser property.`); } if (!fp_1.isFunction(mw)) { throw new Error(`JWTuser file does not export an injectable function on the populateJWTUser property.`); } const populateJWTUser = Injector.inject(mw); const commandArr = PluginVariables.key_ttl > 0 ? ['EX', PluginVariables.key_ttl] : []; console.log(commandArr); return (decodedJwt, next) => { let keyName = `${PluginVariables.redisPrefix}:${decodedJwt.uuid}`; let U = {}; Object.defineProperty(U, 'update', { enumerable: false, writable: true }); Object.defineProperty(U, 'init', { enumerable: false, writable: true }); Object.defineProperty(U, 'expire', { enumerable: false, writable: true }); U.init = function () { const _this = this; if (!decodedJwt || !decodedJwt.uuid) { return next(); } Redis.getAsync(keyName) .then((value) => { if (value === null) { return ['db', populateJWTUser(decodedJwt)]; } return ['redis', JSON.parse(value)]; }) .spread(function (source, user) { if (source === 'db') { let jsonUser = JSON.stringify(user); let redisArgs = [jsonUser, ...commandArr]; return Redis.setAsync(keyName, redisArgs) .then((result) => { return user; }); } return user; }) .then((redisInsert) => { if (redisInsert) { mutableExtend(_this, redisInsert); } next && next(); }) .catch((err) => { PluginLogger.error('Failed to parse redis response correctly.'); PluginLogger.error(err); err.defaultStatusCode = 401; next && next(err); }); }; U.update = () => { }; U.expire = (cb) => { Redis.del(keyName, function (err, status) { cb && cb(err); }); }; U.init(); return U; }; }) }) .commands(function (PomConfig, PluginFiles, Handlebars) { return (yargs) => { return yargs .usage('usage: $0') .command({ command: 'generate', aliases: 'g', describe: `Generates Serializer file`, builder: (yargs) => { return yargs .option('l', { alias: 'language', describe: 'Generate TypeScript or Javascript', default: 'ts', choices: ['ts'], type: 'string' }) .option('force', { alias: 'f', default: false, describe: 'overwrites the specified file if it exists.', type: 'boolean' }); }, handler: (argv) => __awaiter(this, void 0, void 0, function* () { let Pf = PluginFiles('main'); let file = `index.${argv.language}`; let exists = yield Pf.projectFileExists(file); let compile = Handlebars.compile(tsGenerator); let compiled = compile({ creationDate: new Date().toDateString(), name: 'index.ts' }); if (exists && !argv.force) { throw new Error(`${file} \n exists \n Rerun with --force to overwrite.`); } yield Pf.outputProjectFile(file, compiled); console.log(`Created @restmatic/authentication Serializers file ${file}`); }) }) .help(); }; }); //# sourceMappingURL=JWTuser.js.map