From ae9f0fae7343cb8eda9523d9c09454103d19a922 Mon Sep 17 00:00:00 2001 From: "Peter.Morton" Date: Wed, 11 Oct 2023 19:17:13 -0500 Subject: [PATCH] Switch from local store to redis --- src/api/middlewares/authKey.js | 20 ++++++++-------- src/api/routes/auth.js | 36 +++++++++++++++-------------- src/api/routes/interactions-flow.js | 18 +++++---------- src/config/index.js | 22 +++++++++--------- src/utils/index.js | 10 ++++++++ src/utils/store.js | 14 +++++++++++ 6 files changed, 71 insertions(+), 49 deletions(-) create mode 100644 src/utils/store.js diff --git a/src/api/middlewares/authKey.js b/src/api/middlewares/authKey.js index d48b3b9..6484123 100644 --- a/src/api/middlewares/authKey.js +++ b/src/api/middlewares/authKey.js @@ -1,14 +1,16 @@ -import localStorage from "local-storage"; +import { store } from "../../utils/index.js"; import createHttpError from "http-errors"; export default (req, res, next) => { - if (localStorage(req.query.authKey) == null) { - next( - new createHttpError.Forbidden( - `middleware:authKey ${req.query.authKey} not authenticated` - ) - ); - return; - } + store.get(req.query.authKey).then((value) => { + if (value == null) { + next( + new createHttpError.Forbidden( + `middleware:authKey ${req.query.authKey} not authenticated` + ) + ); + return; + } + }); next(); }; diff --git a/src/api/routes/auth.js b/src/api/routes/auth.js index a56494c..cbd4a1d 100644 --- a/src/api/routes/auth.js +++ b/src/api/routes/auth.js @@ -1,10 +1,9 @@ import { Router } from "express"; import axios from "axios"; -import { logger } from "../../utils/index.js"; +import { logger, store } from "../../utils/index.js"; import { decode } from "jsonwebtoken"; import jwt from "jsonwebtoken"; import jwkToPem from "jwk-to-pem"; -import localStorage from "local-storage"; const router = Router(); @@ -73,23 +72,26 @@ router.all("/", (req, res, next) => { tenant: issSplit[1], }; + const authDataString = JSON.stringify(authData); + logger.info( - `Adding ${ - verified.sub - } to local-stoage for environment ${JSON.stringify(authData)}` + `Adding agent ${verified.sub} to store for environment ${authDataString}}` ); - localStorage(verified.sub, authData); - - if (sessionIdentifier && sessionIdentifier.length > 0) { - logger.info( - `Adding ${sessionIdentifier} to local-stoage for environment ${JSON.stringify( - authData - )}` - ); - localStorage(sessionIdentifier, authData); - } - - res.send(decoded); + store + .hSet(verified.sub, authData) + .then(() => { + if (sessionIdentifier && sessionIdentifier.length > 0) { + logger.info( + `Adding sessionIdentifier ${sessionIdentifier} to store for environment ${authDataString}` + ); + return store.hSet(sessionIdentifier, authData); + } + }) + .then(() => { + res.send(decoded); + }).catch((e) => { + logger.error(e); // "Uh-oh!" + });; } catch (err) { logger.error(`Verify failed [${JSON.stringify(err, null, 2)}].`); next(err); diff --git a/src/api/routes/interactions-flow.js b/src/api/routes/interactions-flow.js index 1450aee..46604ed 100644 --- a/src/api/routes/interactions-flow.js +++ b/src/api/routes/interactions-flow.js @@ -1,12 +1,10 @@ import { Router } from "express"; import axios from "axios"; -import localStorage from "local-storage"; -import sampleFlow from "../../utils/sampleFlow.js"; const router = Router(); -import { logger } from "../../utils/index.js"; +import { logger, store } from "../../utils/index.js"; import { referenceIdQuery } from "../../utils/graphQueries.js"; -router.get("/", (req, res) => { +router.get("/", async (req, res) => { const data = { nodes: [], links: [], @@ -35,8 +33,8 @@ router.get("/", (req, res) => { // FIX for 'endTime' parameter cannot be later than one minute prior to now. endTime.setMinutes(endTime.getMinutes() - 1); - const { host, tenant, token } = localStorage(req.query.authKey); - + const auth = await store.hGetAll(req.query.authKey); + const { host, tenant, token } = auth; axios .post( `${host}/unified-data-gateway/${tenant}/graphql`, @@ -136,13 +134,9 @@ router.get("/", (req, res) => { logger.debug(`Sending data: ${JSON.stringify(data, null, 2)}`); res.send(data); + }).catch((e) => { + logger.error(e); // "Uh-oh!" }); - - if (req.query.useSampleData) { - const data = sampleFlow(filter); - res.send(data); - return; - } }); function addLink(data, source, target, _fraction) { diff --git a/src/config/index.js b/src/config/index.js index ebc3a6f..863b980 100644 --- a/src/config/index.js +++ b/src/config/index.js @@ -3,24 +3,20 @@ import dotenv from "dotenv"; // Set the NODE_ENV to 'development' by default process.env.NODE_ENV = process.env.NODE_ENV || "development"; -const envFound = dotenv.config(); -if (envFound.error) { - // This error should crash whole process +if (process.env.NODE_ENV !== "production") { + const envFound = dotenv.config({ debug: true }); + if (envFound.error) { + // This error should crash whole process - throw new Error("⚠️ Couldn't find .env file ⚠️"); + throw new Error("⚠️ Couldn't find .env file ⚠️"); + } } export default { /** * Your favorite port */ - port: parseInt(process.env.PORT, 10), - - /** - * Your secret sauce - */ - jwtSecret: process.env.JWT_SECRET, - jwtAlgorithm: process.env.JWT_ALGO, + port: parseInt(process.env.PORT || 3000, 10), /** * Used by winston logger @@ -29,6 +25,10 @@ export default { level: process.env.LOG_LEVEL || "silly", }, + redis: { + url: process.env.REDIS_URL || "redis://localhost:6379", + }, + /** * API configs */ diff --git a/src/utils/index.js b/src/utils/index.js index c925577..fe0fde4 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -1 +1,11 @@ export { default as logger } from "./logger.js"; +export { default as store } from "./store.js"; +export function isEmpty(obj) { + for (const prop in obj) { + if (Object.hasOwn(obj, prop)) { + return false; + } + } + + return true; + } diff --git a/src/utils/store.js b/src/utils/store.js new file mode 100644 index 0000000..1f4555d --- /dev/null +++ b/src/utils/store.js @@ -0,0 +1,14 @@ +import { createClient } from 'redis'; +import config from "../config/index.js"; +import { logger } from "./index.js"; + +const client = createClient({ + url: config.redis.url + }); + +client.on('error', err => logger.error('Redis Client Error', err)); + +await client.connect(); +logger.info(`Connect store to ${config.redis.url}`) + +export default client; \ No newline at end of file