Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 11th, 2012  |  syntax: None  |  size: 1.72 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. var mongoose = require('mongoose');
  2.  
  3. function Account() {
  4.     this.isValid = false;
  5.     this.fields = {};
  6.  
  7.     var AccountData = new mongoose.Schema({
  8.         createdOn:{type:Date, required:true},
  9.         email:{type:String},
  10.         phone:{type:String},
  11.         firstName:{type:String},
  12.         lastName:{type:String},
  13.     });
  14.     mongoose.model('Account', AccountData);
  15. };
  16.  
  17. Account.prototype.toSessionStore = function() {
  18.     var serialized = {};
  19.     for (var i in this) {
  20.         if (typeof i !== 'function' || typeof i !== 'object') {
  21.             serialized[i] = this[i];
  22.         }
  23.     }
  24.  
  25.     return JSON.stringify(serialized);
  26. };
  27.  
  28. Account.fromSessionStore = function(sessionStore) {
  29.     var sessionObject = JSON.parse(sessionStore);
  30.     var account = new Account();
  31.     for (var i in sessionObject) {
  32.         if (sessionObject.hasOwnProperty(i)) {
  33.             account[i] = sessionObject[i];
  34.         }
  35.     }
  36.  
  37.     return account;
  38. };
  39.  
  40. Account.login = function(email, password, onReady) {
  41.     var account = new Account();
  42.  
  43.     var accountModel = mongoose.model('Account');
  44.     accountModel.findOne({email:email}, function(err, accountData) {
  45.         if (err) {
  46.             console.log('Unable to log in to account because: ' + err.message);
  47.             onReady('Unknown error', null);
  48.         } else {
  49.             if (!accountData) {
  50.                 onReady('Account not found.', null);
  51.             } else {
  52.                 if (Account.hashPassword(password) === accountData.passwordHash) {
  53.                     account.fields = accountData;
  54.                     account.isValid = true;
  55.                     onReady(null, account);
  56.                 } else {
  57.                     onReady('Invalid password.', null);
  58.                 }
  59.             }
  60.         }
  61.     });
  62. };