ads-marketing/mail-service/src/middleware/auth.js
2025-07-23 17:45:31 +05:00

23 lines
857 B
JavaScript

export default async function authMiddleware(req, res, next) {
const authHeader = req.headers['authorization'];
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'No token provided' });
}
const token = authHeader.split(' ')[1];
try {
// Проверяем токен через auth-service
const resp = await fetch('http://auth-service:3000/api/auth/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` },
body: JSON.stringify({ token }),
});
if (!resp.ok) {
return res.status(401).json({ error: 'Invalid token' });
}
const user = await resp.json();
req.user = user;
next();
} catch (err) {
return res.status(401).json({ error: 'Auth service error', details: err.message });
}
}