22 lines
561 B
TypeScript
22 lines
561 B
TypeScript
|
import {
|
||
|
Injectable,
|
||
|
NestMiddleware,
|
||
|
UnauthorizedException,
|
||
|
} from '@nestjs/common';
|
||
|
import { NextFunction, Request, Response } from 'express';
|
||
|
|
||
|
@Injectable()
|
||
|
export class AuthMiddleware implements NestMiddleware {
|
||
|
use(req: Request, res: Response, next: NextFunction) {
|
||
|
if (!req.session.user) {
|
||
|
if (req.header('content-type')?.includes('application/json')) {
|
||
|
throw new UnauthorizedException('Unauthorized');
|
||
|
}
|
||
|
|
||
|
res.redirect('/login?redirectTo=' + encodeURIComponent(req.originalUrl));
|
||
|
return;
|
||
|
}
|
||
|
next();
|
||
|
}
|
||
|
}
|