2020-05-03 20:18:57 +02:00
|
|
|
import { Injectable, ForbiddenException } from "@nestjs/common";
|
|
|
|
|
import { ConfigService } from "@nestjs/config";
|
|
|
|
|
import { JwtService } from "@nestjs/jwt";
|
2020-02-01 16:11:48 +01:00
|
|
|
import { User } from "../users/user.entity";
|
|
|
|
|
import { UsersService } from "../users/users.service";
|
|
|
|
|
import { LoginDto } from "./dto/login.dto";
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class AuthService {
|
2020-05-03 20:18:57 +02:00
|
|
|
private readonly userFilter: null | string;
|
2020-02-01 16:11:48 +01:00
|
|
|
constructor(
|
2020-05-03 20:18:57 +02:00
|
|
|
private readonly config: ConfigService,
|
2020-02-01 16:11:48 +01:00
|
|
|
private readonly usersService: UsersService,
|
|
|
|
|
private readonly jwtService: JwtService
|
2020-05-03 20:18:57 +02:00
|
|
|
) {
|
|
|
|
|
this.userFilter = this.config.get<string>("SPOTIFY_USER_FILTER");
|
|
|
|
|
}
|
2020-02-01 16:11:48 +01:00
|
|
|
|
|
|
|
|
async spotifyLogin({
|
|
|
|
|
accessToken,
|
|
|
|
|
refreshToken,
|
2020-05-02 17:17:20 +02:00
|
|
|
profile,
|
2020-02-01 16:11:48 +01:00
|
|
|
}: LoginDto): Promise<User> {
|
2020-05-03 20:18:57 +02:00
|
|
|
if (!this.allowedByUserFilter(profile.id)) {
|
|
|
|
|
throw new ForbiddenException("UserNotWhitelisted");
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-01 16:11:48 +01:00
|
|
|
const user = await this.usersService.createOrUpdate({
|
|
|
|
|
displayName: profile.displayName,
|
|
|
|
|
photo: profile.photos.length > 0 ? profile.photos[0] : null,
|
|
|
|
|
spotify: {
|
|
|
|
|
id: profile.id,
|
|
|
|
|
accessToken,
|
2020-05-02 17:17:20 +02:00
|
|
|
refreshToken,
|
|
|
|
|
},
|
2020-02-01 16:11:48 +01:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return user;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async createToken(user: User): Promise<{ accessToken }> {
|
|
|
|
|
const payload = {
|
|
|
|
|
sub: user.id,
|
|
|
|
|
name: user.displayName,
|
2020-05-02 17:17:20 +02:00
|
|
|
picture: user.photo,
|
2020-02-01 16:11:48 +01:00
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const token = await this.jwtService.signAsync(payload);
|
|
|
|
|
|
|
|
|
|
return { accessToken: token };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
async findUser(id: string): Promise<User> {
|
|
|
|
|
return this.usersService.findById(id);
|
|
|
|
|
}
|
2020-05-03 20:18:57 +02:00
|
|
|
|
|
|
|
|
allowedByUserFilter(spotifyID: string) {
|
|
|
|
|
if (!this.userFilter) {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const whitelistedIDs = this.userFilter.split(",");
|
|
|
|
|
|
|
|
|
|
return whitelistedIDs.includes(spotifyID);
|
|
|
|
|
}
|
2020-02-01 16:11:48 +01:00
|
|
|
}
|