Getting an error when using req.session.userID - node.js

I'm using req.session.userID variable to set a sessionID for the user.
My code is
On the server side,
router.post('/signin', bodyParser.json(),function(req, res){
var db = req.db;
var collection = db.get('userCollection');
var name = req.body.name;
var password = req.body.password;
name = name.trim();
password = password.trim();
collection.find({"name":name}, {}, function(e1, username){
if (e1 === null){
if (username[0].password == password) {
req.session.userID = username[0]._id;
var string2 = "before session" + req.session.userID + "after session" + username[0]._id;
res.send(string2);
}
else {
res.send("Failure!");
}
}
});
And on the client side
router.post('/signin', bodyParser.json(),function(req, res){
var db = req.db;
var collection = db.get('userCollection');
var name = req.body.name;
var password = req.body.password;
name = name.trim();
password = password.trim();
collection.find({"name":name}, {}, function(e1, username){
if (e1 === null){
if (username[0].password == password) {
req.session.userID = username[0]._id;
var string2 = "before session" + req.session.userID + "after session" + username[0]._id;
res.send(string2);
}
else {
res.send("Failure!");
}
}
});
I have also set a secret token for in my app.js as advised in some other answers, but still whenever I user req.session.userID it gives me an error.
The moment I remove req.session.userID and just send a normal statement back it works. Can anyone tell me what could be the possible reason for this.
My app.js looks something like this...
var session = require('express-session');
app.use(session({
secret: 'secret token'
}))
I have even installed express-session. Should I be doing something else too?
Full app.js code,
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var mongo = require('mongodb');
var monk = require('monk');
var db = monk('localhost:27017/learnproject1');
var logger = require('morgan');
var bodyParser = require('body-parser');
var indexRouter = require('./routes/myroutes.js');
//var userRouter = require('.')
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(function(req,res,next){
req.db = db;
next();
});
app.use('/', indexRouter);
//app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
app.use(session({
secret: 'secret token'
}))
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;

Related

"express-session deprecated undefined resave option; provide resave option node_modules/admin-bro-expressjs/plugin.js:138:14"

am using admin-bro for my admin , it works fine until i try to use its authentication, when i try to login to the admin using the admin-bro login form dashboard ,it just keeps loading with no response,my terminal says
express-session deprecated undefined resave option; provide resave option node_modules/admin-bro-expressjs/plugin.js:138:14
express-session deprecated undefined saveUninitialized option; provide saveUninitialized option node_modules/admin-bro-expressjs/plugin.js :138:14 AdminBro: bundle ready we're connected!
here's my app.js file
require('dotenv').config();
const express = require('express');
const engine = require('ejs-mate');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
const passport = require('passport');
const User = require('./models/user');
//const formidableMiddleware = require('express-formidable');
const session = require('express-session');
const mongoose = require('mongoose');
const methodOverride = require('method-override');
// const seedPosts = require('./seeds');
// seedPosts();
// require routes
const index = require('./routes/index');
const posts = require('./routes/posts');
const reviews = require('./routes/reviews');
const adminRouter= require('./routes/admin.router');
const app = express();
//connect to database
//var url = process.env.DATABASEURL || "mongodb://localhost:27017/surf-shop"
mongoose.connect("mongodb://localhost:27017/surf-shop" , {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', () => {
console.log('we\'re connected!');
});
// use ejs-locals for all ejs templates:
app.engine('ejs', engine);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// set public assets directory
app.use(express.static('public'));
//app.use(favicon(path.join(__dirname, 'public', 'favi.jpg')));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(methodOverride('_method'));
// Configure Passport and Sessions
app.use(session({
secret: 'hang ten dude!',
resave: false,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(User.createStrategy());
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// set local variables middleware
app.use(function(req, res, next) {
// req.user = {
// // '_id' : '5bb27cd1f986d278582aa58c',
// // '_id' : '5bc521c0b142b6d7f7523406',
// '_id' : '5bfed10ad176f845e38aec92',
// 'username' : 'ian3'
// }
res.locals.currentUser = req.user;
// set default page title
res.locals.title = 'Surf Shop';
// set success flash message
res.locals.success = req.session.success || '';
delete req.session.success;
// set error flash message
res.locals.error = req.session.error || '';
delete req.session.error;
// continue on to next function in middleware chain
next();
});
// Mount routes
app.use('/', index);
app.use('/posts', posts);
app.use('/posts/:id/reviews', reviews);
app.use('/admin', adminRouter);
//app.use(formidableMiddleware());
// catch 404 and forward to error handler
app.use(function(req, res, next) {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// // set locals, only providing error in development
// res.locals.message = err.message;
// res.locals.error = req.app.get('env') === 'development' ? err : {};
// // render the error page
// res.status(err.status || 500);
// res.render('error');
console.log(err);
req.session.error = err.message;
res.redirect('back');
});
module.exports = app;
here's my admin.route.js file
const AdminBro = require('admin-bro');
const AdminBroExpress = require('admin-bro-expressjs');
const AdminBroMongoose = require('admin-bro-mongoose');
const mongoose = require('mongoose');
AdminBro.registerAdapter(AdminBroMongoose);
const adminBro = new AdminBro({
databases: [mongoose],
rootPath: '/admin',
});
const ADMIN = {
email: process.env.ADMIN_EMAIL || 'admin#example.com',
password: process.env.ADMIN_PASSWORD || 'lovejs',
}
const router = AdminBroExpress.buildAuthenticatedRouter(adminBro, {
cookieName: process.env.ADMIN_COOKIE_NAME || 'admin-bro',
cookiePassword: process.env.ADMIN_COOKIE_PASS || 'some-super-sensitive-password',
authenticate: async (email, password) => {
if (ADMIN.password === password && ADMIN.email === email) {
return ADMIN
}
return null
}
});
module.exports = router;
any help would be appreciated
Put your app.use('/admin', adminRouter); before app.use(express.json());
That was how I solved the problem because admin bro has an issue with express body parser or the built in one.
delete app.use(express.urlencoded({ extended: true }));

Node.js & Express Form Submit returns 404

I'm trying to make a simple file upload system but everytime I submit my uploaded file I get a 404 error. I've tried various different names and paths but all of them fail instantly. When I press submit, the browser tries to redirect to /upload then returns the 404 error. I'm new to node.js so it may as well be very simple to solve but I couldn't find it.
I've tried 2 different modules, formidable and express-fileupload. Both return the same error.
./views/test2.ejs
<html>
<head>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="filetoupload"><br>
<input type="submit">
</form>
</body>
./routes/test2.js
var express = require('express');
var router = express.Router();
var http = require('http');
var formidable = require('formidable');
router.get('/', function (req, res, next) {
res.render('test2');
res.sendFile(__dirname + '/test2.ejs');
});
router.post('/upload', function (req, res, next) {
var form = new formidable.IncomingForm();
form.parse(req);
form.on('fileBegin', function (name, file) {
file.path = __dirname + '/uploads/' + file.name;
});
form.on('file', function (name, file) {
console.log('Uploaded ' + file.name);
});
res.sendFile(__dirname + '/test2.ejs');
});
module.exports = router;
./app.js
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');
mongoose.connect("REDACTED", function(err,db){
if(!err){
console.log("Connected");
}
});
var index = require('./routes/index');
var users = require('./routes/users');
var login = require('./routes/login');
var form = require('./routes/form');
var buttonrelay = require('./routes/buttonrelay');
var tesekkurler = require('./routes/tesekkurler');
var test = require('./routes/test');
var test2 = require('./routes/test2');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
//app.use(expressLayout);
// Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
app.use(expressValidator());
// Express Session
app.use(session({
secret: REDACTED,
saveUninitialized: true,
resave: true
}));
app.use('/', index);
app.use('/users', users);
app.use('/login', login);
app.use('/form', form);
app.use('/buttonrelay', buttonrelay);
app.use('/tesekkurler', tesekkurler);
app.use('/test', test);
app.use('/test2', test2);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
you used app.use('/test2', test2); for the /upload routing
So form action should be "/test2/upload"

Session Issue with nodejs

I seem to be having a problem when applying a user to a session. When I login, the function runs perfect and bcrypt check the password perfectly. But when the req.session.user = user is called I get Cannot set property user of undefined.
Here is my users.js file
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
var expressValidator = require('express-validator');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
router.use(expressValidator);
var UserModel = require('../models/user');
/* GET users listing. */
router.get('/register', function(req, res, next) {
res.send('respond with a resource');
});
router.get('/login', function(req, res, next) {
res.send('respond with a resource');
});
router.registerUser = function(req,res){
console.warn('Getting Here');
var name = req.body.name;
var email = req.body.email;
var username = req.body.username;
var password = req.body.password;
var password2 = req.body.password2;
console.log(req.body.name);
var newUser = new UserModel({
name:name,
email:email,
username:username,
password: password
});
UserModel.createUser(newUser, function(err,user){
if(err) throw err;
console.log(user);
});
}
router.login = function(req,res){
var username = req.body.username;
var password = req.body.password;
UserModel.findById("584340be3f63a303484eccc0", function(err, user){
console.warn(user.username);
console.warn(user.password);
bcrypt.compare(password , user.password, function(err,res) {
if (err) throw err;
});
console.warn (user);
req.session.user = user;
console.warn(req.session.user);
})
}
module.exports = router;
As you can see in the file im finding a user in the DB and comparing its string. If the strings are correct I just want to add the user to the session. Here is my app.js file where the middleware is housed.
var session = require('express-session');
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var passport = require('passport');
var LocalStrategy = require('passport-local'),Strategy;
var mongo = require('mongoose');
var routes = require('./routes/index');
var users = require('./routes/users');
var candidates = require('./routes/candidates.js');
var supporters = require('./routes/supporters.js');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
app.get('/candidates', candidates.findAll);
app.get('/candidates/:id', candidates.findOne);
app.put('/candidates/:id/votes', candidates.incrementUpvotes);
app.delete('/candidates/:id', candidates.deleteCandidate);
app.get('/supporters', supporters.findAll);
app.get('/supporters/:id', supporters.findOne);
app.post('/supporters',supporters.addPerson);
app.post('/candidates', candidates.addPerson);
app.post('/candidates/:id',candidates.updateCandidate);
app.post('/image',candidates.addImage);
app.post('/register', users.registerUser);
app.post('/login', users.login);
app.delete('/supporters/:id', supporters.deleteSupporter);
// catch 404 and forward to error handler
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
app.use(session({
cookieName: 'session',
secret: 'random_string_goes_here',
duration: 30 * 60 * 1000,
activeDuration: 5 * 60 * 1000,
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(expressValidator({
errorFormatter: function(param,msg,value){
var namespace = param.split('.'),
root = namespace.shift(),
formParam = root;
while(namespace.length){
formParam += '[' + namespace.shift() + ']';
}
return{
param: formParam,
msg: msg,
value: value
};
}
}
));
//Connect Flash
app.use(flash());
app.use(function(req,res,next){
res.locals.success_msg = req.flash('success_msg');
res.locals.error_msg = req.flash('error_msg');
res.locals.error = req.flash('error');
next();
});
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
I've been at this problem for quite a while now and was wondering if anyone can send me in the right direction. Thanks in advance!
I found the issue. In app.js I had some of my app.use functions placed below the app.user('router') and it was causing the issue

How to share Session across multiple route JS files in ExpressJS

First of all, I am using:
express-session#1.14.2
express#4.14.0
I am basically trying to get a login system working and when user logs in, I set session.isloggedin = true.
So this is my app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var index = require('./routes/index');
var portfolioRoute = require('./routes/portfolio');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
// CORS (Cross-Origin Resource Sharing) headers to support Cross-site HTTP requests
app.all('*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
next();
});
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { secure: true,
maxAge: new Date(Date.now() + 2 * 60 * 1000) }
}));
app.use('/', index);
app.use('/portfolio', portfolioRoute);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
The index.html contains the login form.
Next, my index.js
var express = require('express');
var router = express.Router();
var util = require('util');
var api = require('../server/api.js');
var port = require('../server/portfolio.js');
var sess;
/* GET home page. */
router.get('/', function (req, res) {
sess = req.session;
console.log("SESSION IS: " + sess.isLoggedIn);
if(sess.isLoggedIn) {
res.render('portfolio', { isLoggedIn: true })
} else {
res.render('index', { isLoggedIn: false })
}
})
//END ------------
if(global.GLB_PORTFOLIO === null) {
port.getPortfolio(null, function(err, result) {
global.GLB_PORTFOLIO = result;
});
}
// API Routes
//router.use('/api', router);
router.route('/api/login')
.post(api.postLogin)
router.route('/api/portfolio')
.post(api.postPortfolio)
.get(api.getPortfolio)
//END ------------
module.exports = router;
Next, my api.js:
var util = require('util');
const backend = require('./portfolio.js');
exports.postPortfolio = function(req,res) {
backend.insertPortFolio(req.body, function(err, result) {
res.json({ result: result, error:err });
});
}
exports.getPortfolio = function(req,res) {
backend.getPortfolio(req, function(err, result) {
global.GLB_PORTFOLIO = result;
res.json({ portfolio: result, error: err });
});
}
exports.postLogin = function(req,res) {
backend.findUserByEmail(req.body.email, function(err, result) {
console.log("API: SESSION IS: " + req.session.isLoggedIn);
if(err || result === null) {
req.session.isLoggedIn = false;
} else {
req.session.isLoggedIn = true;
}
req.session.save();
res.json({ user: result, error: err });
});
}
The session variable is always undefined even after the save(). What am I doing wrong?

unable to start app in node.js getting the following error

Welcome to Git (version 1.9.5-preview20150319)
Run 'git help git' to display the help index.
Run 'git help ' to display help for specific commands.
$ npm start
nodeauth#1.0.0 start C:\Users*****\Desktop\nodeauth
node ./bin/www
C:\Users***\Desktop\nodeauth\node_modules\express\lib\application.js:206
throw new TypeError('app.use() requires middleware functions');
^
TypeError: app.use() requires middleware functions
at EventEmitter.use >>...>
//app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator = require('express-validator');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer = require('multer');
var flash = require('connect-flash');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var db = mongoose.connection;
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// Handle File Uploads
app.use(multer({dest:'./uploads'}));
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
//Handle Express Sessions
app.use(session({
secret:'secret',
saveUninitialized: true,
resave:true
}));
// Passport
app.use(passport.initialize());
app.use(passport.session());
// Validator
app.use(expressValidator({
errorFormatter: function(param, msg, value) {
var namespace = param.split('.')
, root = namespace.shift()
, formParam = root;
while(namespace.length) {
formParam += '[' + namespace.shift() + ']';
}
return {
param : formParam,
msg : msg,
value : value
};
}
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(flash());
app.use(function (req, res, next) {
res.locals.messages = require('express-messages')(req, res);
next();
});
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
You need to use app.use(multer({dest:'./uploads/'})) in the form of one of these:
app.use(multer({dest:'./uploads/'}).single(...));
app.use(multer({dest:'./uploads/'}).array(...));
app.use(multer({dest:'./uploads/'}).fields(...));
ie:
app.use(multer({dest:'./uploads/'}).single('photo'));
And be sure to have something like:
<form action="/postPhotos" enctype="multipart/form-data">
<input type="file" name="photo">
<input type="submit" value="Upload photo">
</form>
In your html.

Resources