adonisjs / lucid

AdonisJS SQL ORM. Supports PostgreSQL, MySQL, MSSQL, Redshift, SQLite and many more
https://lucid.adonisjs.com/
MIT License
1.07k stars 191 forks source link

QUESTION: How can I create a "middleware" to intercept queries #936

Closed mariosantosdev closed 1 year ago

mariosantosdev commented 1 year ago

Hello, I have a question. My database the datas are encrypted and I would like encrypt and decrypt "automatically". The Lucid there's a decorator that I can use prepare and consume properties to do it but just works after the query run, when I use something like Users.query().where('email', plainTextMail) (This function use the Knex), the query will search by the plainText mail on database. Actually I encrypt the mail and save on variable and use it on query, like this:

const encryptedMail = Encrypt('user@example.com')
const user = Users.query().where('email', user)

but I would like do it in a decorator for example and just send the plainText. I got the bindings of query but I can't modify and send the modified mail to the query.

RomainLanz commented 1 year ago

Hey @mariosantosdev! 👋🏻

You cannot search on encrypted field, the encryption will give back a different results for the same input, making the result unsearchable.

mariosantosdev commented 1 year ago

Yeah! Before I to search, I encrypt the plain text using the same IV (to generate same encrypted value) and search by the encrypted value. But I would like do it in a decorator or something like it.

arthur-er commented 1 year ago

You can do it using hooks like default user model

mariosantosdev commented 1 year ago

I solved extending the LucidModel interface and creating a method called findByWithEncrypt and your behavior is like the findBy but it's encrypting the value before to search.