Fixed some bugs in api and auth services, completed auth cores.
This commit is contained in:
20
api/src/middlewares/internalware.js
Normal file
20
api/src/middlewares/internalware.js
Normal file
@@ -0,0 +1,20 @@
|
||||
const interalToken = process.env.INTERNAL_API_TOKEN;
|
||||
|
||||
export function internalware(req, res, next) {
|
||||
if (req.headers['x-internal-token'] === interalToken) {
|
||||
req.internal = true; // La richiesta è interna
|
||||
return next();
|
||||
}
|
||||
return res.status(403).json({error: 'not-internal'});
|
||||
}
|
||||
|
||||
export function userOrInternal(userware) {
|
||||
return (req, res, next) => {
|
||||
if (req.headers['x-internal-token'] === interalToken) {
|
||||
req.internal = true;
|
||||
return next();
|
||||
}
|
||||
return userware(req, res, next);
|
||||
};
|
||||
}
|
||||
|
||||
47
api/src/middlewares/userware.js
Normal file
47
api/src/middlewares/userware.js
Normal file
@@ -0,0 +1,47 @@
|
||||
import { redis } from "../data/redis.js";
|
||||
|
||||
const authURL = process.env.AUTH_INTERNAL_URL;
|
||||
const cookieName = process.env.COOKIE_NAME;
|
||||
const cacheTTL = 30;
|
||||
|
||||
function hashCookie(cookie) {
|
||||
return crypto.createHash('sha256').update(cookie).digest('hex').slice(0, 32);
|
||||
}
|
||||
|
||||
export async function userware(req, res, next) {
|
||||
const token = req.cookies?.[cookieName];
|
||||
if (!token) return res.status(401).json({ message: 'not authenticated' })
|
||||
|
||||
const cacheKey = `auth:cookie:${hashCookie(token)}`
|
||||
const cached = await redis.get(cacheKey).catch( ()=> null);
|
||||
if (cached) {
|
||||
req.user = JSON.parse(cached)
|
||||
return next();
|
||||
}
|
||||
|
||||
try {
|
||||
const r = await fetch(`${authURL}/api/users/me`, {
|
||||
headers: {
|
||||
cookie: `${cookieName}=${token}`
|
||||
},
|
||||
});
|
||||
if (!r.ok) throw new Error('unauthorized');
|
||||
const user = await r.json();
|
||||
req.user = {
|
||||
id: body.user.id,
|
||||
sessionId: body.thisSession?.id
|
||||
};
|
||||
await redis.set(cacheKey, JSON.stringify(req.user), 'EX', cacheTTL).catch(() => { });
|
||||
return next();
|
||||
|
||||
} catch (error) {
|
||||
console.error('Userware Middleware: errore in auth:', error.message);
|
||||
return res.status(503).json({ message: 'Error in auth service', error: error})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
//TODO: Da finire
|
||||
|
||||
//TODO: Capire perche le versioni del package manager pnpm sono diverse tra i vari servizi
|
||||
// TODO: Aggiungere 'private' ai package.json per rendere privati i pacchetti
|
||||
Reference in New Issue
Block a user