简体   繁体   中英

Nestjs - how to get session in middleware

im trying to add graphql to nestjs app. I use postgraphile for the graphql server.

everything works, but i don't know how to protect the '/graphql' endpoint.

the login is done via session, through the nestjs app.

on the needed endpoints (in the existed nestjs app) there is a Session guard which works fine.

i want to add the same behavior to the graphql endpoint.

this is the graphql code:

export const graphqlBootstrap = async (app: INestApplication) => {
  app.use(cors());
  // what i want to achieve 
  app.use('/graphql', (req, res, next) => {
      if (!req.session.user) res.send('Authetication Error`);
      next();
   })

  app.use(
    postgraphile(...)

and the nestjs code the init it:

const bootstrap = async () => {
  const { app, start } = await createApplication(TearupsApplicationModule);
  app.useGlobalInterceptors(new ApiResponseInterceptor());
  configureHiddenFileUploadEndpoint(app.getHttpAdapter());
  await Promise.all(app.get(INITIATION_SEQUENCE).map((fn) => fn()));
  await graphqlBootstrap(app); // <--
  await start();
  app.get(EventsEmitter).init(app);
};

is it possible to use the session in a middleware?

I don't know how to reach the ExecutionContext that exist in the Guard. I read in the docs that there is also ArgumentsHost which might hold the session, but i also don't know how to get it in simple middleware(app.use(...))

Edit 1

i tried to add a middleware to the app module, with forRoutes call.

but the middleware isn't called with the graphql route /graphql .

also, when using route: / - there is no session on the request.

middleware:

export function Logger(req: any, res: Response, next: NextFunction) {
  if (req.session) console.log(`Request...`, req.session.user);
  next();
}

App Module:

export class MyApp implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer.apply(Logger).forRoutes('/');
  }

Edit 2

tried this now, still didn't work:

export class MyApp implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(logger)
      .forRoutes({ path: 'api/tearups/graphql', method: RequestMethod.ALL });
  }
}

Write a functional middleware as follow signature:

import { Request, Response, NextFunction } from 'express';

export function Logger(req: Request, res: Response, next: NextFunction) {
  console.log(`Request...`, req.session.user);
  next();
};

Or, a class-based middleware as:

@Injectable()
export class Logger implements NestMiddleware {
  use(req: Request, res: Response, next: NextFunction) {
    console.log('Request...', req.session.user);
    next();
  }
}

Now apply the middleware as follows:

export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(Logger)
      .forRoutes(CatsController);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM