2020-09-05 23:35:53 +02:00
|
|
|
import {
|
|
|
|
|
Controller,
|
|
|
|
|
Get,
|
|
|
|
|
Post,
|
|
|
|
|
Res,
|
|
|
|
|
UseFilters,
|
|
|
|
|
UseGuards,
|
|
|
|
|
} from "@nestjs/common";
|
2020-05-02 20:04:33 +02:00
|
|
|
import { ConfigService } from "@nestjs/config";
|
2021-05-25 18:12:42 +02:00
|
|
|
import type { Response } from "express";
|
2020-02-01 16:11:48 +01:00
|
|
|
import { User } from "../users/user.entity";
|
2020-09-05 23:35:53 +02:00
|
|
|
import { AuthSession } from "./auth-session.entity";
|
2020-02-01 16:11:48 +01:00
|
|
|
import { AuthService } from "./auth.service";
|
2020-09-05 23:35:53 +02:00
|
|
|
import { COOKIE_REFRESH_TOKEN } from "./constants";
|
2020-05-02 20:04:33 +02:00
|
|
|
import { ReqUser } from "./decorators/req-user.decorator";
|
2020-09-05 23:35:53 +02:00
|
|
|
import { RefreshAccessTokenResponseDto } from "./dto/refresh-access-token-response.dto";
|
|
|
|
|
import {
|
|
|
|
|
RefreshTokenAuthGuard,
|
|
|
|
|
SpotifyAuthGuard,
|
|
|
|
|
} from "./guards/auth-strategies.guard";
|
2020-05-02 20:04:33 +02:00
|
|
|
import { SpotifyAuthFilter } from "./spotify.filter";
|
2020-02-01 16:11:48 +01:00
|
|
|
|
|
|
|
|
@Controller("api/v1/auth")
|
|
|
|
|
export class AuthController {
|
|
|
|
|
constructor(
|
|
|
|
|
private readonly authService: AuthService,
|
|
|
|
|
private readonly config: ConfigService
|
|
|
|
|
) {}
|
|
|
|
|
|
|
|
|
|
@Get("spotify")
|
2020-09-05 23:35:53 +02:00
|
|
|
@UseGuards(SpotifyAuthGuard)
|
2020-02-01 16:11:48 +01:00
|
|
|
spotifyRedirect() {
|
|
|
|
|
// User is redirected by AuthGuard
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
@Get("spotify/callback")
|
2020-05-02 20:04:33 +02:00
|
|
|
@UseFilters(SpotifyAuthFilter)
|
2020-09-05 23:35:53 +02:00
|
|
|
@UseGuards(SpotifyAuthGuard)
|
2020-02-01 16:11:48 +01:00
|
|
|
async spotifyCallback(@ReqUser() user: User, @Res() res: Response) {
|
2020-09-05 23:35:53 +02:00
|
|
|
const { refreshToken } = await this.authService.createSession(user);
|
2020-02-01 16:11:48 +01:00
|
|
|
|
2020-09-05 23:35:53 +02:00
|
|
|
// Refresh token should not be accessible to frontend to reduce risk
|
|
|
|
|
// of XSS attacks.
|
|
|
|
|
res.cookie(COOKIE_REFRESH_TOKEN, refreshToken, { httpOnly: true });
|
2020-02-01 16:11:48 +01:00
|
|
|
|
|
|
|
|
// Redirect User to SPA
|
2020-05-02 21:46:05 +02:00
|
|
|
res.redirect("/login/success?source=spotify");
|
2020-02-01 16:11:48 +01:00
|
|
|
}
|
2020-09-05 23:35:53 +02:00
|
|
|
|
|
|
|
|
@Post("token/refresh")
|
|
|
|
|
@UseGuards(RefreshTokenAuthGuard)
|
|
|
|
|
async refreshAccessToken(
|
|
|
|
|
// With RefreshTokenAuthGuard the session is available instead of user
|
|
|
|
|
@ReqUser() session: AuthSession
|
|
|
|
|
): Promise<RefreshAccessTokenResponseDto> {
|
|
|
|
|
const { accessToken } = await this.authService.createAccessToken(session);
|
|
|
|
|
|
|
|
|
|
return { accessToken };
|
|
|
|
|
}
|
2020-02-01 16:11:48 +01:00
|
|
|
}
|