Skip to content

Instantly share code, notes, and snippets.

@robwormald
Created December 23, 2013 09:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robwormald/8094352 to your computer and use it in GitHub Desktop.
Save robwormald/8094352 to your computer and use it in GitHub Desktop.
/**
* User
*
* @module :: Model
* @description :: A short summary of how this model works and what it represents.
*
*/
var uuid = require('node-uuid')
var bcrypt = require('bcrypt')
, SALT_WORK_FACTOR = 10
, MIN_PASSWORD_LENGTH = 8;
/**
* [hashPassword description]
* @param {Object} values [description]
* @param {Function} next [description]
* @return {[type]} [description]
*/
function hashPassword(values, next) {
bcrypt.hash(values.password, SALT_WORK_FACTOR, function(err, hash) {
if (err) {
return next(err);
}
values.password = hash;
next();
});
}
module.exports = {
adapter : 'postgresql',
// tableName : 'user',
attributes: {
id : {
type : 'string',
primaryKey : true,
required : true,
},
/* e.g.
nickname: 'string'
*/
identifier : {
type : 'string',
// unique : true
},
username : {
type : 'string'
},
email : {
type : 'string'
},
password : {
type : 'string'
},
provider : {
type : 'string'
},
displayName : {
type : 'string'
},
userType : {
type : 'string'
},
domain : {
model : 'domain',
type : 'string'
},
domainKey : {
type : 'string'
},
credentials : {
collection : 'token'
},
//instance methods
//strip the password out when returning this object!
toJSON: function() {
var obj = this.toObject();
delete obj.password;
delete obj.credentials;
delete obj.email;
delete obj.identifier;
return obj;
},
//compare the asserted password to the hashed password.
validPassword: function(password, callback) {
var obj = this.toObject();
if (callback) {
//callback (err, res)
return bcrypt.compare(password, obj.password, callback);
}
return bcrypt.compareSync(password, obj.password);
}
},
verifyGoogleUser : function(req,accessToken, refreshToken, profile, done) {
User.findOne({identifier : profile.id},function(err,user){
if (err) {
return done(err);
}
if (!user) {
if(profile._json && profile._json.verified_email){
// console.log(profile._json)
User.create({
identifier : profile.id,
username : profile._json.email,
password : uuid.v4(),
email : profile._json.email,
domainKey : profile._json['hd'],
provider : 'google'
})
.done(function(err,_user){
return done(err,_user)
})
}
}
else{
return done(null, user);
}
})
},
// Lifecycle Callbacks
beforeCreate: function(values, next) {
if(!values.id){
values.id = uuid.v4();
}
hashPassword(values, next);
},
beforeUpdate: function(values, next) {
if (values.password) {
hashPassword(values, next);
}
else {
User.findOne(values.id).done(function(err, user) {
if (err) {
next(err);
}
else {
values.password = user.password;
next();
}
});
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment