refactor(old app): login migration to new app

This commit is contained in:
2025-10-21 20:22:21 -05:00
parent a2a8e0ef9f
commit eb3fa4dd52
28 changed files with 2273 additions and 2140 deletions

View File

@@ -1,45 +1,62 @@
import {type MiddlewareHandler} from "hono";
import axios from "axios";
import { type MiddlewareHandler } from "hono";
import jwt from "jsonwebtoken";
const {sign, verify} = jwt;
const { sign, verify } = jwt;
export const authMiddleware: MiddlewareHandler = async (c, next) => {
const authHeader = c.req.header("Authorization");
console.log("middleware checked");
const cookieHeader = c.req.header("Cookie");
if (!cookieHeader) return c.json({ error: "Unauthorized" }, 401);
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return c.json({error: "Unauthorized"}, 401);
}
const res = await axios.get(`${process.env.LST_BASE_URL}/api/user/me`, {
headers: { Cookie: cookieHeader },
});
const token = authHeader.split(" ")[1];
if (res.status === 401) return c.json({ error: "Unauthorized" }, 401);
try {
const decoded = verify(token, process.env.JWT_SECRET!, {ignoreExpiration: false}) as {
userId: number;
exp: number;
};
const currentTime = Math.floor(Date.now() / 1000); // Get current timestamp
const timeLeft = decoded.exp - currentTime;
// If the token has less than REFRESH_THRESHOLD seconds left, refresh it
let newToken = null;
if (timeLeft < parseInt(process.env.REFRESH_THRESHOLD!)) {
newToken = sign({userId: decoded.userId}, process.env.JWT_SECRET!, {
expiresIn: parseInt(process.env.EXPIRATION_TIME!),
});
c.res.headers.set("Authorization", `Bearer ${newToken}`);
}
c.set("user", {id: decoded.userId});
await next();
// If a new token was generated, send it in response headers
if (newToken) {
console.log("token was refreshed");
c.res.headers.set("X-Refreshed-Token", newToken);
}
} catch (err) {
return c.json({error: "Invalid token"}, 401);
}
//const user = await resp.json();
c.set("user", res.data.user);
return next();
};
// export const authMiddleware: MiddlewareHandler = async (c, next) => {
// const authHeader = c.req.header("Authorization");
// if (!authHeader || !authHeader.startsWith("Bearer ")) {
// return c.json({error: "Unauthorized"}, 401);
// }
// const token = authHeader.split(" ")[1];
// try {
// const decoded = verify(token, process.env.JWT_SECRET!, {ignoreExpiration: false}) as {
// userId: number;
// exp: number;
// };
// const currentTime = Math.floor(Date.now() / 1000); // Get current timestamp
// const timeLeft = decoded.exp - currentTime;
// // If the token has less than REFRESH_THRESHOLD seconds left, refresh it
// let newToken = null;
// if (timeLeft < parseInt(process.env.REFRESH_THRESHOLD!)) {
// newToken = sign({userId: decoded.userId}, process.env.JWT_SECRET!, {
// expiresIn: parseInt(process.env.EXPIRATION_TIME!),
// });
// c.res.headers.set("Authorization", `Bearer ${newToken}`);
// }
// c.set("user", {id: decoded.userId});
// await next();
// // If a new token was generated, send it in response headers
// if (newToken) {
// console.log("token was refreshed");
// c.res.headers.set("X-Refreshed-Token", newToken);
// }
// } catch (err) {
// return c.json({error: "Invalid token"}, 401);
// }
// };

View File

@@ -1,85 +1,111 @@
import axios from "axios";
import { createMiddleware } from "hono/factory";
import type { CustomJwtPayload } from "../../../types/jwtToken.js";
import { verify } from "hono/jwt";
import { db } from "../../../../database/dbclient.js";
import { modules } from "../../../../database/schema/modules.js";
import { and, eq } from "drizzle-orm";
import { userRoles } from "../../../../database/schema/userRoles.js";
import { tryCatch } from "../../../globalUtils/tryCatch.js";
// const hasCorrectRole = (requiredRole: string[], module: string) =>
// createMiddleware(async (c, next) => {
// /**
// * We want to check to make sure you have the correct role to be here
// */
// const authHeader = c.req.header("Authorization");
// if (!authHeader || !authHeader.startsWith("Bearer ")) {
// return c.json({ error: "Unauthorized" }, 401);
// }
// const token = authHeader.split(" ")[1];
// // deal with token data
// const { data: tokenData, error: tokenError } = await tryCatch(
// verify(token, process.env.JWT_SECRET!),
// );
// if (tokenError) {
// return c.json({ error: "Invalid token" }, 401);
// }
// const customToken = tokenData as CustomJwtPayload;
// // Get the module
// const { data: mod, error: modError } = await tryCatch(
// db.select().from(modules).where(eq(modules.name, module)),
// );
// if (modError) {
// console.log(modError);
// return;
// }
// if (mod.length === 0) {
// return c.json({ error: "You have entered an invalid module name" }, 403);
// }
// // check if the user has the role needed to get into this module
// const { data: userRole, error: userRoleError } = await tryCatch(
// db
// .select()
// .from(userRoles)
// .where(
// and(
// eq(userRoles.module_id, mod[0].module_id),
// eq(userRoles.user_id, customToken.user?.user_id!),
// ),
// ),
// );
// if (userRoleError) {
// return;
// }
// if (!userRole) {
// return c.json(
// {
// error:
// "The module you are trying to access is not active or is invalid.",
// },
// 403,
// );
// }
// if (!requiredRole.includes(userRole[0]?.role)) {
// return c.json(
// { error: "You do not have access to this part of the app." },
// 403,
// );
// }
// await next();
// });
interface UserRole {
userRoleId: string;
userId: string;
module: string;
role: string;
}
const hasCorrectRole = (requiredRole: string[], module: string) =>
createMiddleware(async (c, next) => {
/**
* We want to check to make sure you have the correct role to be here
*/
const authHeader = c.req.header("Authorization");
createMiddleware(async (c, next) => {
const cookieHeader = c.req.header("Cookie");
if (!cookieHeader) return c.json({ error: "Unauthorized" }, 401);
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return c.json({ error: "Unauthorized" }, 401);
}
const res = await axios.get(`${process.env.LST_BASE_URL}/api/user/roles`, {
headers: { Cookie: cookieHeader },
});
const token = authHeader.split(" ")[1];
const currentRoles: UserRole[] = res.data.data;
const canAccess = currentRoles.some(
(r) => r.module === module && requiredRole.includes(r.role),
);
if (!canAccess) {
return c.json(
{
error: "Unauthorized",
message: `You do not have access to ${module}`,
},
400,
);
}
// deal with token data
const { data: tokenData, error: tokenError } = await tryCatch(
verify(token, process.env.JWT_SECRET!)
);
if (tokenError) {
return c.json({ error: "Invalid token" }, 401);
}
const customToken = tokenData as CustomJwtPayload;
// Get the module
const { data: mod, error: modError } = await tryCatch(
db.select().from(modules).where(eq(modules.name, module))
);
if (modError) {
console.log(modError);
return;
}
if (mod.length === 0) {
return c.json({ error: "You have entered an invalid module name" }, 403);
}
// check if the user has the role needed to get into this module
const { data: userRole, error: userRoleError } = await tryCatch(
db
.select()
.from(userRoles)
.where(
and(
eq(userRoles.module_id, mod[0].module_id),
eq(userRoles.user_id, customToken.user?.user_id!)
)
)
);
if (userRoleError) {
return;
}
if (!userRole) {
return c.json(
{
error:
"The module you are trying to access is not active or is invalid.",
},
403
);
}
if (!requiredRole.includes(userRole[0]?.role)) {
return c.json(
{ error: "You do not have access to this part of the app." },
403
);
}
await next();
});
return next();
});
export default hasCorrectRole;