backend/src/auth/strategies/jwt.strategy.ts   A
last analyzed

Complexity

Total Complexity 2
Complexity/F 2

Size

Lines of Code 32
Function Count 1

Duplication

Duplicated Lines 0
Ratio 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
eloc 25
dl 0
loc 32
ccs 13
cts 13
cp 1
rs 10
c 0
b 0
f 0
wmc 2
mnd 1
bc 1
fnc 1
bpm 1
cpm 2
noi 0

1 Function

Rating   Name   Duplication   Size   Complexity  
A JwtStrategy.validate 0 8 2
1 7
import { Injectable, UnauthorizedException } from '@nestjs/common';
2 7
import { PassportStrategy } from '@nestjs/passport';
3 7
import { ExtractJwt, Strategy } from 'passport-jwt';
4 7
import { ConfigService } from '@nestjs/config';
5
import { JwtPayload } from '../types/jwt-payload.interface';
6 7
import { AuthService } from '../auth.service';
7
8
@Injectable()
9 7
export class JwtStrategy extends PassportStrategy(Strategy) {
10
  constructor(
11 5
    private configService: ConfigService,
12 5
    private authService: AuthService,
13
  ) {
14
    // const secret = process.env.JWT_SECRET || 'your-secret-key';
15
    // console.log('JwtStrategy initialized with secret:', secret);
16 5
    super({
17
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
18
      ignoreExpiration: false,
19
      secretOrKey: configService.get<string>('JWT_SECRET'),
20
    });
21
  }
22
23
  async validate(payload: JwtPayload) {
24
    // this is not stateless, as we query the db. This can be refactored to be stateless, the token contains all user data.
25 30
    const user = await this.authService.validateUserById(payload.sub);
26 30
    if (!user) {
27 2
      throw new UnauthorizedException();
28
    }
29 28
    return user;
30
  }
31
}
32