auth.js 1.5 KB

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