Jesus Soto Jesus Soto - 6 months ago 14
AngularJS Question

How to show failure message on signup using MEAN stack

I am developing an SPA which use passport authentication to do the login and signup proccess. The thing is that everything works fine, I can even show a success notification, but I can't find out a way to show an error notification in case the user makes a bad operation.

Here is my code for signup in passport-init:

passport.use('signup', new LocalStrategy({
passReqToCallback : true
},
function(req, username, password, done){
var email = req.body.email;
User.findOne({$or:
[
{username: username},
{email: email}
]
}, function(err, user){
if(err){
return done(err, false);
}

if(user) {
console.log('username or email already taken '+req.body.username);
return done(null, false, {message: 'Username or email already taken.'});
}

user = new User();

if(req.body.password===req.body.username || req.body.password===req.body.fullname
|| req.body.password===req.body.email){
console.log('The password can not be equals to your fullname'+
', username or email. Try another password.');
return done(null, false, {message: 'The password can not be equals to your fullname'+
', username or email. Try another password.'});
}


Then if non of this cases happens the method returns no errors with the user data.

Here is the route code to pass results to angular:

router.get('/failure', function(req, res){
res.send({state: 'failure', user: null, message: "Invalid username or password"});
});

router.post('/signup', passport.authenticate('signup',{
successRedirect: '/auth/success',
failureRedirect: '/auth/failure',
failureFlash: true
}));


And finally I got this angular in order to call and get a response:

$scope.register = function(){
$http.post('/auth/signup', $scope.user).then(

function(data){
$rootScope.authenticated = true;
$rootScope.current_user = data.user.username;
$rootScope.signUp = true;
},

function(data, status){
console.log(status);
}
);
};


This is it. Ofcourse the angular code is inside a controller. I just began learning to build MEAN stack applications so, any help will be appreciated.

Answer

If there's a custom error/ custom logic you should send an error back to the client:

if(user)
return done({error:'userAlreadyTaken'},false);

the same for the other conditions you have in your code.

Comments