I encounter the problem when I have auth.guard
import { CanActivate, ExecutionContext, ForbiddenException, Injectable } from "@nestjs/common";
import { JwtService } from "@nestjs/jwt";
import { ConfigService } from "@nestjs/config";
@Injectable()
export class AuthGuard implements CanActivate {
constructor(
private jwtService: JwtService,
private configService: ConfigService
) { }
async canActivate(context: ExecutionContext): Promise<boolean> {
const request = context.switchToHttp().getRequest();
try {
const token = request.headers.authorization.split(' ')[1];
if (!token) {
throw new ForbiddenException('Token not found');
}
const payload = await this.jwtService.verifyAsync(token, {
secret: this.configService.get<string>('JWT_SECRET')
// secret: process.env.JWT_SECRET
});
// const user = await this.userService.findByEmail(payload.email);
// if (!user) {
// throw new BadRequestException('User not belong to token');
// }
// request.currentUser = user;
request.currentUser = payload;
} catch (error) {
throw new ForbiddenException('Invalid token or expired');
}
return true;
}
}
but when I use it in module posts. it has a bug which is the following message
Potential solutions:
- Is PostsModule a valid NestJS module?
- If JwtService is a provider, is it part of the current PostsModule?
- If JwtService is exported from a separate @Module, is that module imported within PostsModule?
@Module({
imports: [ /* the Module containing JwtService */ ]
})
I ask copilot and they said that I have to import jwtService into postsModule. Is it right and someone help me