api-v1/core/middleware/JwtAuthMiddleware.js

22 lines
695 B
JavaScript

import axios from 'axios';
import BaseMiddleware from './BaseMiddleware.js';
export default class JwtAuthMiddleware extends BaseMiddleware {
constructor(options={}){
super();
this.authServiceUrl=options.authServiceUrl||'http://auth-service:3000/auth/validate-token';
}
middleware(){
return async (req,res,next)=>{
const h=req.headers.authorization;
if(!h) return res.status(401).json({ error:'UNAUTHORIZED' });
try{
const token=h.replace('Bearer ','');
const r=await axios.post(this.authServiceUrl,{ token });
req.user=r.data;
next();
}catch{
res.status(401).json({ error:'INVALID_TOKEN' });
}
};
}
}