File size: 1,063 Bytes
b0798af
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { Store, secret } from '../../core/store';
@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor(private readonly store: Store) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      ignoreExpiration: false,
      secretOrKey: secret('SESSION_SIGNING_KEY'),
    });
  }
  async validate(payload: { sub: string; sid: string; type: string }) {
    const session = this.store.get('sessions', payload.sid || '');
    const user = this.store.get('users', payload.sub || '');
    if (
      payload.type !== 'access' ||
      !session ||
      !user ||
      session.user_id !== user.id ||
      session.expires < Date.now()
    )
      throw new UnauthorizedException('Session expired');
    return {
      userId: user.id,
      sessionId: session.id,
      email: user.email,
      role: user.account_type,
    };
  }
}