needle-innovision / nestjs-tenancy

Multi-tenancy approach for nestjs - currently supported only for mongodb with mongoose
MIT License
187 stars 58 forks source link

Question: for controllers/services that don't need tenant. How to bypass the tenant validation #27

Open raphaelarias opened 2 years ago

raphaelarias commented 2 years ago

For some controllers, (e.g. /v1/tenants/create) we don't have the tenant id yet, because in this case, for example, they are actually creating a new tenant.

We were trying not to set the X-TENANT-ID as null or something just for the sake of it. Is there a way to for certain controllers to bypass the validator? We studied rolling out our own validation, but if/before we do that, I thought it would be better to ask. :)

sandeepsuvit commented 2 years ago

@raphaelarias interesting question. In the current implementation the tenant context is resolved from the request scope. So this means all requests to the controllers under tenant module implementation should comply to pass this information for this to work. According to your requirement how would you want to get this working? Any suggestions?

raphaelarias commented 2 years ago

That's an interesting question, for which I don't have the answer yet. Maybe a decorator for specific controllers?

sandeepsuvit commented 2 years ago

@raphaelarias would you like to give it a try via a PR.

AdamJessop commented 2 years ago

I have just been looking at this, and would need substantial refactoring, the problem is that all of the checks for the tenant key is done in the module instantiation, which is executed before any of the guards.

One solution would be to have a tenancy middleware which could get applied to routes at an inheriting module level, but even that feels clunky when working with Nest and how nice using decorators are.

The best way forward would be to set the tenantId the request, and if the tenantId isn't set it should skip the validator and degrade gracefully. Then an AuthGuard could be written at a controller level to check for the presence of tenantId and if needed, throw an error.

AdamJessop commented 2 years ago

That PR above will get the ball rolling I guess.

samuelpares commented 2 years ago

Perhaps in this case, the module associated with your route /v1/tenants/create should not import TenancyModule or any other module that imports it. Then you can just create a new mongoose connection, do stuffs you need and close it, or even use the default MongooseModule to connect to a predefined database and inject models in your services. I speak from experience, since I'm doing the same thing you are trying to. With this PR, what would happen with a skipped route that has some service that injects a model using InjectTenancyModel?