fix(api): redirect to frontend on spotify auth error

This commit is contained in:
Julian Tölle 2020-05-02 20:04:33 +02:00
parent b6eef7f090
commit cffddedc81
2 changed files with 34 additions and 4 deletions

View file

@ -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");
}
}

View file

@ -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<Response>();
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`);
}
}