Get "undefined" for req.session in nodejs - node.js

Noob here, and I tried to have a session to do the login attempt count in nodejs, but it seem the session is not declared in route as it just show undefined when i console.log it.
Below is my code :
Server.js
var express = require('express');
var session = require('express-session');
var cors = require('cors');
var bodyParser = require("body-parser");
var app = express();
var port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(cors());
app.use(session({ resave: false, saveUninitialized: true, secret: 'onemonkey', cookie: { secure: false }}));
app.use(bodyParser.urlencoded({
extended: false
}));
var Users = require('./Routes/Users');
app.use('/users',Users);
app.listen(port,function(){
console.log("Server is running on port: "+port);
});
in users.js
var express = require('express');
var users = express.Router();
var database = require('../Database/database');
var cors = require('cors')
var jwt = require('jsonwebtoken');
const bcrypt = require('bcrypt');
//var request = require('request');
var token;
users.use(cors());
users.post('/login', function(req, res) {
var appData = {};
var email = req.body.email;
var password = req.body.password;
let someRows, otherRows;
let token;
var databaseQuery = new database.DatabaseQuery();
databaseQuery.beginTransaction()
.then (() => {
return databaseQuery.query('SELECT * FROM users WHERE email = ? AND status = ?', [email, 'active'])
})
.then( rows => {
someRows = rows;
if (someRows.length > 0) {
bcrypt.compare(password, someRows[0].password).then(function(ret) {
// res == true
if(ret){
//when validate successfully
}else{
console.log(req.session[email]);
req.session[email] = req.session[email] + 1;
req.session.save();
console.log('--------login-----');
console.log(req.session[email]);
if(req.session[email] == 3){
databaseQuery.query('update users set status=? where email=?',['block',email])
.then( rows => {
otherRows = rows;
var user_status = {
contact_id : someRows.insertId,
remark : "3 times login attempt fail",
status : "block",
edit_by : "SYSTEM"
}
return databaseQuery.query( 'INSERT INTO user_status_detail SET ?', [user_status] );
}).then ( rows =>{
appData.error = 1;
appData["data"] = "Email account blocked";
req.session[email] = null;
req.session.save();
res.status(200).json(appData);
return databaseQuery.commit();
}, err => {
return databaseQuery.close.then( () => { throw err; } )
})
}else{
//record not match
}
}
});
}else {
//account not exist
}
})
.catch( err => {
//err handling
} )
});
module.exports = users;
I tried to store the count in req.session[email] in user.js, and block the email once the count equal to 3. However, it not storing the count and showing undefined every time i tried to login which wrong password.
Highly appreciate your advise on it.

add these lines to the top :
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

Related

Express-session not saving

I'm now to nodejs and have been trying to find a solution for this problem but all of the solutions haven't been working.
req.session.user is always return undefined. it sets if I set it within a function but as soon as it exits the function it becomes undefined again. It works find from app.get/post but not when using a router
server.js
const express = require('express');
const session = require('express-session');
const cors = require('cors');
const bodyParser = require('body-parser');
require('dotenv').config();
const app = express();
const dbo = require('./database');
app.use(cors());
const sessionMiddleware = session({
secret: "ei_13495781kam",
resave: false,
saveUninitialized: true,
cookie: {
secure: false,
maxAge: 6000
}
});
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(sessionMiddleware);
const userRoute = require('./routes/user-route');
app.use('/user', sessionMiddleware, userRoute);
app.route('/').get((req, res) => {
req.session.user = {
loggedIn: false,
id: ''
};
});
const port = process.env.PORT || 5000;
app.listen(port, () => {
console.log('App is running on port ' + port);
dbo.connectToServer((err) => {
console.log(err);
})
})
user-route.js
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const dbo = require('../database');
const session = require('express-session')
const {response} = require("express");
const objectId = require('mongodb').ObjectId;
router.route('/register').post((req, res) => {
console.log('Hello World');
if(typeof req.session.user === 'undefined' || !req.session.user.loggedIn) {
let db_connection = dbo.getDb();
bcrypt.hash(req.body.password, 10)
.then((hashedPswd) => {
req.body.password = hashedPswd
db_connection.collection('users').insertOne(req.body, (err, response) => {
if(err) throw err;
req.session.user = {
loggedIn: true,
id: response.insertedId
};
res.json({loggedIn: true});
})
})
}
})
router.route('/session').get((req, res) => {
if(typeof req.session.user === 'undefined') {
req.session.user = {
loggedIn: false,
id: ''
}
res.json({sessionValid: false})
} else {
res.json({sessionValid: req.session.user.loggedIn})
}
});
router.route('/login').post((req, res) => {
let db_connection = dbo.getDb();
const searchQuery = {
username: req.body.username
};
db_connection.collection('users').findOne(searchQuery, (err, response) => {
if(err) throw err;
if(response) {
bcrypt.compare(req.body.password, response.password, (err, pResponse) => {
if(pResponse) {
req.session.user = {
loggedIn: true,
id: objectId(response._id),
}
req.session.save();
console.log("1 " + JSON.stringify(req.session.user));
res.json({loggedIn: true});
} else {
res.json({loggedIn: false});
}
})
}
})
console.log("2 " + req.session.user);
})
module.exports = router;
I've tried setting it if it's undefined also tried saving it manually or passing the middle ware into the app.use(/route/)
maxAge: 6000
Your cookie has a maxAge of 6 seconds... are you sure you made a request within six seconds of the server being started and still produced an error?

How to get data from another route (POST method)?

I have multiple routes setup. I want to get specific data from another route. That data is coming from a post method.
My server.js look like this:
var mysql = require('mysql')
var morgan = require('morgan')
var cors = require('cors')
var bodyParser = require('body-parser')
var http = require('http')
var dateFormat = require('dateformat')
const port = process.env.PORT || 3000;
//middleware
var app = express()
app.use(cors())
app.use(morgan('dev'))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}))
var now = new Date()
//routes
var user_details = require('./routes/users')
var user_orders = require('./routes/order')
//Use routes
app.use('/', user_details)
app.use('/', user_orders)
//Launch Server
app.listen(port, () => {
console.log('Server start at port: ' + port)
})
My routes/users.js :
var router = express.Router()
var db = require('../dbConfig')
var randomstring = require("randomstring");
var moment = require('moment')
router.post('/list', (req, res) => {
var appendRandomString = randomstring.generate({
length: 10,
capitalization: 'uppercase',
readable: true
})
var id = 'PEPPR_' + appendRandomString
var email = req.body.email
var listItems = req.body.listItems
var listTitle = req.body.listTitle
var date = moment().format("Do MMMM YYYY");
var time = moment().format("LT");
const INSERT_USER_LISTS = `INSERT INTO user_lists (id,date,time,user_email,list_title,list_items) VALUES('${id}','${date}','${time}','${email}','${listTitle}','${listItems}')`
db.query(INSERT_USER_LISTS, (err, success) => {
if (err) {
return res.send(err)
} else {
console.log('list added')
res.send('list added')
}
})
})
module.exports = router
And my routes/order.js
var router = express.Router()
var db = require('../dbConfig')
var randomstring = require("randomstring");
var moment = require('moment')
var user_details = require('./users')
router.post('/sendOrder', (req, res) => {
var email = req.body.email
var status = 'Order Confirmed'
var date = moment().format("Do MMMM YYYY");
var time = moment().format("LT");
var appendRandomString = randomstring.generate({
length: 10,
capitalization: 'uppercase',
readable: true
})
var id = 'PEPPR_ORDER_' + appendRandomString
var list_items = ''
var list_title = ''
var data = {
id: id,
email: email,
list_items: list_items,
list_title: list_title,
date: date,
time: time,
status: status
}
const CREATE_ORDER = `INSERT INTO user_orders SET ?`
db.query(CREATE_ORDER, data, (err, success) => {
if (err) {
return res.send(err)
} else {
res.send('oc')
}
})
})
module.exports = router
I want the list_items and list_title in my order.js from users.js , this two data is coming from a POST method as you can see in users.js
If I understood you correctly you want to use request body which comes to /users in another route /orders.
You are saving user data list_title and list_item in users table. So all you need to access the data from /orders route is make an additional query to db where you will select users by id\email.
Not sure which db ORM you use but in general cases your code may look like this:
router.post('/sendOrder', async (req, res) => {
const { email } = req.body;
// declare other fields
const user = await db.query(
`SELECT * FROM users WHERE email LIKE '%${email}%'`,
(err, success) => {
if (err) {
return res.send(err);
} else {
res.send('ok');
}
}
);
// declare `data` object with user.list_title, user.list_item
const CREATE_ORDER = `INSERT INTO user_orders SET ?`;
db.query(CREATE_ORDER, data, (err, success) => {
if (err) {
return res.send(err);
} else {
res.send('ok');
}
});
});

Why Am getting the request-body content as empty?

when i submit the register form ,the data from that register page should be posted on the console.. and I try to print that result using "req.body.Username" , it says undefined and when i view the req in console. The body seems to be an empty set like " {} ", how to post my form details in body to view in console and how to get rid of that "undefined" error?
app.js
const express = require('express');
const flash = require('connect-flash');
const path = require('path');
const request = require('request')
const expressValidator = require('express-validator');
const authRoutes = require('./routes/auth-routes');
const session = require('express-session');
const passport = require('passport');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const db = require('./config/db');
const registerc = require('./registerc');
const loginc = require('./loginc');
const registerRoute = require('./routes/register');
const fs = require('fs');
// const request = require('./modules/module1')
const app = express();
// set view engine
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
// set up routes
app.use('/auth', authRoutes);
app.use('', registerRoute);
// create home route
app.get('/', (req, res) => {
res.render('home');
res.render('mycourses', {
final1: final1
});
res.render('recent', {
final2: final2
});
});
// fetching course details
request(options, function (error, response, result) {
if (error) throw new Error(error);
// console.log(result);
// final1 = JSON.stringify(result)
final1 = JSON.parse(result);
// console.log(final1);
});
// fetching User recent Activity
request(options, function (error, response, result) {
if (error) throw new Error(error);
// console.log(result);
final2 = JSON.parse(result);
// console.log(final2);
// console.log(final2.length)
});
app.use(session(
{
secret : 'secret',
saveUninitialised : true,
resave : true
}
));
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
};
}
}));
app.use(flash());
// app.use(function(res,req,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.post('/api/register',registerc.register);
// app.post('/api/login', loginc.login);
app.listen(3000, () => {
console.log('app now listening for requests on port 3000');
});
In your app.js, update the register auth from
app.use('', registerRoute);
To
app.use('/soemRoute', registerRoute);

Cannot read property 'end' of undefined - MySQL , NodeJS

I want to show you my error with NodeJS and MySQL.
Error is at line 45 of app.js
Cannot read property 'end' of undefined
at ServerResponse.<anonymous> (/usr/my_server/app.js:45:24)
It happen when I call a request from 'addReferFriend.js' file.
I link here the two files that I am using.
app.js:
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mysql= require('mysql2');
var http = require('http');
var app = express();
var addReferFriend = require('./addReferFriend');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(async function(req, res, next) {
try {
if( req.dbConnection ) {
// ensure that req.dbConnection was not set already by another middleware
throw new Error('req.dbConnection was already set')
}
let connection = mysql.createConnection({
host: 'xx',
user: 'xx',
password: 'xx',
database: 'xx'
});
res.on("finish", function() {
// end the connection after the resonponse was send
req.dbConnection.end()
});
// wait for the connection and assign it to the request
req.dbConnection = await connection.connect();
next();
} catch(err) {
next(err);
}
});
app.use('/api/addReferFriend', addReferFriend);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
var server = http.createServer(app);
server.listen(3955);
addReferFriend.js:
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.post('/', function(req, res, next) {
var uid = req.body.uid;
var friendReferCode = req.body.friendReferCode;
var sqlCheckIfExist = "SELECT my_refer FROM hub_user WHERE my_refer = '" + friendReferCode + "'";
var sqlCodeCheckSameAsMine = "SELECT my_refer FROM hub_user WHERE uid = '" + uid + "'";
function checkIfUserCodeExist() {
return req.dbConnection.query(sqlCheckIfExist)
.then(([rows, fields]) => {
if (rows == 0) {
console.log("Non esiste!")
return res.send(JSON.stringify({
"status": 500,
"response": "codeNotExist"
}));
}
console.log("Esiste!")
return checkIfCodeIsSameAsMine(connection)
})
}
function checkIfCodeIsSameAsMine() {
return req.dbConnection.query(sqlCodeCheckSameAsMine)
.then(([rows, fields]) => {
if (rows == friendReferCode) {
console.log("Codice uguale!")
return res.send(JSON.stringify({
"status": 500,
"response": "sameCodeAsMine"
}));
}
console.log("Codice non uguale!")
})
}
checkIfUserCodeExist()
.catch(next)
});
module.exports = router;
I have no idea how fix this type of problem. It happen when I call the checkIfUserCodeExist() and it doesn't join into the function and it gives directly the error. I can't print any of console.log because it break.
Hope that somebody can help me with this issue.
Thanks in advance for the help,
Michele.
it seems to be req.dbConnection.end() the problem... the object dbConnection is undefined.
is it possible that the connection is closed first for some reason? so the point to closing connection is not correct?

App still let's user type in any username and password and accepts it

In my app I decided to add a bit of security by trying to restrict the user to enter the right password and name but the user still can enter the any name and password and get access to the files .
Screenshot of the user getting access to the files without name and password
'use strict'
const express = require('express')
const fs = require('fs')
const https =require('https')
const path = require('path')
const app = express()
const directoryToServe = 'client'
const port = 3443
var _ = require("lodash");
var bodyParser = require("body-parser");
var jwt = require('jsonwebtoken');
var passport = require("passport");
var passportJWT = require("passport-jwt");
var ExtractJwt = passportJWT.ExtractJwt;
var JwtStrategy = passportJWT.Strategy;
var users = [
{
id: 1,
name: 'jonathanmh',
password: '%2yx4'
},
{
id: 2,
name: 'test',
password: 'test'
}
];
var jwtOptions = {}
jwtOptions.jwtFromRequest = ExtractJwt.fromAuthHeader();
jwtOptions.secretOrKey = 'tasmanianDevil';
var strategy = new JwtStrategy(jwtOptions, function(jwt_payload, next) {
console.log('payload received', jwt_payload);
// usually this would be a database call:
var user = users[_.findIndex(users, {id: jwt_payload.id})];
if (user) {
next(null, user);
} else {
next(null, false);
}
});
passport.use(strategy);
//var app = express();
app.use(passport.initialize());
// parse application/x-www-form-urlencoded
// for easier testing with Postman or plain HTML forms
app.use(bodyParser.urlencoded({
extended: true
}));
// parse application/json
app.use(bodyParser.json())
app.use('/',express.static(path.join(__dirname,'..',directoryToServe)))
const httpsOptions = {
cert: fs.readFileSync(path.join(__dirname,'ssl','server.crt')),
key: fs.readFileSync(path.join(__dirname,'ssl','server.key'))
}
https.createServer(httpsOptions, app)
.listen(port, function()
{
console.log(`Serving the ${directoryToServe}/directory at https://localhost:${port}`)})
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.get('/', function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("We're up and running!!!");
});
var plan = require('./api/planner/index');
//app.get('/api/planner',plan.index);
app.get("/api/planner",plan.index, function(req, res) {
if(req.body.name && req.body.password){
var name = req.body.name;
var password = req.body.password;
}
// usually this would be a database call:
var user = users[_.findIndex(users, {name: name})];
if( ! user ){
res.status(401).json({message:"no such user found"});
}
if(user.password === req.body.password) {
// from now on we'll identify the user by the id and the id is the only personalized value that goes into our token
var payload = {id: user.id};
var token = jwt.sign(payload, jwtOptions.secretOrKey);
res.json({message: "ok", token: token});
} else {
res.status(401).json({message:"passwords did not match"});
}
});
app.post('/api/planner',plan.create);
app.put('/api/planner/:id',plan.update);
app.delete('/api/planner/:id',plan.delete);
console.log("Server running at http://127.0.0.1:8000/");
//

Resources