Created
August 17, 2011 22:55
-
-
Save marccampbell/1152853 to your computer and use it in GitHub Desktop.
Account.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
function Account() { | |
this.isValid = false; | |
this.fields = {}; | |
var AccountData = new mongoose.Schema({ | |
createdOn:{type:Date, required:true}, | |
email:{type:String}, | |
phone:{type:String}, | |
firstName:{type:String}, | |
lastName:{type:String}, | |
}); | |
mongoose.model('Account', AccountData); | |
}; | |
Account.prototype.toSessionStore = function() { | |
var serialized = {}; | |
for (var i in this) { | |
if (typeof i !== 'function' || typeof i !== 'object') { | |
serialized[i] = this[i]; | |
} | |
} | |
return JSON.stringify(serialized); | |
}; | |
Account.fromSessionStore = function(sessionStore) { | |
var sessionObject = JSON.parse(sessionStore); | |
var account = new Account(); | |
for (var i in sessionObject) { | |
if (sessionObject.hasOwnProperty(i)) { | |
account[i] = sessionObject[i]; | |
} | |
} | |
return account; | |
}; | |
Account.login = function(email, password, onReady) { | |
var account = new Account(); | |
var accountModel = mongoose.model('Account'); | |
accountModel.findOne({email:email}, function(err, accountData) { | |
if (err) { | |
console.log('Unable to log in to account because: ' + err.message); | |
onReady('Unknown error', null); | |
} else { | |
if (!accountData) { | |
onReady('Account not found.', null); | |
} else { | |
if (Account.hashPassword(password) === accountData.passwordHash) { | |
account.fields = accountData; | |
account.isValid = true; | |
onReady(null, account); | |
} else { | |
onReady('Invalid password.', null); | |
} | |
} | |
} | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment