Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
♻️ Use custom JWT strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Nov 8, 2020
1 parent e2541a1 commit b32c5af
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 18 deletions.
10 changes: 1 addition & 9 deletions src/modules/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
import {
Body,
Controller,
Get,
Headers,
Ip,
Post,
Query,
} from '@nestjs/common';
import { Body, Controller, Headers, Ip, Post } from '@nestjs/common';
import { users } from '@prisma/client';
import { RateLimit } from 'nestjs-rate-limiter';
import { Expose } from '../../modules/prisma/prisma.interface';
Expand Down
36 changes: 27 additions & 9 deletions src/modules/auth/jwt.strategy.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,38 @@
import { ExtractJwt, Strategy } from 'passport-jwt';
import { PassportStrategy } from '@nestjs/passport';
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { AccessTokenClaims, AccessTokenParsed } from './auth.interface';
import { PassportStrategy } from '@nestjs/passport';
import { Request } from 'express';
import { verify } from 'jsonwebtoken';
import { Strategy } from 'passport-strategy';
import { LOGIN_ACCESS_TOKEN } from '../tokens/tokens.constants';
import { AccessTokenClaims, AccessTokenParsed } from './auth.interface';

class StaartStrategy extends Strategy {
name = 'jwt';
}

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
export class JwtStrategy extends PassportStrategy(StaartStrategy) {
constructor() {
super({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
ignoreExpiration: false,
secretOrKey: process.env.JWT_SECRET,
});
super();
}

authenticate(request: Request) {
const bearerToken = request.headers.authorization;
if (typeof bearerToken !== 'string')
return this.fail('No token found', 401);
const matches = bearerToken.match(/(\S+)\s+(\S+)/);
if (matches) {
const token = matches[2];
if (!token) return this.fail('No token found', 401);
try {
return this.success(verify(token, process.env.JWT_SECRET));
} catch (error) {}
}
return this.fail('Unable to parse token', 401);
}

async validate(payload: AccessTokenClaims): Promise<AccessTokenParsed> {
console.log('got here');
const { sub, id, scopes } = payload;
if (sub !== LOGIN_ACCESS_TOKEN) throw new UnauthorizedException();
return { id, scopes };
Expand Down

0 comments on commit b32c5af

Please sign in to comment.