diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts index ab1bef5..79c10af 100644 --- a/src/auth/auth.service.ts +++ b/src/auth/auth.service.ts @@ -1,21 +1,30 @@ -import { Injectable } from "@nestjs/common"; +import { Injectable, ForbiddenException } from "@nestjs/common"; +import { ConfigService } from "@nestjs/config"; +import { JwtService } from "@nestjs/jwt"; import { User } from "../users/user.entity"; import { UsersService } from "../users/users.service"; import { LoginDto } from "./dto/login.dto"; -import { JwtService } from "@nestjs/jwt"; @Injectable() export class AuthService { + private readonly userFilter: null | string; constructor( + private readonly config: ConfigService, private readonly usersService: UsersService, private readonly jwtService: JwtService - ) {} + ) { + this.userFilter = this.config.get("SPOTIFY_USER_FILTER"); + } async spotifyLogin({ accessToken, refreshToken, profile, }: LoginDto): Promise { + if (!this.allowedByUserFilter(profile.id)) { + throw new ForbiddenException("UserNotWhitelisted"); + } + const user = await this.usersService.createOrUpdate({ displayName: profile.displayName, photo: profile.photos.length > 0 ? profile.photos[0] : null, @@ -44,4 +53,20 @@ export class AuthService { async findUser(id: string): Promise { return this.usersService.findById(id); } + + allowedByUserFilter(spotifyID: string) { + if (!this.userFilter) { + return true; + } + + const whitelistedIDs = this.userFilter.split(","); + + console.log("whitelisted ids", { + whitelistedIDs, + uf: this.userFilter, + spotifyID, + }); + + return whitelistedIDs.includes(spotifyID); + } } diff --git a/src/auth/spotify.filter.ts b/src/auth/spotify.filter.ts index 86a0486..57e8f3e 100644 --- a/src/auth/spotify.filter.ts +++ b/src/auth/spotify.filter.ts @@ -1,4 +1,9 @@ -import { ArgumentsHost, Catch, ExceptionFilter } from "@nestjs/common"; +import { + ArgumentsHost, + Catch, + ExceptionFilter, + ForbiddenException, +} from "@nestjs/common"; import { Response } from "express"; import { Logger } from "../logger/logger.service"; @@ -16,6 +21,12 @@ export class SpotifyAuthFilter implements ExceptionFilter { if (exception.name === "TokenError") { // Error during oauth2 flow reason = "oauth2"; + } else if ( + exception instanceof ForbiddenException && + exception.message === "UserNotWhitelisted" + ) { + // User ID is not in the whitelist + reason = "whitelist"; } this.logger.error( diff --git a/src/config/config.module.ts b/src/config/config.module.ts index 7dcbe6e..e5095fb 100644 --- a/src/config/config.module.ts +++ b/src/config/config.module.ts @@ -27,6 +27,7 @@ import { SPOTIFY_AUTH_API_URL: Joi.string().default( "https://accounts.spotify.com/" ), + SPOTIFY_USER_FILTER: Joi.string(), // DB DB_HOST: Joi.string().required(),