add verifyAccess
This commit is contained in:
42
middleware/verifyAcces.js
Normal file
42
middleware/verifyAcces.js
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
const { ErrorHandler } = require("../helpers/error");
|
||||||
|
const { getUserByIdDb } = require("../db/user.db");
|
||||||
|
|
||||||
|
const verifyAccess = (minLevel = 1, allowUnapprovedReadOnly = false) => {
|
||||||
|
return async (req, res, next) => {
|
||||||
|
try {
|
||||||
|
const user = req.user;
|
||||||
|
|
||||||
|
if (!user) throw new ErrorHandler(401, "Unauthorized: User not found");
|
||||||
|
|
||||||
|
// Super Admin bypass semua
|
||||||
|
if (user.is_sa) return next();
|
||||||
|
|
||||||
|
// Ambil user lengkap dari DB
|
||||||
|
const fullUser = await getUserByIdDb(user.user_id);
|
||||||
|
if (!fullUser) throw new ErrorHandler(403, "Forbidden: User not found");
|
||||||
|
|
||||||
|
// Jika belum di-approve
|
||||||
|
if (!fullUser.is_approve) {
|
||||||
|
// Hanya boleh GET (read-only)
|
||||||
|
if (req.method !== "GET") {
|
||||||
|
throw new ErrorHandler(403, "Account not approved — read-only access");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allowUnapprovedReadOnly) return next();
|
||||||
|
|
||||||
|
throw new ErrorHandler(403, "Account not approved");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cek role level
|
||||||
|
if (!fullUser.role_level || fullUser.role_level < minLevel) {
|
||||||
|
throw new ErrorHandler(403, "Forbidden: Insufficient role level");
|
||||||
|
}
|
||||||
|
|
||||||
|
next();
|
||||||
|
} catch (err) {
|
||||||
|
next(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
module.exports = verifyAccess;
|
||||||
Reference in New Issue
Block a user