Refactor giai đoạn 1: test các tính năng vừa thay đổi như tour, scene...

This commit is contained in:
2026-06-10 21:58:45 +07:00
parent 3f1b31b233
commit 358a98b21b
31 changed files with 1391 additions and 638 deletions
+29 -26
View File
@@ -2,55 +2,58 @@ const jwt = require('jsonwebtoken');
const User = require('../models/User');
/**
* Strict authentication middleware. Rejects requests without a valid JWT.
* Middleware bảo vệ các route yêu cầu đăng nhập.
* Chặn quyền 'guest' (người dùng chưa đăng nhập).
*/
const protect = async (req, res, next) => {
let token;
if (
(req.headers.authorization && req.headers.authorization.startsWith('Bearer')) ||
req.query.token
) {
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
try {
token = req.headers.authorization
? req.headers.authorization.split(' ')[1]
: req.query.token;
token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id).select('-password');
if (!req.user) {
return res.status(401).json({ message: 'User not found' });
return res.status(401).json({ message: 'Tài khoản không tồn tại' });
}
return next();
} catch (error) {
return res.status(401).json({ message: 'Not authorized, token failed' });
return res.status(401).json({ message: 'Phiên làm việc hết hạn, vui lòng đăng nhập lại' });
}
}
return res.status(401).json({ message: 'Not authorized, no token provided' });
return res.status(401).json({ message: 'Vui lòng đăng nhập để sử dụng tính năng này' });
};
/**
* Optional authentication middleware. Populates req.user if a valid token is present,
* but allows the request to proceed as a guest if no token is found.
* Middleware xác thực tùy chọn.
* Nếu không có token hoặc token không hợp lệ, gán role 'guest' cho req.user.
*/
const optionalAuth = async (req, res, next) => {
if (
(req.headers.authorization && req.headers.authorization.startsWith('Bearer')) ||
req.query.token
) {
let token;
if (req.headers.authorization && req.headers.authorization.startsWith('Bearer')) {
try {
const token = req.headers.authorization
? req.headers.authorization.split(' ')[1]
: req.query.token;
token = req.headers.authorization.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = await User.findById(decoded.id).select('-password');
} catch (error) {
// Ignore error and continue as guest
// Token lỗi, gán guest ở dưới
}
}
// Logic gán Guest Role: Không lưu trong DB, chỉ tồn tại trong vòng đời Request
if (!req.user) {
req.user = {
role: 'guest',
username: 'Guest'
};
}
next();
};
module.exports = {
protect,
optionalAuth
};
module.exports = { protect, optionalAuth };