Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

node.js - How do I use pgcrypto with knex inside a .select statement? (Postgres database)

I'm currently using knex to connect my node.js sever to a postgres database and I have started using pgcrypto to encrypt some of my data. I am a bit late to the game with encrypting my data, so I have several queries I'll need to update, and am looking for the most efficient way to not only swap over my queries, but to actually query the database. When I try to implement the PGP_SYM_DECRYPT directly inside the knex.select() query, I get an error saying the user can't be found. However, if I use the knex.raw() query, I can get it to work. Is there any way to use the PGG_SYM_DECRYPT inside the .select() query, or perhaps a way to pass the secret key alongside of the query so it will automatically decrypt any encrypted columns?

Example WORKING code:

const user = await knex("n_user AS u")
  .where({
    "u.uuid": uuid,
    "su.site_id": site.id
  })
  .first()
  .join("site_has_user AS su", { "su.user_id": "u.id" })
  .select(
    "u.id",
    "u.uuid",
    "u.mobile_number",
    "u.email",
    "u.first_name",
    "u.last_name",
    "u.department",
    // "u.note", the note is the encrypted data
    "u.disabled",
    "su.role"
  )
.select(
  knex.raw(
    `PGP_SYM_DECRYPT(u.note::bytea, '${process.env.SECRET_KEY}') as note`
  )
);

Example DESIRED code (or some other variant):

const user = await knex("n_user AS u")
  .where({
    "u.uuid": uuid,
    "su.site_id": site.id
  })
  .first()
  .join("site_has_user AS su", { "su.user_id": "u.id" })
  .select(
    "u.id",
    "u.uuid",
    "u.mobile_number",
    "u.email",
    "u.first_name",
    "u.last_name",
    "u.department",
    `PGP_SYM_DECRYPT(u.note::bytea, '${process.env.SECRET_KEY}') as note`,
    "u.disabled",
    "su.role"
  );

Any thoughts?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can add raw snippet inside select like this:

  .select(
    "u.id",
    "u.uuid",
    "u.mobile_number",
    "u.email",
    "u.first_name",
    "u.last_name",
    "u.department",
    knex.raw("PGP_SYM_DECRYPT(??::bytea, ?) as note", ['u.note', process.env.SECRET_KEY]),
    "u.disabled",
    "su.role"
  );

In raw syntax ?? is identifier replacement and ? is value binding so that secret key is passed to driver safely as binding without trying to interpolate it directly to SQL string.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...