Listory/src/auth/auth.service.ts

67 lines
1.7 KiB
TypeScript
Raw Normal View History

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 {
private readonly userFilter: null | string;
2020-02-01 16:11:48 +01:00
constructor(
private readonly config: ConfigService,
2020-02-01 16:11:48 +01:00
private readonly usersService: UsersService,
private readonly jwtService: JwtService
) {
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> {
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);
}
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
}