0

I used passportjs and passport-local-mongoose for creating user signup. This is my code

var express         =require("express"),
    app             =express(),
    bodyParser      =require("body-parser"),
    passport        =require("passport"),
    LocalStrategy   =require("passport-local"),
    User            =require("./models/user"),
    mongoose        =require("mongoose"),
    exphbs      =require("express-handlebars");

mongoose.connect("mongodb://localhost/lone");
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
var hbs = exphbs.create({
    defaultLayout: 'main',


    partialsDir: [

        'views/partials/'
    ]
});
app.use(express.static(__dirname +"/public"))

app.engine('handlebars', hbs.engine);
app.set("view engine", "handlebars");

app.use(require("express-session")({
    secret:"You are beautiful",
    resave: false,
    saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(function (req,res,next) {
    res.locals.currentUser=req.user;
    next();

});
//Auth Routes
app.get("/signup",function(req,res){
    res.render("signup");
});
app.get("/",function(req,res){
res.render("home");
});
app.post("/signup",function(req,res,next){
    var newUser= new User({username: req.body.userName,name:req.body.firstName,email:req.body.email});
    User.register(newUser, req.body.password, function(err,user){
        if (err){
            console.log(err);
            res.redirect("/login")
            return next();
        }
        passport.authenticate("local")(req,res,function(){

            res.redirect("/");
            return next();
        });
    })
});
app.get("/login",function(req,res){
    res.render("login");
});
app.get("/logout",function(req,res){
    req.logout();
    res.redirect("/");
});
app.get("/",function (req,res) {
    res.render("home");

});
app.listen(3000,function(){
    console.log("started");

});

When I click on submit signup button I get an error which says bad request. and this is the message I get in my console { [UserExistsError: A user with the given username is already registered] name: 'UserExistsError', message: 'A user with the given username is already registered' }

Alan Xalil
  • 1
  • 1
  • 6
  • Probably unrelated to your error, but don't call `next()` after `res.redirect()`. Once you've sent the response, don't call `next()` because you don't want any other handlers seeing this request. – jfriend00 Nov 09 '16 at 17:26
  • ... does the user already exist in your database? – Josh Beam Nov 09 '16 at 18:33
  • No the user does not exist. But I think the problem is with register method. when I run the program it will loop twice in the register method. – Alan Xalil Nov 09 '16 at 21:19

2 Answers2

0

Nothing is wrong with your code.

You are trying to sign up a user, with a username that is already taken. You can handle this more gracefully like so :

app.post("/signup",function(req,res,next){
  var newUser= new User({username: req.body.userName,name:req.body.firstName,email:req.body.email});
  User.register(newUser, req.body.password, function(err,user){
    if (err){
        console.log(err);
        return next(err);
    }
    passport.authenticate("local", function(_err, user){
        if(_err) return next(_err);
        res.redirect("/");
        return next();
    });
  })
});
Moshe Karmel
  • 459
  • 4
  • 9
  • I did a debug on this app. It seems the problem is in the register method. The program loop twice, At the first time it doesn't get inside the callback function, but in the second round it will get inside the function and recognize the user as exist. – Alan Xalil Nov 09 '16 at 20:53
-1

I am getting the Same Error, This error is not of Username which is already registered. This is because of your email is already registered in database.

Rajat
  • 486
  • 1
  • 10
  • 35