2021-08-14 16:55:40 +02:00
|
|
|
import { UserService } from '@ghostfolio/api/app/user/user.service';
|
2021-04-21 20:27:39 +02:00
|
|
|
import { ConfigurationService } from '@ghostfolio/api/services/configuration.service';
|
|
|
|
import { PrismaService } from '@ghostfolio/api/services/prisma.service';
|
2021-04-13 21:53:58 +02:00
|
|
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
|
|
import { PassportStrategy } from '@nestjs/passport';
|
|
|
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
|
|
|
public constructor(
|
2021-04-18 19:06:54 +02:00
|
|
|
readonly configurationService: ConfigurationService,
|
2021-08-07 22:38:07 +02:00
|
|
|
private readonly prismaService: PrismaService,
|
2021-04-13 21:53:58 +02:00
|
|
|
private readonly userService: UserService
|
|
|
|
) {
|
|
|
|
super({
|
|
|
|
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
2021-04-18 19:06:54 +02:00
|
|
|
secretOrKey: configurationService.get('JWT_SECRET_KEY')
|
2021-04-13 21:53:58 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
public async validate({ id }: { id: string }) {
|
|
|
|
try {
|
|
|
|
const user = await this.userService.user({ id });
|
|
|
|
|
|
|
|
if (user) {
|
2021-08-07 22:38:07 +02:00
|
|
|
await this.prismaService.analytics.upsert({
|
2021-04-13 21:53:58 +02:00
|
|
|
create: { User: { connect: { id: user.id } } },
|
|
|
|
update: { activityCount: { increment: 1 }, updatedAt: new Date() },
|
|
|
|
where: { userId: user.id }
|
|
|
|
});
|
|
|
|
|
|
|
|
return user;
|
|
|
|
} else {
|
|
|
|
throw '';
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
throw new UnauthorizedException('unauthorized', err.message);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|