How to authenticate graphql-ws on nestjs?

211 Views Asked by At

I need to apply authentication in graphql subscription. But I get into a problem when I try to implement. I find the documentation and from the documentation -

@Module({
  imports: [
    ConfigModule.forRoot({ isGlobal: true }),
    ScheduleModule.forRoot(),
    GraphQLModule.forRoot<ApolloDriverConfig>({
      driver: ApolloDriver,
      autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
      subscriptions: {
        "graphql-ws": {
          onConnect: async (context: Context<any>) => {
            const { extra }: { extra: any } = context;
            const { request }: { request: Request } = extra;
            const cookies = request.headers.cookie;
            if (cookies) throw new Error("No cookies")

            //Here I need to verify cookies and find the user

          }
        }
      },
      playground: false,
      path: "ecampus",
      plugins: [process.env.NODE_ENV === 'production'
        ? ApolloServerPluginLandingPageProductionDefault({
          footer: false
        })
        : ApolloServerPluginLandingPageLocalDefault({
          footer: false,
          includeCookies: true
        })],
      context: ({ req }) => ({ req })
    }),
    TypeOrmModule.forRoot({
      type: "postgres",
      host: process.env.POSTGRES_HOST,
      port: parseInt(<string>process.env.POSTGRES_PORT),
      username: process.env.POSTGRES_USER,
      password: process.env.POSTGRES_PASSWORD,
      database: process.env.POSTGRES_DATABASE_NAME,
      autoLoadEntities: true,
      synchronize: true
    }),
    .....
  ]
})
export class AppModule { }

Problem is Here I am using typeorm and @nestjs/jwt

I can't use jwtService and userRepository without any constructor. I need to create a service first-

import { Injectable } from "@nestjs/common";
import { InjectRepository } from "@nestjs/typeorm";
import { Repository } from "typeorm";
import { JwtService } from "@nestjs/jwt";

//Entity
import { User } from "src/user/model/user.entity";

@Injectable()
export class AuthService {
    constructor(
        private readonly jwtService: JwtService,
        @InjectRepository(User) private readonly userRepository: Repository<User>,
    ) { }

    async verifyTokenAndFindUser(token: string): Promise<User | null> {
        try {
            const decodedToken = this.jwtService.verify(token);
            const user = await this.userRepository.findOne(decodedToken.userId);
            return user;
        } catch (error) {
            return null;
        }
    }
}

But how can I use jwtService and userRepository into onConnect function in subscription. Please anybody help me.

0

There are 0 best solutions below