Skip to content

Commit

Permalink
fix(deploy-web): refactor user pages + bring back to pages router fro…
Browse files Browse the repository at this point in the history
…m app router (#169)
  • Loading branch information
baktun14 committed Apr 25, 2024
1 parent 8bbd191 commit fc11dce
Show file tree
Hide file tree
Showing 194 changed files with 2,981 additions and 4,170 deletions.
10 changes: 5 additions & 5 deletions api/src/caching/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,19 @@ export const Memoize = (options?: MemoizeOptions) => (target: object, propertyNa
export async function cacheResponse<T>(seconds: number, key: string, refreshRequest: () => Promise<T>, keepData?: boolean): Promise<T> {
const duration = seconds * 1000;
const cachedObject = cacheEngine.getFromCache(key) as CachedObject<T> | undefined;
console.log(`Cache key: ${key}`);
// console.log(`Cache key: ${key}`);

// If first time or expired, must refresh data if not already refreshing
const cacheExpired = Math.abs(differenceInSeconds(cachedObject?.date, new Date())) > seconds;
if ((!cachedObject || cacheExpired) && !(key in pendingRequests)) {
console.log(`Making request: ${key}`);
// console.log(`Making request: ${key}`);
pendingRequests[key] = refreshRequest()
.then((data) => {
cacheEngine.storeInCache(key, { date: new Date(), data: data }, keepData ? undefined : duration);
return data;
})
.catch((err) => {
console.log(`Error making cache request ${err}`);
// console.log(`Error making cache request ${err}`);
Sentry.captureException(err);
})
.finally(() => {
Expand All @@ -51,10 +51,10 @@ export async function cacheResponse<T>(seconds: number, key: string, refreshRequ

// If there is data in cache, return it even if it is expired. Otherwise, wait for the refresh request to finish
if (cachedObject) {
console.log(`Cache hit: ${key}`);
// console.log(`Cache hit: ${key}`);
return cachedObject.data;
} else {
console.log(`Waiting for pending request: ${key}`);
// console.log(`Waiting for pending request: ${key}`);
return (await pendingRequests[key]) as T;
}
}
Expand Down
3 changes: 1 addition & 2 deletions api/src/middlewares/userMiddleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ export const kvStore = {

export const requiredUserMiddleware = verifyRsaJwt({
jwksUri: env.Auth0JWKSUri,
kvStore: kvStore,
verbose: true
kvStore: kvStore
});

export const optionalUserMiddleware = verifyRsaJwt({
Expand Down
1 change: 0 additions & 1 deletion api/src/routers/userRouter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ userOptionalRouter.get("/template/:id", async (c) => {

if (!uuid.validate(templateId)) {
return c.text("Invalid template id", 400);
return;
}

const template = await getTemplateById(templateId, userId);
Expand Down
2 changes: 1 addition & 1 deletion api/src/services/db/templateService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ export async function saveTemplate(
) {
let template = await Template.findOne({
where: {
id: id,
id: id || null,
userId: userId
}
});
Expand Down
26 changes: 12 additions & 14 deletions api/src/verify-rsa-jwt-cloudflare-worker-main/hono-middleware.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Context, MiddlewareHandler } from 'hono';
import type { GeneralKeyValueStore, VerificationResult } from '.';
import { getJwks, useKVStore, verify } from '.';
import type { Context, MiddlewareHandler } from "hono";
import type { GeneralKeyValueStore, VerificationResult } from ".";
import { getJwks, useKVStore, verify } from ".";

export type VerifyRsaJwtConfig = {
jwksUri?: string;
Expand All @@ -10,25 +10,24 @@ export type VerifyRsaJwtConfig = {
optional?: boolean;
};

const PAYLOAD_KEY = 'verifyRsaJwtPayload';
const PAYLOAD_KEY = "verifyRsaJwtPayload";

export function verifyRsaJwt(config?: VerifyRsaJwtConfig): MiddlewareHandler {
return async (ctx: Context, next) => {
const jwtToken = ctx.req.headers
.get('Authorization')
?.replace(/Bearer\s+/i, '');
if (!jwtToken || jwtToken.length === 0) {
return new Response('Bad Request', { status: 400 });
}
try {
const jwtToken = ctx.req.headers.get("Authorization")?.replace(/Bearer\s+/i, "");
if (!jwtToken || jwtToken.length === 0) {
throw new Error("JWT token not found in Authorization header");
}

const jwks = await getJwks(
config?.jwksUri || ctx.env.JWKS_URI,
useKVStore(config?.kvStore || ctx.env?.VERIFY_RSA_JWT),
ctx.env?.VERIFY_RSA_JWT_JWKS_CACHE_KEY,
ctx.env?.VERIFY_RSA_JWT_JWKS_CACHE_KEY
);
const result = await verify(jwtToken, jwks);
if (result.payload === null) {
throw new Error('Invalid token');
throw new Error("Invalid token");
}

// Custom validator that should throw an error if the payload is invalid.
Expand All @@ -38,8 +37,7 @@ export function verifyRsaJwt(config?: VerifyRsaJwtConfig): MiddlewareHandler {
ctx.set(PAYLOAD_KEY, result.payload);
await next();
} catch (error) {
config?.verbose &&
console.error({ message: 'verification failed', error });
config?.verbose && console.error({ message: "verification failed", error });

if (config?.optional) {
await next();
Expand Down
13 changes: 7 additions & 6 deletions api/webpack.dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,14 @@ module.exports = {
entry: "./src/index.ts",
mode: NODE_ENV,
target: "node",
devtool: "source-map",
output: {
path: path.resolve(__dirname, "dist"),
filename: "server.js",
filename: "server.js"
},
resolve: {
extensions: [".ts", ".js"],
alias: hq.get("webpack"),
alias: hq.get("webpack")
},
externals: [nodeExternals()],
module: {
Expand All @@ -23,9 +24,9 @@ module.exports = {
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
loader: "ts-loader",
options: { configFile: "tsconfig.build.json"}
},
],
options: { configFile: "tsconfig.build.json" }
}
]
},
plugins: [new NodemonPlugin()],
plugins: [new NodemonPlugin()]
};
13 changes: 6 additions & 7 deletions api/webpack.prod.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const path = require("path");
const { NODE_ENV = "production" } = process.env;
const NodemonPlugin = require("nodemon-webpack-plugin");
const nodeExternals = require("webpack-node-externals");
const hq = require("alias-hq");

Expand All @@ -10,11 +9,11 @@ module.exports = {
target: "node",
output: {
path: path.resolve(__dirname, "dist"),
filename: "server.js",
filename: "server.js"
},
resolve: {
extensions: [".ts", ".js"],
alias: hq.get("webpack"),
alias: hq.get("webpack")
},
externals: [nodeExternals()],
module: {
Expand All @@ -23,9 +22,9 @@ module.exports = {
test: /\.(ts|js)x?$/,
exclude: /node_modules/,
loader: "ts-loader",
options: { configFile: "tsconfig.build.json"}
},
],
options: { configFile: "tsconfig.build.json" }
}
]
},
plugins: [new NodemonPlugin()],
plugins: []
};
1 change: 0 additions & 1 deletion deploy-web/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference types="next/navigation-types/compat/navigation" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
1 change: 1 addition & 0 deletions deploy-web/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ const moduleExports = {
typescript: {
tsconfigPath: "./tsconfig.json"
},
transpilePackages: ["geist"],
// experimental: {
// // outputStandalone: true,
// externalDir: true // to make the import from shared parent folder work https://github.com/vercel/next.js/issues/9474#issuecomment-810212174
Expand Down
Loading

0 comments on commit fc11dce

Please sign in to comment.