auth.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. // Objection Docs:
  2. // http://vincit.github.io/objection.js/
  3. import bcrypt from "bcrypt";
  4. import { Model } from "objection";
  5. import db from "../db.js";
  6. import { convertBoolFieldsToInt, convertIntFieldsToBool } from "../lib/helpers.js";
  7. import now from "./now_helper.js";
  8. import User from "./user.js";
  9. Model.knex(db);
  10. const boolFields = ["is_deleted"];
  11. function encryptPassword() {
  12. if (this.type === "password" && this.secret) {
  13. return bcrypt.hash(this.secret, 13).then((hash) => {
  14. this.secret = hash;
  15. });
  16. }
  17. return null;
  18. }
  19. class Auth extends Model {
  20. $beforeInsert(queryContext) {
  21. this.created_on = now();
  22. this.modified_on = now();
  23. // Default for meta
  24. if (typeof this.meta === "undefined") {
  25. this.meta = {};
  26. }
  27. return encryptPassword.apply(this, queryContext);
  28. }
  29. $beforeUpdate(queryContext) {
  30. this.modified_on = now();
  31. return encryptPassword.apply(this, queryContext);
  32. }
  33. $parseDatabaseJson(json) {
  34. const thisJson = super.$parseDatabaseJson(json);
  35. return convertIntFieldsToBool(thisJson, boolFields);
  36. }
  37. $formatDatabaseJson(json) {
  38. const thisJson = convertBoolFieldsToInt(json, boolFields);
  39. return super.$formatDatabaseJson(thisJson);
  40. }
  41. /**
  42. * Verify a plain password against the encrypted password
  43. *
  44. * @param {String} password
  45. * @returns {Promise}
  46. */
  47. verifyPassword(password) {
  48. return bcrypt.compare(password, this.secret);
  49. }
  50. static get name() {
  51. return "Auth";
  52. }
  53. static get tableName() {
  54. return "auth";
  55. }
  56. static get jsonAttributes() {
  57. return ["meta"];
  58. }
  59. static get relationMappings() {
  60. return {
  61. user: {
  62. relation: Model.HasOneRelation,
  63. modelClass: User,
  64. join: {
  65. from: "auth.user_id",
  66. to: "user.id",
  67. },
  68. filter: {
  69. is_deleted: 0,
  70. },
  71. },
  72. };
  73. }
  74. }
  75. export default Auth;