jLinux

Untitled

Dec 21st, 2015
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var checkit  = require('checkit');
  2. var Promise  = require('bluebird');
  3. var bcrypt   = Promise.promisifyAll(require('bcrypt'));
  4.  
  5. var Customer = bookshelf.Model.extend({
  6.  
  7.   initialize: function() {
  8.     this.on('saving', this.validateSave);
  9.   },
  10.  
  11.   validateSave: function() {
  12.     return checkit(rules).run(this.attributes);
  13.   },
  14.  
  15.   account: function() {
  16.     return this.belongsTo(Account);
  17.   },
  18.  
  19. }, {
  20.  
  21.   login: Promise.method(function(email, password) {
  22.     if (!email || !password) throw new Error('Email and password are both required');
  23.     return new this({email: email.toLowerCase().trim()}).fetch({require: true}).tap(function(customer) {
  24.       return bcrypt.compareAsync(customer.get('password'), password)
  25.        .then(function(res) {
  26.          if (!res) throw new Error('Invalid password');
  27.        });
  28.     });
  29.   })
  30.  
  31. });
  32.  
  33. Customer.login(email, password)
  34.   .then(function(customer) {
  35.     res.json(customer.omit('password'));
  36.   }).catch(Customer.NotFoundError, function() {
  37.     res.json(400, {error: email + ' not found'});
  38.   }).catch(function(err) {
  39.     console.error(err);
  40.   });
Advertisement
Add Comment
Please, Sign In to add comment