2024-09-13 13:03:35 +00:00
|
|
|
import jwt from "jsonwebtoken";
|
|
|
|
|
import response from "../../response.js";
|
|
|
|
|
import models from "../../models/index.js";
|
|
|
|
|
|
|
|
|
|
export const verifyLoginUser = async (req, res, next) => {
|
|
|
|
|
const authHeader = req.headers.authorization;
|
|
|
|
|
|
|
|
|
|
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
|
|
|
|
return response(401, null, "Please log in to your account first!", res);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const token = authHeader.split(" ")[1];
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
const decoded = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);
|
|
|
|
|
|
2024-09-19 10:04:18 +00:00
|
|
|
const user = await models.User.findByPk(decoded.ID, {
|
2024-09-13 13:03:35 +00:00
|
|
|
attributes: {
|
|
|
|
|
exclude: ["PASSWORD"],
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
return response(404, null, "User not found!", res);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
req.user = user;
|
|
|
|
|
|
|
|
|
|
next();
|
|
|
|
|
} catch (error) {
|
2024-09-23 06:16:02 +00:00
|
|
|
if (error.name === "TokenExpiredError") {
|
|
|
|
|
return response(401, null, "Session expired. Please log in again.", res);
|
|
|
|
|
} else if (error.name === "JsonWebTokenError") {
|
2024-09-13 13:03:35 +00:00
|
|
|
return response(403, null, "Invalid token!", res);
|
|
|
|
|
} else {
|
|
|
|
|
return response(500, null, "An error occurred on the server!", res);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const adminOnly = (req, res, next) => {
|
|
|
|
|
if (!req.user || req.user.ROLE !== "admin") {
|
|
|
|
|
return response(
|
|
|
|
|
403,
|
|
|
|
|
null,
|
|
|
|
|
"Access denied! You do not have admin access.",
|
|
|
|
|
res
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
next();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const teacherOnly = (req, res, next) => {
|
|
|
|
|
if (!req.user || req.user.ROLE !== "teacher") {
|
|
|
|
|
return response(
|
|
|
|
|
403,
|
|
|
|
|
null,
|
|
|
|
|
"Access denied! You do not have teacher access.",
|
|
|
|
|
res
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
next();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const adminOrTeacherOnly = (req, res, next) => {
|
|
|
|
|
if (!req.user || (req.user.ROLE !== "admin" && req.user.ROLE !== "teacher")) {
|
|
|
|
|
return response(
|
|
|
|
|
403,
|
|
|
|
|
null,
|
|
|
|
|
"Access denied! You do not have access for this feature.",
|
|
|
|
|
res
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
next();
|
|
|
|
|
};
|