23 lines
857 B
JavaScript
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 });
|
|
}
|
|
}
|