Inject provider in decorator function

798 views Asked by At

Basically, I need to pass an authService to the "verifyClient" function inside the @WebSocketGateway decorator, like so :

@WebSocketGateway({
  transports: ['websocket'],
  verifyClient: (info: { req: IncomingMessage }, done: (result: boolean, code: number, msg?: string) => void) => {
    try {
      const keys = authService.verify(//stuff); //how do I inject this service ?
      //more stuff
      done(true, 200);
    } catch (error) {
      done(false, 401, 'invalid token');
      return;
    }
  }
})
export class WsGateway implements OnGatewayConnection, OnGatewayDisconnect {...

I tried doing someting like that :

function verifyClient(info: { req: IncomingMessage }, done: (result: boolean, code: number, msg?: string) => void) {
  try {
    const injectAuthService = Inject(AuthService);
    injectAuthService(this,'authService');
    const auth: AuthService = this.authService; 
    const keys = auth.verify(//stuff) 
    //more stuff
    done(true, 200);
  } catch (error) {
    done(false, 401, 'invalid token');
    return;
  }
}

@WebSocketGateway({
  transports: ['websocket'],
  verifyClient: verifyClient
})
export class WsGateway implements OnGatewayConnection, OnGatewayDisconnect {...

based on this and this but it doesn't work, this.authService is undefined

1

There are 1 answers

0
Ibrahim Ali Fawaz On

I faced a similar issue, but at the end, I just used the jsonwebtoken library,which is what is used under the hood by @nest/jwtService, assuming you want to verify the token as well. I couldn't find any other way to do it.

import * as jwt from 'jsonwebtoken';

import * as queryString from 'query-string';
import { AuthService } from '../authentication/auth.service';

export function verifyClient(info, cb) {
  const [_path, params] = info.req.url?.split('?') as string[];
  const token = queryString.parse(params).token;
  if (!token) {
    cb(false, 401, 'Unauthorized');
  } else {
    try {
      (info.req as any).userId = (jwt.decode(token as string) as any).id;
      cb(true);
    } catch (err) {
      console.log(err);
      cb(false, 401, 'Unauthorized');
    }
  }
}

@WebSocketGateway({
  cors: {
    origin: '*',
    methods: ['GET', 'POST'],
    credentials: true,
  },
  verifyClient,
})
export class UserWebSocketGateway implements OnGatewayInit