#redirect to controller inside middleware using fastify
6 messages · Page 1 of 1 (latest)
Not really. middie exposes the IncomingMessage and ServerResponse objects, but disables some of the methods like res.write and res.redirect etc. This is all just due to how fastify works
mhh I see. I need to protect some api routes with a middleware that redirects to to the oAuth route on some conditions. Maybe the best aproach is to export this logic into a microservice that uses express
Why not throw an exception, catch it in a filter, and redirect from there?
oh thats a smart and simple solution
could you take a quik look at this ? My filter doesnt get executed and I dont see the mistake I made.
@UseFilters(ShopifyMiddlewareException)
async use(@Req() req: Request, @Res() res: Response, next: () => void) {
return await this.validateAuthenticatedSession(req, res, next);
}
in my validateAuthenticaredSesssion:
next(new UnauthorizedException());
My filter:
@Catch(UnauthorizedException)
@Injectable()
export class ShopifyMiddlewareException implements ExceptionFilter {
async catch(exception: HttpException, host: ArgumentsHost) {
Logger.log("ShopifyMiddlewareException");
const ctx = host.switchToHttp();
const response = ctx.getResponse<Response>();
const status = exception.getStatus();
const shop = response.getHeader("content-security-policy");
Logger.debug(response.getHeaders());
if (TypeHelper.isString(shop)) {
const shopAsString: string = TypeHelper.parseString(shop).split("https://")[1].replace(/\s/g, "");
response.status(301).redirect(`/api/auth/?shop=${shopAsString}`);
}
}
}