From cffddedc8189b2813bf20b23cf87bcccb40b33e0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian=20T=C3=B6lle?= Date: Sat, 2 May 2020 20:04:33 +0200 Subject: [PATCH] fix(api): redirect to frontend on spotify auth error --- src/auth/auth.controller.ts | 10 ++++++---- src/auth/spotify.filter.ts | 28 ++++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 src/auth/spotify.filter.ts diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts index 2cdb30b..aad7c9a 100644 --- a/src/auth/auth.controller.ts +++ b/src/auth/auth.controller.ts @@ -1,10 +1,11 @@ -import { Controller, Get, Res, UseGuards } from "@nestjs/common"; +import { Controller, Get, Res, UseFilters, UseGuards } from "@nestjs/common"; +import { ConfigService } from "@nestjs/config"; import { AuthGuard } from "@nestjs/passport"; import { Response } from "express"; import { User } from "../users/user.entity"; -import { ReqUser } from "./decorators/req-user.decorator"; import { AuthService } from "./auth.service"; -import { ConfigService } from "@nestjs/config"; +import { ReqUser } from "./decorators/req-user.decorator"; +import { SpotifyAuthFilter } from "./spotify.filter"; @Controller("api/v1/auth") export class AuthController { @@ -20,6 +21,7 @@ export class AuthController { } @Get("spotify/callback") + @UseFilters(SpotifyAuthFilter) @UseGuards(AuthGuard("spotify")) async spotifyCallback(@ReqUser() user: User, @Res() res: Response) { const { accessToken } = await this.authService.createToken(user); @@ -35,6 +37,6 @@ export class AuthController { }); // Redirect User to SPA - res.redirect("/"); + res.redirect("/login/success?type=spotify"); } } diff --git a/src/auth/spotify.filter.ts b/src/auth/spotify.filter.ts new file mode 100644 index 0000000..8a0d34b --- /dev/null +++ b/src/auth/spotify.filter.ts @@ -0,0 +1,28 @@ +import { ArgumentsHost, Catch, ExceptionFilter } from "@nestjs/common"; +import { Response } from "express"; +import { Logger } from "../logger/logger.service"; + +@Catch() +export class SpotifyAuthFilter implements ExceptionFilter { + constructor(private readonly logger: Logger) { + this.logger.setContext(this.constructor.name); + } + + catch(exception: Error, host: ArgumentsHost) { + const response = host.switchToHttp().getResponse(); + + let reason = "unknown"; + + if (exception.name === "TokenError") { + // Error during oauth2 flow + reason = "oauth2"; + } + + this.logger.error( + `Login with Spotify failed: ${exception}`, + exception.stack + ); + + response.redirect(`/login/failure?reason=${reason}&type=spotify`); + } +}