auth.js 1.8 KB

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