Files
Dwinzo-Backend-V0.0/src/shared/utils/token.ts

141 lines
3.4 KiB
TypeScript

import { Request, Response, NextFunction } from "express";
import Jwt from "jsonwebtoken";
import dotenv from "dotenv";
import { extractOrg } from "../services/auth/authServices.ts";
import AuthModel from "../V1Models/Auth/userAuthModel.ts";
dotenv.config();
export interface AuthenticatedRequest extends Request {
user?: {
Email: string;
role: string;
userId: string;
organization: string;
};
}
const jwt_secret = process.env.JWT_SECRET as string;
const refresh_jwt_secret = process.env.REFRESH_JWT_SECRET as string;
const tokenGenerator = (
Email: string,
role: string,
userId: string,
organization: string
) => {
const token = Jwt.sign(
{ Email: Email, role: role, userId: userId, organization: organization },
jwt_secret,
{
expiresIn: "3h",
}
);
return token;
};
const tokenRefreshGenerator = (
Email: string,
role: string,
userId: string,
organization: string
) => {
const token = Jwt.sign(
{ Email: Email, role: role, userId: userId, organization: organization },
refresh_jwt_secret,
{
expiresIn: "7d",
}
);
return token;
};
const tokenValidator = async (
req: AuthenticatedRequest,
res: Response,
next: NextFunction
): Promise<void> => {
const token: string | undefined = req.headers.token as string | undefined;
const refresh_token = req.headers["refresh_token"] as string | undefined;
if (!token) {
res.status(403).json({
msg: "No token present",
});
return;
}
try {
const decoded = Jwt.verify(token, jwt_secret) as {
Email: string;
role: string;
userId: string;
organization: string;
};
if (!decoded) {
res.status(403).json({
success: false,
status: 403,
message: "Invalid Token",
});
return;
}
req.user = decoded;
next();
} catch (err) {
if (!refresh_token) {
res.status(403).json({
success: false,
status: 403,
message: "No refresh token present",
});
return;
}
try {
const decodedRefresh = Jwt.verify(refresh_token, refresh_jwt_secret) as {
Email: string;
role: string;
userId: string;
organization: string;
};
if (!decodedRefresh) {
res.status(403).json({
success: false,
status: 403,
message: "Invalid Token",
});
return;
}
const newAccessToken = tokenGenerator(
decodedRefresh.Email,
decodedRefresh.role,
decodedRefresh.userId,
decodedRefresh.organization
);
res.setHeader("x-access-token", newAccessToken);
req.user = decodedRefresh;
return next();
} catch (err) {
const decodedAny = Jwt.decode(token || refresh_token) as {
Email?: string;
role: string;
userId: string;
organization: string;
};
if (decodedAny?.Email) {
const organization = extractOrg(decodedAny?.Email);
const user = await AuthModel(organization).findOne({
Email: decodedAny.Email,
isArchieve: false,
});
if (user) {
user.visitorBrowserID = "";
await user.save();
}
}
res.status(403).json({
success: false,
status: 403,
message: "Invalid Token",
});
return;
}
}
};
export { tokenValidator, tokenGenerator, tokenRefreshGenerator };