Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[NestJS][Fastify] Middleware doesn't work when using Fastify in NestJS #582

Closed
DennisSnijder opened this issue Jun 13, 2023 · 12 comments
Closed
Labels
wontfix This will not be worked on

Comments

@DennisSnijder
Copy link
Contributor

Context

Earlier on simplenotezy created the issue mentioning that middlewares are not being triggered when using the Fastify Adapter in combination with the NestJS module.

DennisSnijder/nestjs-bull-board#1

Since the issue was originally opened on the nestjs-bull-board github, I move the issue here since we migrated the package to @bull-board/nestjs.

I will keep this issue updated with updates regarding this issue and with a solution when it becomes available on NestJS's side.

What's the status?

@DennisSnijder
Copy link
Contributor Author

Update: a new version has been publish (10.0.0). However this did not fix the mentioned issue. A new issue has been created on NestJS's Github repo to address this.

nestjs/nest#11802

@coder797
Copy link

coder797 commented Aug 9, 2023

Update: the latest update for nestjs v10.1.3 still doesn't fix this issue :-(

Copy link

stale bot commented Nov 7, 2023

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the wontfix This will not be worked on label Nov 7, 2023
@stale stale bot closed this as completed Nov 15, 2023
@mareksuscak
Copy link

Can we reopen this issue? It has not been resolved yet.

@felixmosh felixmosh reopened this Feb 19, 2024
@stale stale bot removed the wontfix This will not be worked on label Feb 19, 2024
@felixmosh
Copy link
Owner

@DennisSnijder can you check if #704 solves this issue?

@Ttou
Copy link
Contributor

Ttou commented Apr 11, 2024

issue still exist

@nestjs/core 10.3.7
@bull-board/fastify 5.15.3

write a logger for test

iShot_2024-04-11_22 33 01

@Number16BusShelter
Copy link

Number16BusShelter commented Jun 17, 2024

This issue was not resolved and is still present. All other solutions mostly don't work. Current possible workaround is to wrap into a custom controller. Therefore it affects core functionality and probably should get resolved

Node: 18.20.2
Nest: 10.3.5
OS: OSX

Dependencies:
fastify: "4.27.0",
fastify-plugin: "^4.5.1"
bull-board/fastify: "^5.19.2"
bull-board/nestjs: "^5.19.2"

@Yarob50
Copy link

Yarob50 commented Jul 18, 2024

I also had a hard time setting up the Auth middleware for the dashboard in my NestJS app with the Fastify adapter. At least I am glad now that someone mentioned it, and we all look forward to having this fixed soon. Any contribution here will be highly appreciated.

@NatashkinAlex
Copy link

Is there another way to set up authorization when using Fastify? I need to go into production soon and need to restrict access to the admin panel.

@mareksuscak
Copy link

For those of you looking for a workaround, here's roughly what you should do (please pardon any mistakes, you can not just copy-paste the code below but check out the configure method for the steps):

import type { FastifyBasicAuthOptions } from '@fastify/basic-auth';
import basicAuth from '@fastify/basic-auth';
import { ConfigService } from '@nestjs/config';
import { BullModule as NestBullModule } from '@nestjs/bullmq';
import type { DynamicModule, NestModule } from '@nestjs/common';
import { HttpStatus, Module, UnauthorizedException } from '@nestjs/common';
import { BullMQAdapter } from '@bull-board/api/bullMQAdapter';
import { FastifyAdapter } from '@bull-board/fastify';
import { createBullBoard } from '@bull-board/api';
import { HttpAdapterHost } from '@nestjs/core';
import type { FastifyInstance } from 'fastify';

@Module({})
export class JobsModule implements NestModule {
  constructor(
    private readonly adapterHost: HttpAdapterHost,
    @InjectQueue("QUEUE_NAME") private readonly queue: Queue,
  ) {}

  static forRoot(): DynamicModule {
    return {
      module: QueueModule,
      imports: [
        BullModule,
        BullModule.registerQueueAsync({
		  name: "QUEUE_NAME",
		})
      ],
      providers: [],
      exports: [],
    };
  }

  configure() {
    const route = '/bullboard';

    const serverAdapter = new FastifyAdapter();
    serverAdapter.setBasePath(route);

    createBullBoard({
      queues: [
        new BullMQAdapter(this.queue),
      ],
      serverAdapter,
    });

    const app = this.adapterHost.httpAdapter.getInstance<FastifyInstance>();

    // Basic auth
    const authenticate: FastifyBasicAuthOptions['authenticate'] = true;

    const validate: FastifyBasicAuthOptions['validate'] = async (
      username,
      password
    ) => {
      if (username !== "YOUR_USERNAME" || password !== "YOUR_PASSWORD") {
        throw new UnauthorizedException();
      }
    };

    app.register(basicAuth, {
      validate,
      authenticate,
    });

    const bullboardPlugin = serverAdapter.registerPlugin();

    /* Inspired by:
     * https://github.com/felixmosh/bull-board/blob/master/examples/with-fastify-auth/basicAuth.js
     * revisit later as the middleware isn't running correctly due to the following bug:
     * https://github.com/nestjs/nest/issues/11802
     */

    app.register(async (instance) => {
      instance.addHook('onRequest', (req, reply, next) => {
        instance.basicAuth(req, reply, function (error) {
          if (!error) {
            return next();
          }

          const statusCode =
            (error as $TSFixMe).statusCode || HttpStatus.INTERNAL_SERVER_ERROR;
          reply.code(statusCode).send({ error: error.name });
        });
      });

      instance.register(bullboardPlugin, {
        basePath: undefined,
        prefix: route,
      });
    });
  }
}

@Yarob50
Copy link

Yarob50 commented Aug 7, 2024

@mareksuscak
thanks for sharing the above code,
could you please provide an example of how we are supposed to inject this JobsModule into the parent Module?

Copy link

stale bot commented Nov 8, 2024

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

@stale stale bot added the wontfix This will not be worked on label Nov 8, 2024
@stale stale bot closed this as completed Nov 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
wontfix This will not be worked on
Projects
None yet
Development

No branches or pull requests

8 participants