Skip to content

Commit

Permalink
Merge pull request techx#51 from patins/unique-emails
Browse files Browse the repository at this point in the history
Force emails to be unique with mongo
  • Loading branch information
jlin816 authored Jan 22, 2018
2 parents 9bf8f65 + 908f5b4 commit 3be9dd5
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 37 deletions.
62 changes: 25 additions & 37 deletions app/server/controllers/UserController.js
Original file line number Diff line number Diff line change
Expand Up @@ -150,48 +150,36 @@ UserController.createUser = function(email, password, callback) {
return callback(err);
}

User
.findOneByEmail(email)
.exec(function(err, user){

if (err) {
return callback(err);
}

if (user) {
var u = new User();
u.email = email;
u.password = User.generateHash(password);
u.save(function(err){
if (err){
// Duplicate key error codes
if (err.name === 'MongoError' && (err.code === 11000 || err.code === 11001)) {
return callback({
message: 'An account for this email already exists.'
});
} else {

// Make a new user
var u = new User();
u.email = email;
u.password = User.generateHash(password);
u.save(function(err){
if (err){
return callback(err);
} else {
// yay! success.
var token = u.generateAuthToken();

// Send over a verification email
var verificationToken = u.generateEmailVerificationToken();
Mailer.sendVerificationEmail(email, verificationToken);

return callback(
null,
{
token: token,
user: u
}
);
}

});

}

return callback(err);
} else {
// yay! success.
var token = u.generateAuthToken();

// Send over a verification email
var verificationToken = u.generateEmailVerificationToken();
Mailer.sendVerificationEmail(email, verificationToken);

return callback(
null,
{
token: token,
user: u
}
);
}

});
});
};
Expand Down
1 change: 1 addition & 0 deletions app/server/models/User.js
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,7 @@ var schema = new mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
validate: [
validator.isEmail,
'Invalid Email',
Expand Down

0 comments on commit 3be9dd5

Please sign in to comment.