Skip to content

Instantly share code, notes, and snippets.

@yukeehan
Created July 16, 2018 02:53
Show Gist options
  • Save yukeehan/23fbbe53f1ca94be440161c1562b489a to your computer and use it in GitHub Desktop.
Save yukeehan/23fbbe53f1ca94be440161c1562b489a to your computer and use it in GitHub Desktop.
Login/Logout/Register using Passport-Local-Mongoose
var express = require("express"),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
User = require("./models/user"),
passport = require("passport"),
LocalStrategy = require("passport-local"),
passportLocalMongoose = require("passport-local-mongoose");
mongoose.connect("mongodb://localhost:27017/auth_demo_app", { useNewUrlParser: true });
var app = express();
app.set("view engine","ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(require("express-session")({
secret:"Miss white is my cat",
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());
// ===================
// ROUTES
// ===================
app.get("/",function(req, res){
res.render("home");
});
app.get("/secret", isLoggedIn, function(req, res){
res.render("secret");
});
app.get("/register", function(req, res){
res.render("register");
});
// handeling user sign up
app.post("/register", function(req, res){
// console.log(req.body.username);
// console.log(req.body.password);
User.register(new User({username: req.body.username}), req.body.password, function(err, user){
if(err){
console.log(err);
return res.render("register");
}
passport.authenticate("local")(req, res, function(){
res.redirect("/secret");
});
});
});
// Login Form
app.get("/login", function(req, res){
res.render("login");
});
// Login Logic
// middleware
app.post("/login", passport.authenticate("local",{
successRedirect: "/secret",
failureRedirect: "/login"
}), function(req, res){
});
// Logout
app.get("/logout", function(req, res){
req.logout();
res.redirect("/");
});
// check isLoggedIn
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
res.redirect("/login");
}
app.listen(process.env.PORT, process.env.IP, function(){
console.log("app started!!!")
});
<h1>This is the homepage!</h1>
<li><a href="/register">register!</a></li>
<li><a href="/login">login!</a></li>
<li><a href="/logout">logout!</a></li>
<h1>Login Page</h1>
<form action="/login" method="POST">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<button>Submit</button>
</form>
<li><a href="/register">register!</a></li>
<li><a href="/login">login!</a></li>
<li><a href="/logout">logout!</a></li>
<h1>Sign Up Form</h1>
<form action="/register" method="POST">
<input type="text" name="username" placeholder="username">
<input type="password" name="password" placeholder="password">
<button>Submit</button>
</form>
<li><a href="/register">register!</a></li>
<li><a href="/login">login!</a></li>
<li><a href="/logout">logout!</a></li>
<h1>Secret page</h1>
<li><a href="/register">register!</a></li>
<li><a href="/login">login!</a></li>
<li><a href="/logout">logout!</a></li>
var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = new mongoose.Schema({
username: String,
password: String
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
@oyenmwen
Copy link

How would I go about updating a user's password to a new one. Route wise

@florianjs
Copy link

How would I go about updating a user's password to a new one. Route wise

https://stackoverflow.com/questions/17828663/passport-local-mongoose-change-password

@osanyin1986
Copy link

If I want to add confirmpassword with this can you explain how to go about it .
User.register(new User({username: req.body.username}), req.body.password, function(err, user){
if(err){
console.log(err);
return res.render("register");

@RogS08
Copy link

RogS08 commented Apr 28, 2021

passportLocalMongoose = require("passport-local-mongoose"); is unused?
line 69?

@gabo71096
Copy link

If I want to add confirmpassword with this can you explain how to go about it . User.register(new User({username: req.body.username}), req.body.password, function(err, user){ if(err){ console.log(err); return res.render("register");

Hi! You have to compare both passwords before registering, something like if (req.body.password === req.body.password1) { User.register(...) }

@Nazehs
Copy link

Nazehs commented Jan 17, 2022

How can you return a JSON response to the client when password/username is not valid?

@lunacodes
Copy link

I'm trying to run this, but run into an error that Error: req#logout requires a callback function when trying to logout. Anyone have any suggestions for how to fix that? Here's the full error message:

Error: req#logout requires a callback function
    at IncomingMessage.req.logout.req.logOut (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\passport\lib\http\request.js:65:44)
    at C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\server\app.js:75:9
    at Layer.handle [as handle_request] (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\index.js:346:12)
    at next (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\index.js:280:10)
    at SessionStrategy.strategy.pass (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\passport\lib\middleware\authenticate.js:346:9)

@OREdwardsJr
Copy link

I'm trying to run this, but run into an error that Error: req#logout requires a callback function when trying to logout. Anyone have any suggestions for how to fix that? Here's the full error message:

Error: req#logout requires a callback function
    at IncomingMessage.req.logout.req.logOut (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\passport\lib\http\request.js:65:44)
    at C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\server\app.js:75:9
    at Layer.handle [as handle_request] (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\index.js:346:12)
    at next (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\express\lib\router\index.js:280:10)
    at SessionStrategy.strategy.pass (C:\Users\lunac\sites\web-dev-and-design-learning-progress-log\express-passport-local-mongoose-plugin\node_modules\passport\lib\middleware\authenticate.js:346:9)

See this Stackoverflow response for the answer.

@meherhendi
Copy link

userSchema.plugin(passportLocalMongoose); should be added in order for User.authenticate() to work:

'./models/user'


const mongoose = require("mongoose");

const userSchema = new mongoose.Schema({
  username: { type: String, required: true },
  password: { type: String, required: true },
});

const passportLocalMongoose = require("passport-local-mongoose");
userSchema.plugin(passportLocalMongoose);
const user = mongoose.model("user", userSchema);
module.exports = user;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment