2026-03-19 05:42:11 +00:00
|
|
|
import { Request, Response, NextFunction } from 'express';
|
2026-04-02 14:42:35 -05:00
|
|
|
import { auth } from './auth.js';
|
2026-03-19 05:42:11 +00:00
|
|
|
import { fromNodeHeaders } from 'better-auth/node';
|
|
|
|
|
|
|
|
|
|
declare global {
|
|
|
|
|
namespace Express {
|
|
|
|
|
interface Request {
|
|
|
|
|
user?: { id: string; email: string; name: string };
|
|
|
|
|
sessionId?: string;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
export async function requireAuth(req: Request, res: Response, next: NextFunction) {
|
|
|
|
|
try {
|
|
|
|
|
const session = await auth.api.getSession({
|
|
|
|
|
headers: fromNodeHeaders(req.headers),
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!session) {
|
|
|
|
|
return res.status(401).json({ error: 'Unauthorized' });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
req.user = session.user;
|
|
|
|
|
req.sessionId = session.session.id;
|
|
|
|
|
next();
|
|
|
|
|
} catch {
|
|
|
|
|
return res.status(401).json({ error: 'Unauthorized' });
|
|
|
|
|
}
|
|
|
|
|
}
|