25 lines
632 B
TypeScript
25 lines
632 B
TypeScript
import type { NextFunction, Request, Response } from 'express';
|
|
|
|
import { fromNodeHeaders } from 'better-auth/node';
|
|
|
|
import { auth } from '../auth';
|
|
|
|
export async function requireAuth(req: Request, res: Response, next: NextFunction): Promise<void> {
|
|
try {
|
|
const session = await auth.api.getSession({
|
|
headers: fromNodeHeaders(req.headers),
|
|
});
|
|
|
|
if (!session) {
|
|
res.status(401).json({ message: 'Unauthorized' });
|
|
return;
|
|
}
|
|
|
|
req.auth = session;
|
|
next();
|
|
} catch (error) {
|
|
console.error('Auth session lookup failed', error);
|
|
res.status(401).json({ message: 'Unauthorized' });
|
|
}
|
|
}
|