So I am fairly new to nestJS and I am building an authguard that extends passportstrategy, and if it fails we refresh accesstokens. Fairly straight forward. However the dependency in the auth guard is undefined. And I cant for the life of me figure out where I went wrong.
This is the authguard in question:
@Injectable()
export class JwtAuthGuard extends AuthGuard("jwt") {
constructor(private readonly authService: AbstractAuthService) {
super();
}
async canActivate(context: ExecutionContext): Promise<any> {
const isPublic = Reflect.getMetadata(IS_PUBLIC_KEY, context.getHandler());
const isBypassJwt = Reflect.getMetadata(
BYPASS_JWT_AUTH_KEY,
context.getHandler(),
);
if (isPublic || isBypassJwt) {
return true;
}
try {
console.log("CanActivate");
return await super.canActivate(context);
} catch (error) {
if (error instanceof UnauthorizedException) {
return await this.handleRefreshToken(context);
}
throw error;
}
}
private async handleRefreshToken(
context: ExecutionContext,
): Promise<boolean> {
const request: Request = context.switchToHttp().getRequest();
const response: Response = context.switchToHttp().getResponse();
if (!request.cookies || !request.cookies[CookieNames.REFRESH_JWT]) {
throw new UnauthorizedException(AuthErrors.COOKIES_NOT_SET);
}
const currentRefreshToken: string = cookieExtractor(
request,
CookieNames.REFRESH_JWT,
);
try {
console.log("Dependency: " + this.authService) // undefined;
const { accessToken, refreshToken } =
await this.authService.refreshAccessToken(currentRefreshToken);
setCookie(response, CookieNames.ACCESS_JWT, accessToken);
setCookie(response, CookieNames.REFRESH_JWT, refreshToken);
return true;
} catch (error) {
console.log("ERRRRROR: " + error);
// clearTokenCookies(response);
throw new UnauthorizedException("Invalid credentials");
}
}
}
And this is the authmodule:
@Module({
imports: [
PassportModule,
AzureModule,
TokenModule,
JwtModule.register({}),
],
providers: [
JwtStrategy,
AuthService,
{
provide: AbstractAuthService,
useClass: AuthService,
},
{
provide: APP_GUARD,
useClass: JwtAuthGuard,
},
],
controllers: [AuthController],
exports: [],
})
export class AuthModule {}
I confirm that the guard is hit on every request but the service is undefined. This module is registered in AppModule as well. I thought maybe I need to use useFactory to resolve the dependency, but then the guard wasnt hit at all on requests.
I am unsure of where to go from here, I feel like I might be missing something obvious so any help at all would be greatly appreciated. And any reading materials as well to further my understanding.
Also worth mentioning, I've read that these issues can happen when there are circular dependencies in the application, but I can't find any.