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';
|
2023-03-04 10:13:04 +01:00
|
|
|
import { HEADER_KEY_TIMEZONE } from '@ghostfolio/common/config';
|
2021-04-13 21:53:58 +02:00
|
|
|
import { Injectable, UnauthorizedException } from '@nestjs/common';
|
|
|
|
import { PassportStrategy } from '@nestjs/passport';
|
2023-03-04 10:13:04 +01:00
|
|
|
import * as countriesAndTimezones from 'countries-and-timezones';
|
2021-04-13 21:53:58 +02:00
|
|
|
import { ExtractJwt, Strategy } from 'passport-jwt';
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
|
|
|
|
public constructor(
|
2023-03-04 10:13:04 +01:00
|
|
|
private 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(),
|
2023-03-04 10:13:04 +01:00
|
|
|
passReqToCallback: true,
|
2021-04-18 19:06:54 +02:00
|
|
|
secretOrKey: configurationService.get('JWT_SECRET_KEY')
|
2021-04-13 21:53:58 +02:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2023-03-04 10:13:04 +01:00
|
|
|
public async validate(request: Request, { id }: { id: string }) {
|
2021-04-13 21:53:58 +02:00
|
|
|
try {
|
2023-03-04 10:13:04 +01:00
|
|
|
const timezone = request.headers[HEADER_KEY_TIMEZONE.toLowerCase()];
|
2021-04-13 21:53:58 +02:00
|
|
|
const user = await this.userService.user({ id });
|
|
|
|
|
|
|
|
if (user) {
|
2023-03-04 10:13:04 +01:00
|
|
|
if (this.configurationService.get('ENABLE_FEATURE_SUBSCRIPTION')) {
|
|
|
|
const country =
|
|
|
|
countriesAndTimezones.getCountryForTimezone(timezone)?.id;
|
|
|
|
|
|
|
|
await this.prismaService.analytics.upsert({
|
|
|
|
create: { country, User: { connect: { id: user.id } } },
|
|
|
|
update: {
|
|
|
|
country,
|
|
|
|
activityCount: { increment: 1 },
|
|
|
|
updatedAt: new Date()
|
|
|
|
},
|
|
|
|
where: { userId: user.id }
|
|
|
|
});
|
|
|
|
}
|
2021-04-13 21:53:58 +02:00
|
|
|
|
|
|
|
return user;
|
|
|
|
} else {
|
|
|
|
throw '';
|
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
throw new UnauthorizedException('unauthorized', err.message);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|