Request scoped query filters for multi-tenant applications
See original GitHub issueI will rephrase this to be a feature request with an API proposition, but I couldn’t figure out how to do it from the docs, so I assume that it may be an existing functionality.
I’m working on a multi-tenant application that accomplishes multi-tenancy through a tenant_id
column in every table. This poses some security risks though, with database access/writes, because the tenant_id
must always be correct and manually passed.
I’m wondering if there’s a way to create a request scoped knex instance, that will be used across the code, and will automatically inject the tenant_id
into every sql query ( read or write ) to the database, if the table is marked as multi-tenant one.
Here’s a short example
app.use((req, res) => {
// The `req.tenant` is populated by another middleware, we just
// scope it to the knex instance
req.knex = knex.createScope({
tenant_id: req.tenant.id
})
})
app.get("/user/:id", async (req, res) => {
// Use the knex instance from the request
// `tenant_id` should be auto-appended to the query
const user = await req.knex("users")
.where({ id: req.params.id })
res.send(user)
})
app.post("/user", async (req, res) => {
// Use the knex instance from the request
// `tenant_id` should be auto-appended to the write op
const user = await req.knex("users")
.insert({
username: req.body.username,
email: req.body.email
})
res.send(user)
})
Is this achievable currently through some of the API’s or would it be a feature request?
Issue Analytics
- State:
- Created 2 years ago
- Comments:8 (3 by maintainers)
Top GitHub Comments
As long as there can be scoped context added to a knex instance, its ok if the hooks can be global, because the context will be different for every hook.
I will see how the compilation works exactly and figure out if I can accomplish it with the current API and what edge cases occur and I will keep this issue updated, if anybody else stumbles upon it.
Thank you both for the quick responses and the insights. You have done amazing work with this library and there are a few projects built on top of it already ( at least Objection and MikroOrm ).
Event handlers can be also set in global level in knex so you won’t need to add them to every query separately.