auth.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. Model.knex(db);
  8. function encryptPassword () {
  9. /* jshint -W040 */
  10. let _this = this;
  11. if (_this.type === 'password' && _this.secret) {
  12. return bcrypt.hash(_this.secret, 13)
  13. .then(function (hash) {
  14. _this.secret = hash;
  15. });
  16. }
  17. return null;
  18. }
  19. class Auth extends Model {
  20. $beforeInsert (queryContext) {
  21. this.created_on = Model.raw('NOW()');
  22. this.modified_on = Model.raw('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 = Model.raw('NOW()');
  31. return encryptPassword.apply(this, queryContext);
  32. }
  33. /**
  34. * Verify a plain password against the encrypted password
  35. *
  36. * @param {String} password
  37. * @returns {Promise}
  38. */
  39. verifyPassword (password) {
  40. return bcrypt.compare(password, this.secret);
  41. }
  42. static get name () {
  43. return 'Auth';
  44. }
  45. static get tableName () {
  46. return 'auth';
  47. }
  48. static get jsonAttributes () {
  49. return ['meta'];
  50. }
  51. static get relationMappings () {
  52. return {
  53. user: {
  54. relation: Model.HasOneRelation,
  55. modelClass: User,
  56. join: {
  57. from: 'auth.user_id',
  58. to: 'user.id'
  59. },
  60. filter: {
  61. is_deleted: 0
  62. },
  63. modify: function (qb) {
  64. qb.omit(['is_deleted']);
  65. }
  66. }
  67. };
  68. }
  69. }
  70. module.exports = Auth;