ExpressJS with html5mode while fetching API not working - javascript

I am trying to remove the # sign on the URL using html5mode by stating the location provider html5mode to true
$locationProvider.html5Mode(true);
I also did configured my server.js file to serve my static files and my index.html as below
var express = require('express'),
app = express(),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
port = process.env.PORT || 8080;
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/assets', express.static(__dirname + '/public/assets'));
app.use('/libs', express.static(__dirname + '/public/libs'));
app.all('/*', function(req, res, next) {
res.sendFile('/public/index.html', { root: __dirname });
});
app.use(bodyParser.json());
require('./app/routes.js')(app);
app.listen('8080');
console.log('The magic happens on port 8080');
At this point, everything works fine from localhost:8080 to other navigation such as localhost:8080/login even when I refreshed the page, it is still working fine.
It it not working during any API fetch statement is being called. Below is my routes.js
route.js
var mongoose = require('mongoose'),
db = mongoose.createConnection('mongodb://127.0.0.1/database'),
Role = require('./models/role.js')(db);
User = require('./models/user.js')(db);
module.exports = function(app) {
app.route('/api/user')
.get(function(req, res, next) {
User.find(function(err, user){
if(err)
res.json(err);
res.json(user);
});
})
.post(function(req, res, next) {
var error_return = [{response:'User Existed'},{response:'Invalid Username or Password'},{response:'Server Error'}];
if(req.body.type === "local"){
var newUser = new User();
newUser.first_name = req.body.first_name;
newUser.last_name = req.body.last_name;
newUser.email = req.body.email;
newUser.password = newUser.generateHash(req.body.password);
newUser.type = req.body.type;
newUser.role = req.body.role;
User.findOne({email: req.body.email}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user){
newUser.save(function(error, result){
if(error)
res.json(error_return[2]);
res.json({response:result});
});
return;
}
res.json(error_return[0]);
});
}else if(req.body.type === "login"){
User.findOne({email: req.body.email}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user){
res.json(error_return[1]);
return;
}
if (!user.validPassword(req.body.password)){
res.json(error_return[1]);
return;
}
res.json({response:user});
});
}
});
};
Previously before enabling html5mode, my files in require('./app/routes.js')(app); is running smoothly, after enabling, it is not even being called. Have I missing something in my code?

All your requests are going to public/index.html right now.
Modify your code to allow /api/ requests to go to the routes
app.use('/api', bodyParser.json(), require('./app/routes.js'));
app.use('/app', express.static(__dirname + '/public/app'));
app.use('/assets', express.static(__dirname + '/public/assets'));
app.use('/libs', express.static(__dirname + '/public/libs'));
app.all('/*', function(req, res, next) {
res.sendFile('/public/index.html', { root: __dirname });
});
app.listen('8080');
console.log('The magic happens on port 8080');
routes.js
var mongoose = require('mongoose'),
db = mongoose.createConnection('mongodb://127.0.0.1/database'),
Role = require('./models/role.js')(db),
User = require('./models/user.js')(db),
router = require('express').Router();
module.exports = router;
router.route('/user')
.get(function (req, res, next) {
User.find(function (err, user) {
if (err) res.json(err);
res.json(user);
});
})
.post(function (req, res, next) {
var error_return = [{
response: 'User Existed'
}, {
response: 'Invalid Username or Password'
}, {
response: 'Server Error'
}];
if (req.body.type === "local") {
var newUser = new User();
newUser.first_name = req.body.first_name;
newUser.last_name = req.body.last_name;
newUser.email = req.body.email;
newUser.password = newUser.generateHash(req.body.password);
newUser.type = req.body.type;
newUser.role = req.body.role;
User.findOne({
email: req.body.email
}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user) {
newUser.save(function (error, result) {
if (error) res.json(error_return[2]);
res.json({
response: result
});
});
return;
}
res.json(error_return[0]);
});
} else if (req.body.type === "login") {
User.findOne({
email: req.body.email
}, function (err, user) {
if (err) {
res.json(error_return[2]);
return;
}
if (!user) {
res.json(error_return[1]);
return;
}
if (!user.validPassword(req.body.password)) {
res.json(error_return[1]);
return;
}
res.json({
response: user
});
});
}
});

Related

Login mechanism using jwt / mysql / api for a website

I'm trying to make a login mechanism with jwt but as I'm a newbie, I'm not sure if I'm doing right.
I already made my server.js which looks like this :
const express = require('express');
const bodyParser = require('body-parser');
const session = require('express-session');
const path = require('path');
require('dotenv').config();
var cors = require('cors');
const app = express();
const port = process.env.PORT || 8600;
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.get('/', (req, res) => {
});
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'static')));
const adRoutes = require('./routes/adRoutes.js');
app.use('/Advertisements', adRoutes);
const comRoutes = require('./routes/comRoutes.js');
app.use('/Companies', comRoutes);
const userRoutes = require('./routes/userRoutes.js');
app.use('/Users', userRoutes);
const appRoutes = require('./routes/appRoutes.js');
app.use('/Applications', appRoutes);
const appAuth = require('./routes/loginRoutes.js');
let refreshTokens = [];
app.use('/auth', appAuth);
app.get('/api', authenticateToken, (req, res) => {
res.json(posts.filter(post => post.username === req.user.name))
});
app.post('/auth/token', (req, res) => {
const refrechToken = req.body.token;
if (refrechToken == null) return res.sendStatus(401);
if (!refreshTokens.includes(refrechToken)) return res.sendStatus(403);
jwt.verify(refrechToken, process.env.REFRESH_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
const accessToken = generateAccessToken({ name: user.name });
res.json({ accessToken: accessToken });
}
)
});
app.post('/auth/login', (req, res) => {
const email = req.body.email;
const password = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
const accessToken = generateAccessToken({ email: email });
const refreshToken = jwt.sign(email, process.env.REFRESH_TOKEN_SECRET);
refreshTokens.push(refreshToken);
res.json({ accessToken: accessToken, refreshToken: refreshToken });
});
app.delete('/auth/logout', (req, res) => {
refreshTokens = refreshTokens.filter(token => token !== req.body.token);
res.sendStatus(204);
});
function generateAccessToken(email) {
return jwt.sign(email, process.env.ACCESS_TOKEN_SECRET, { expiresIn: '1800s' });
}
function authenticateToken(req, res, next) {
const authHeader = req.headers['authorization'];
const token = authHeader && authHeader.split(' ')[1];
if (token == null) return res.sendStatus(401);
jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, user) => {
if (err) return res.sendStatus(403);
req.user = user;
next();
});
}
app.listen(port)
And I have a login mechanism that works on Postman but without jwt like this :
const express = require('express');
const router = express.Router();
const path = require('path');
const CryptoJS = require('crypto-js');
const UserController = require('../controllers/userController.js');
var con = require("../config.js");
const { log } = require('console');
router.get('/', function(request, response) {
response.sendFile(path.join(__dirname, '../../front', 'login.html'));
});
router.post('/register', (req, res) => {
const hashedPassword = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
req.body.password = hashedPassword;
UserController.create(req, res);
});
router.post('/login', function(req, res) {
const email = req.body.email;
const hashedPassword = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(req.body.password));
email_ = "\"" + email + "\"";
password_ = "\"" + hashedPassword + "\"";
if (email == "" || hashedPassword == ""){
res.send('Please enter Email and/or Password !');
}
else{
var sql = "SELECT * FROM User WHERE email = " + email_;
con.query(sql, function (err, result) {
if (err) throw err;
if (result.length == 0){
res.send('Incorrect Email !');
}
else{
if (result[0].password == hashedPassword){
req.session.email = result[0].email;
res.send('Login successful!');
}
else{
res.send("Incorrect Password !");
}
}
});
}
});
router.get('/check', function(req, res) {
if (req.session.email) {
console.log(req.session.email);
res.send('Logged in');
} else {
res.send('Not logged in');
}
});
router.get('/logout', function(req, res) {
req.session.destroy();
res.send('Logout successful!');
});
I want to 1. login with token, 2. auto-filled profile using the token and 3. logout system
So that I could make them and that it works on the website, let me know not exact codes but just a mechanism or functions that I need please.
Here's my config.js if you need :
const mysql = require("mysql");
const con = mysql.createConnection({
host: "localhost",
user: "username",
password: "password",
database: "DB name",
port: "port"
});
con.connect((err) => {
if(err)
{
console.warn("Error in connection: " + err.message);
}
});
module.exports = con;

Express APP how to redirect user to /:id path from server side

I'm learning Node.js and I'm finding some troubles with redirecting the user to an :id path. I would like to print there his username.
So to make an overview it is a landing page with a form where I ask for an Alias and an email. When user clicks submit I'd like to move him to /:id path to print its' username.
My code is the following:
var express = require("express"),
app = express(),
request = require("request"),
mongoose = require("mongoose"),
bodyParser = require("body-parser");
app.set("view engine", "ejs")
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect("mongodb://localhost/Scape_Room", {useNewUrlParser: true, useUnifiedTopology: true});
var userSchema = new mongoose.Schema({
email: String,
alias: String,
});
var user = mongoose.model ("user",userSchema);
app.get("/", function(req, res){
res.render("index")
})
app.post("/newuser", function(req,res){
var name = req.body.name;
var email = req.body.email;
var newUser = {name:name, email:email}
user.create(newUser, function(err,newlyUser){
if(err){
console.log(err)
} else {
res.redirect("/start/:id")
}
})
})
app.get("/start/:id", function(req,res){
user.findById(req.params.id, function(err, foundUser){
if(err){
console.log(err)
} else{
res.render("startPoint", {user:foundUser})
}
})
})
app.listen(3000, function(err){
console.log("Server listening")
})
error is the following: { CastError: Cast to ObjectId failed for value ":id" at path "_id" for model "user"
I've tried:
- to change the path to :_id
- added start/ into the route
When you are using the redirect() method, you must pass a real route url not an id.
const express = require("express")
const request = require("request");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const app = express();
app.set("view engine", "ejs")
app.use(express.static("public"));
mongoose.connect("mongodb://localhost/Scape_Room", { useNewUrlParser: true, useUnifiedTopology: true });
const userSchema = new mongoose.Schema({
email: String,
alias: String,
});
const user = mongoose.model("user", userSchema);
app.get("/", function (req, res) {
res.render("index");
});
app.post("/newuser", function (req, res) {
const { name, email } = req.body;
if (!name || !email) {
return res.end();
}
const newUser = { name: name, email: email }
user.create(newUser, function (err, newlyUser) {
if (err) {
console.log(err);
return res.end();
}
if (!newlyUser) {
console.log("Couldn't save user!");
return res.end();
}
if (!newlyUser.id) {
console.log("No user id found");
return res.end();
}
res.redirect(`/start/${newlyUser.id}`);
});
});
app.get("/start/:id", function (req, res) {
user.findById(req.params.id, function (err, user) {
if (err) {
console.log(err);
} else {
res.render("startPoint", { user });
}
})
})
app.listen(3000, function (err) {
console.log("Server listening")
});
Use something like below
app.post("/newuser", function(req,res){
var name = req.body.name;
var email = req.body.email;
var newUser = {name:name, email:email}
user.create(newUser, function(err,newlyUser){
if(err){
console.log(err)
} else {
res.redirect(`/start/${newlyUser._id}`)
}
})
})

Node.js Mongodb Intergration Issues; .save()

This is an example site that I have created with a basic Node.js server. I am able to successfully post, create a user given the schema, and "save" to the database; however, saving does not return the user object and cannot be found in my actual database. The connection is also returned as successful.
main.js
const session = require('express-session');
const pug = require('pug');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const User = require('./schema.js');
const app = express();
var path = require('path');
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient('mongodb://localhost:27017');
var db;
client.connect((err, client) => {
if (err) {
console.log(err);
}
else if (!err) {
db = client.db('node');
console.log('Connected to Mongodb');
client.close()
}
});
app.engine('pug', require('pug').__express)
app.set('view engine', 'pug');
app.use(bodyParser.urlencoded({ extended : true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'styles')));
app.use(session({secret: 'testing',saveUninitialized: true,resave: true}));
//root directory get response
app.get('/', (req, res) => {
res.render('homepage', {
title : 'Homepage',
req : req
});
});
//register directory get response
app.get('/register', (req, res) => {
res.render('register', {
title : 'Register',
req: req
});
});
//profile directory get response
app.get('/profile', (req, res) => {
res.render('profile', {
title: 'Profile',
email: req.session.email,
username: req.session.username,
req: req
});
});
//login directory get response
app.get('/login', (req, res) => {
res.render('login', {
title: 'Login',
req: req
})
})
//register directory post request
app.post('/register', (req, res) => {
console.log(req.body);
if(req.body.username && req.body.email && req.body.password){
var user = User({
email : req.body.email,
username : req.body.username,
password : req.body.password
});
console.log(user);
user.save((err) => {
user.markModified('password')
console.log("Trying to save")
console.log(user)
if(err){
console.log(err);
} else {
var sess = req.session;
sess.email = req.body.email;
console.log("Saved")
res.redirect('/profile')
}
});
}
});
//login directory post request
app.post('/login', (req, res) => {
console.log(req.body);
if(req.body.username && req.body.password){
var sess = req.session;
sess.username = req.body.username;
res.redirect('/profile')
}
})
const server = app.listen(8000, () => {
console.log(`Express running → PORT ${server.address().port}`);
});
schema.js
const bcrypt = require('bcrypt');
var UserSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true,
trim: true
},
username: {
type: String,
unique: true,
required: true,
trim: true
},
password: {
type: String,
unique: false,
required: true,
trim: true
}
});
UserSchema.pre('save', function(req, err, next) {
var user = this;
bcrypt.genSalt(10, (err, salt) => {
if(err){
return next(err);
}
bcrypt.hash(user.password, salt, (err, hash) => {
if(err){
return next(err);
}
user.password = hash;
console.log(hash);
next()
});
});
});
var User = mongoose.model('User', UserSchema);
module.exports = User;
You are using mongoose to create models and make db querys but not connecting to mongoose. Instead you are connecting to MongoDb native driver.
Replace this
const MongoClient = require('mongodb').MongoClient;
const client = new MongoClient('mongodb://localhost:27017');
var db;
client.connect((err, client) => {
if (err) {
console.log(err);
}
else if (!err) {
db = client.db('node');
console.log('Connected to Mongodb');
client.close()
}
});
with
mongoose.connect(connectionString, {useNewUrlParser: true});
mongoose.connection.on("open", function(ref) {
console.log("Connected to mongo server.");
});
mongoose.connection.on("error", function(err) {
console.log("Could not connect to mongo server!");
console.log(err);
});
Try this var user = new User({ ... }); instead of this var user = User({ ... });. Notice the new keyword.

passportjs: user undefined, req.isAuthenticated() is false

Note: there are many similar questions but I've gone through all of them and none of the solutions work.
Hi,
I've tried every solution on the net, bug still persists.
I'm building a simple CRUD app, and I'm currently struggling with passportjs's req.isAuthenticated().
The user is definitely being authenticated, as console.log(req.user) in passport.authenticate returns the user object, and req.session.passport has the user id.
After the redirect though, even if the redirect is async, user is undefined and req.session.passport is empty. It's as if the session is reset.
Here's the code:
app.js
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');
var flash = require('connect-flash');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/bootstrap', express.static(path.join(__dirname + '/node_modules/bootstrap/dist')));
app.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 5 * 60 * 1000
}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
app.use(function(req, res, next) {
res.locals.messages = require("express-messages")(req, res);
next();
});
app.get('*', function(req, res, next) {
console.log(req.method, ":", req.url);
res.locals.user = req.user || null;
next();
});
app.use("/", index);
app.use("/users", users);
var port = 4000;
app.listen(port);
module.exports = app;
index.js
var express = require('express');
var router = express.Router();
router.get('/', isLoggedIn, function(req, res) {
if (req.user) {
console.log(req.user.username);
}
res.render('homepage');
});
function isLoggedIn(req, res, next) {
console.log("passport: ", req.session.passport); //passport:{}
if (req.isAuthenticated()) {
return next();
}
res.redirect('/users/login');
}
module.exports = router;
users.js
var express = require('express');
var router = express.Router();
var mongojs = require('mongojs');
var db = mongojs('usersDB', ['users']);
var bcrypt = require('bcryptjs');
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;​
router.get('/login', function(req, res) {
res.render('login');
});​
router.get('/signup', function(req, res) {
res.render('signup');
});​
router.post('/signup', function(req, res) {
db.users.findOne({
username: req.body.name
}, function(err, user) {
if (err) {
return done(err);
}
if (user) {
console.log("nope");
req.flash("error", "Username taken. Choose a different username.");
return res.redirect('/users/signup');
}
var password = req.body.password;
bcrypt.genSalt(10, function(err, salt) {
if (err) {
return done(err);
}
bcrypt.hash(password, salt, function(err, hash) {
if (err) {
return done(err);
}
var user = {
username: req.body.name,
email: req.body.email,
phone: req.body.phone,
password: hash
}
db.users.insert(user, function(err, result) {
if (err) {
return done(err);
}
console.log("registered", user)
res.render("homepage", {
user: user
});
});
});
});
});
}); //sorry for the callback hell..works fine
​​
passport.serializeUser(function(user, done) {
return done(null, user._id);
});​
passport.deserializeUser(function(id, done) {
db.users.findOne({
id: mongojs.ObjectId(id)
}, function(err, user) {
return done(err, user);
});
});​
passport.use('loginStrategy', new LocalStrategy({
passReqToCallback: true,
usernameField: 'username',
passwordField: 'password'
},
function(req, username, password, done) {
db.users.findOne({
username: username
}, function(err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, req.flash('error', "Invalid username."));
}
bcrypt.compare(password, user.password,
function isMatch(err, isMatch) {
if (err) {
return done(err);
}
if (!isMatch) {
return done(null, false, req.flash('error', "Oops. Incorrect password."));
}
return done(null, user, req.flash('success', "Welcome " + user.username + ", you are now logged in."));
});
});
}​));​
router.post('/login', function(req, res, next) {
passport.authenticate('loginStrategy', function(err, user, info) {
if (info) {
req.flash('error', info.message);
}
if (err) {
return next(err);
}
if (!user) {
return res.redirect('/users/login');
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
//callback redirect after saving session.
req.session.save(function() {
console.log(req.session.passport); //{ user: 59ceb263dae7a4270087ae57 }
res.redirect('/');
});
});
})(req, res, next);
});​
router.get('/logout', function(req, res) {
req.logout();
res.redirect('/users/login');
});​
module.exports = router;
I would really appreciate some help, as this is seems to be a common bug, but none of the workarounds work for me.
This seems to be related to the method you are using to store the user creds. Please note, Chrome and IE have different quirks about local vs session storage. Try this in chrome, Passport JS will store the response in either Local or Session storage - you should interrogate those storage mechanisms to verify the user's credentials are in them.
In chrome, go to the F12 debug tools and look in your session and local storage:
Please let us know the browser you are using, and if using Chrome makes a difference.

passport module on node.js - Reference Error: LocalStrategy is not defined

When I try to run my code it gives me Reference Error: LocalStrategy is not defined.
This is my first time using node.js and I hit a wall with this. I appreciate the help in advance.
I put all the code in one snippet so you can go through it easily. I have tried other posts for fixes but have been unsuccessful.
/***********
Modules
***********/
//Load the express library
var express = require('express');
//Create a new variable called “app”; we pass on the express() method.
var app = express();
//Set Port
var port = 7878;
var mongoose = require('mongoose'); //Place this on top; Loads mongoose library
var bodyParser = require('body-parser');
var passport = require('passport');
var LocalStratgy = require('passport-local').Strategy;
/*Body parser*///whenever you do a post request from the form, it gets the data through a URL encoded format.
app.use(bodyParser.urlencoded({
extended: true
}));
app.use('/js', express.static(__dirname + '/js'));
/*Initialize Passport*/
app.use(passport.initialize());
app.use(passport.session());
/***********
Database
***********/
/*Database connection - MongoDB*/
//Created from the command earlier. Ensure this is done on the first_db instance
var usr = 'admin';
var pwd = '123456';
var dbHost = 'localhost';
var dbPort = '27017';
var database = 'first_db';
var url = 'mongodb://' + usr + ':' + pwd + '#' + dbHost + ':' + dbPort + '/' + database;
console.log('mongodb connection = ' + url);
mongoose.connect(url, function(err) {
if(err) {
console.log('connection error: ', err);
} else {
console.log('connection successful');
}
});
/***********
Models
***********/
//User model
//Define our fields for the table
var UserSchema = new mongoose.Schema({
user_id: mongoose.Schema.ObjectId,
username: String,
password: String
});
//Create model object
var User = mongoose.model('user', UserSchema);
/***********
Routes
***********/
var bcrypt = require('bcrypt-nodejs'); //should be placed on top
//Renders our html file
app.get('/', function (req, res, next) {
res.sendFile( __dirname + '/index.html');
});
//render register.html when /register is called
app.get('/register', function (req, res, next) {
res.sendFile( __dirname + '/register.html');
});
app.get('/home', function (req, res, next) {
res.sendFile(__dirname + '/home.html');
});
app.post('/login', passport.authenticate('local'),
function(req, res) {
res.redirect('/home');
});
/* Login logic for passport.authenticate*/
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function (err, user) {
if(user !== null) {
var isPasswordCorrect = bcrypt.compareSync(password, user.password);
if(isPasswordCorrect) {
console.log("Username and password correct!");
return done(null, user);
} else {
console.log("Password incorrect!");
return done(null, false);
}
} else {
console.log("Username does not exist!");
return done(null, false);
}
});
}
));
/**********
Serialize and Deserialize here for passport.authenticate
**********/
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(err, user);
});
app.post('/register', function (req, res, next) {
var password = bcrypt.hashSync(req.body.password);
req.body.password = password;
User.create(req.body, function(err, saved) {
if(err) {
console.log(err);
res.json({ message : err });
} else {
res.json({ message : "User successfully registered!"});
}
});
});
app.listen(port, '0.0.0.0', function() {
console.log('Server running at port ' + port);
});
The reason is you have defined var LocalStratgy, not LocalStrategy.
You're using it like this-
https://www.npmjs.com/package/passport-local-mongoose#configure-passportpassport-local
// use static authenticate method of model in LocalStrategy
passport.use(new LocalStrategy(User.authenticate()));
// use static serialize and deserialize of model for passport session support
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
But I suggest you to use it like this -
https://www.npmjs.com/package/passport-local-mongoose#simplified-passportpassport-local-configuration
// CHANGE: USE "createStrategy" INSTEAD OF "authenticate"
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

Categories