Check if username is taken - PassportJS

一笑奈何 提交于 2019-12-12 02:15:59

问题


I am needing to check that the username is not taken before a user creates an account. I am attempting to build a one page application with AJAX and passport.

How would I go about checking to see if the username is taken BEFORE posting when a user is registering using passport?

Not sure where to start.

Thanks!

app.post("/quiz", function(req, res){

    var newUser = new User({username: req.body.username, datapoint: req.body.datapoint});
    User.register(newUser, req.body.password, function(err, user){


        // if(res.error){

          if(err){
            req.flash("error", err.message);
            res.redirect('back')
            return res.render("quiz");

        } else {

        passport.authenticate("local")(req, res, function(){
        //   req.flash("success", "Welcome to JobQuiz " + user.username);
          res.redirect("jobquiz");
          console.log(req.body.datapoint)
        });
        }
    });

});

回答1:


First find if the user exists using findOne function. If user exists then you can just return an error

app.post("/quiz", function(req, res){
    User.findOne({username: req.body.username}, function(err, user){
       if(err) {//error handling... }
       if(user) { //user already exists. throw error accordingly}

       //continue with your registration logic
       var newUser = new User({username: req.body.username, datapoint: req.body.datapoint});
         User.register(newUser, req.body.password, function(err, user){


        // if(res.error){

             if(err){
               req.flash("error", err.message);
               res.redirect('back')
               return res.render("quiz");

           } else {

           passport.authenticate("local")(req, res, function(){
           //   req.flash("success", "Welcome to JobQuiz " + user.username);
             res.redirect("jobquiz");
             console.log(req.body.datapoint)
           });
           }
       });
    });


});

The above code is handled in a callback. If you want to avoid callback hell you can use promises




回答2:


If you're using passport-local-mongoose, User.register() will check and give the error message:

A user with the given username is already registered

You can view the other error codes here



来源:https://stackoverflow.com/questions/42615404/check-if-username-is-taken-passportjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!