ghostfolio/apps/api/src/app/auth/jwt.strategy.ts
Thomas 5d1f1b452a
Simplify initial project setup (#12)
* Simplify initial project setup

* Added a validation for environment variables
* Added support for feature flags to simplify the initial project setup

* Add configuration service to test

* Optimize data gathering and exchange rate calculation (#14)

* Clean up changelog
2021-04-18 19:06:54 +02:00

42 lines
1.3 KiB
TypeScript

import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { ConfigurationService } from '../../services/configuration.service';
import { PrismaService } from '../../services/prisma.service';
import { UserService } from '../user/user.service';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
public constructor(
readonly configurationService: ConfigurationService,
private prisma: PrismaService,
private readonly userService: UserService
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: configurationService.get('JWT_SECRET_KEY')
});
}
public async validate({ id }: { id: string }) {
try {
const user = await this.userService.user({ id });
if (user) {
await this.prisma.analytics.upsert({
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);
}
}
}