Files
GPI/src/server/middleware/logtoAuth.ts

82 lines
2.0 KiB
TypeScript

import { createRemoteJWKSet, jwtVerify } from 'jose';
import { supabase, findOneGpi } from '../config/supabase.js';
const LOGTO_URL = process.env.LOGTO_URL || 'https://logto-admin-bzlued1boxl3t8ewsyn99an9.187.77.227.172.sslip.io';
const APP_ID = process.env.LOGTO_APP_ID || 'gpi-app-001';
const jwks = createRemoteJWKSet(new URL(`${LOGTO_URL}/oidc/jwks`));
export interface AppUser {
id: string;
logtoId: string;
email: string;
name: string;
role: string;
}
export async function authenticateRequest(req: any): Promise<AppUser | null> {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return null;
}
const token = authHeader.substring(7);
try {
const { payload } = await jwtVerify(token, jwks, {
issuer: `${LOGTO_URL}/oidc`,
audience: APP_ID
});
const logtoId = payload.sub as string;
const user = await findOneGpi('users', { logto_id: logtoId });
if (!user) {
console.log(`[Auth] Usuário Logto ${logtoId} não encontrado no GPI`);
return null;
}
return {
id: user.id,
logtoId: user.logto_id,
email: user.email,
name: user.name,
role: user.role
};
} catch (error) {
console.error('[Auth] Erro ao verificar token:', error);
return null;
}
}
export function requireAuth() {
return async (req: any, res: any, next: any) => {
const user = await authenticateRequest(req);
if (!user) {
return res.status(401).json({ error: 'Unauthorized' });
}
req.appUser = user;
next();
};
}
export function requireRole(roles: string[]) {
return async (req: any, res: any, next: any) => {
const user = await authenticateRequest(req);
if (!user) {
return res.status(401).json({ error: 'Unauthorized' });
}
if (!roles.includes(user.role)) {
return res.status(403).json({ error: 'Forbidden' });
}
req.appUser = user;
next();
};
}