Skip to content

Commit

Permalink
Created findOrCreateOauth user function
Browse files Browse the repository at this point in the history
  • Loading branch information
sahat committed Nov 14, 2013
1 parent 7b86a34 commit b6e55c1
Showing 1 changed file with 29 additions and 31 deletions.
60 changes: 29 additions & 31 deletions server/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,62 +43,60 @@ var users = [
];

module.exports = {

addUser: function(username, password, role, callback) {
if (this.findByUsername(username) !== undefined) {
if (this.findByUsername(username)) {
return callback("UserAlreadyExists");
}

// Clean up when 500 users reached
if(users.length > 500) {
users = users.slice(0, 2);
}

var user = new User({
id: _.max(users, function(user) { return user.id; }).id + 1,
username: username,
password: password,
role: role
});
users.push(user);
callback(null, user);

user.save(function(err) {
callback(null, user);
});
},

findOrCreateOauthUser: function(provider, providerId) {
var user = module.exports.findByProviderId(provider, providerId);
if(!user) {
user = {
id: _.max(users, function(user) { return user.id; }).id + 1,
username: provider + '_user', // Should keep Oauth users anonymous on demo site
role: userRoles.user,
provider: provider
};
user[provider] = providerId;
users.push(user);
}

return user;
User.findOne({ $where: provider + '===' + providerId }, function(err, user) {
if (user) {
return user;
} else {
user = {
username: provider + '_user',
role: userRoles.user,
provider: provider
};
user[provider] = providerId;

user.save(function(err) {
return user;
});
}
});
},

findAll: function() {
return _.map(users, function(user) { return _.clone(user); });
User.find(function(err, users) {
return users;
});
},

findById: function(id) {
return _.clone(_.find(users, function(user) { return user.id === id }));
User.findById(id, function(err, user) {
if (user) return user;
});
},

findByUsername: function(username) {
User.findOne({ username: username }, function(err, user) {
if (user) {
return user;
}
if (user) return user;
});
},

findByProviderId: function(provider, id) {
return _.find(users, function(user) { return user[provider] === id; });
},

validate: function(user) {
check(user.username, 'Username must be 1-20 characters long').len(1, 20);
check(user.password, 'Password must be 5-60 characters long').len(5, 60);
Expand Down

0 comments on commit b6e55c1

Please sign in to comment.