#jwt module

1 messages · Page 1 of 1 (latest)

empty iris
#

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

grave axle
#

Good Morning

Can you share your PostsModule?

empty iris
#
import { Module } from '@nestjs/common';
import { PostsController } from './posts.controller';
import { PostsService } from './posts.service';
import { MongooseModule } from '@nestjs/mongoose';
import { Post, PostSchema } from 'src/schemas/Post.schema';

@Module({
  imports: [
    MongooseModule.forFeature([
      {
        name: Post.name,
        schema: PostSchema
      }
    ])
  ],
  controllers: [PostsController],
  providers: [PostsService],
})
export class PostsModule { }

this is my postModule

#

last night my code run normally when I use process.env instead of configService but when I change all to configSevice, I encountered the problem like this about Jwt.

#

I can solve problem by adding jwtModule in postModule but I think it's not needed

nova delta
warm nacelle
#

In which module is your AuthGuard registered? Is it exported in that module? Is the module holding the AuthGuard imported into the Post module?

empty iris
#

I use authGuard in almost module so I add jwtService in app.module and set isGlobal: true. The problem was solved. should I do this?

warm nacelle
#

@empty iris - It is a possibility. What you might want to think about is making the guard global though and only decorating endpoints, which need to circumvent the guard. You can read about that here.

empty iris
#

tks u bro @warm nacelle