forked from ZyntariHQ/Invoisio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjwt.strategy.ts
More file actions
59 lines (54 loc) · 1.83 KB
/
Copy pathjwt.strategy.ts
File metadata and controls
59 lines (54 loc) · 1.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import { Injectable, UnauthorizedException } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import { ExtractJwt, Strategy } from "passport-jwt";
import { ConfigService } from "@nestjs/config";
import { PrismaService } from "../../prisma/prisma.service";
import { User } from "../../users/user.entity";
export interface JwtPayload {
sub: string;
publicKey: string;
merchantId?: string;
tokenVersion?: number;
}
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
constructor(
private readonly prisma: PrismaService,
private readonly configService: ConfigService,
) {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: configService.getOrThrow<string>("JWT_SECRET"),
});
}
async validate(payload: JwtPayload): Promise<User> {
const user = await this.prisma.user.findUnique({
where: { id: payload.sub },
});
if (!user) {
throw new UnauthorizedException("User no longer exists.");
}
// Session revocation:
// - tokens include `tokenVersion` in their payload
// - logout increments user's `tokenVersion`
// - any token with a stale version is rejected
const payloadVersion = payload.tokenVersion ?? 0;
const userVersion = (user as any).tokenVersion ?? 0;
if (payloadVersion !== userVersion) {
throw new UnauthorizedException("Token has been revoked.");
}
return {
id: user.id,
merchantId: user.merchantId,
role: (user as any).role ?? "owner",
publicKey: user.publicKey,
createdAt: user.createdAt,
updatedAt: user.updatedAt,
email: user.email,
isAdmin: user.isAdmin,
pushNotificationsEnabled: user.pushNotificationsEnabled,
tokenVersion: (user as any).tokenVersion ?? 0,
} as any;
}
}