Hello I'm just new to Node.js and currently working on session login.
Why can't I set session inside my query function?
Why do I need req.session.save() to save it, but after redirecting to some page session its still not totally set and the page needs to refresh to show session.
Here is my function in setting session
client.query(
"Select id FROM users Where username = '" + req.body.username + "' AND password = '" + req.body.password + "'",
function(err, result) {
if (err) {
return console.error('error running query', err);
} else {
done();
req.session.user_id = result.rows;
req.session.save();
res.redirect('/wall');
}
});
You might want to simplify your example and clarify what libraries you are using. I am assuming you are using express and express-session. I set up a simple example where when you go to to /login?username=yourname page it redirects you to a different page where it shows your name.
var app = require('express')();
var http = require('http').Server(app);
var session = require('express-session');
var mysql = require('mysql')
app.use(session({secret: 'super secret'}));
var client = mysql.createConnection({
host: "My",
user: "private",
password: "configuration",
database: "my_db"
});
app.get('/login', function(req, res, next) {
var sessionData = req.session;
client.query('SELECT * from users where username = ?', [req.query.username], function(err, rows) {
if(err) throw err;
if (rows.length) {
var user = rows[0]
req.session.username = user.username;
req.session.user_id = user.id
res.redirect('/signed_in');
} else {
res.send("user not found")
}
})
})
app.get('/signed_in', function(req, res){
res.send(req.session.user_id + "," + req.session.username);
});
http.listen(3000);
Quentin is right you should look out for sql injections. in the case of node you typically do something like this, depending on what sql library you are using.
client.query(
"Select id FROM users Where username = ? AND password = ?", [req.body.username, req.body.password],
function(err, result) {
// Your code
}
As for why you have to refresh the page after you reload it my guess is something related to done function since i don't know what it is doing in your code. I have no idea why you need to call save, it is not necessary in my example.
Related
i am getting started with node.js and now I got stuck.
var mysql = require('mysql');
var dbconfig = require('../config/database');
var connection = mysql.createConnection(dbconfig.connection);
connection.query('USE ' + dbconfig.database);
app.get('/createarticle', isLoggedIn, function(req, res){
res.render('createarticle.ejs', {
user:req.user
});
});
app.post('/createarticle' , (req, res ) => {
let sql = 'INSERT INTO news SET ?'
let post = {
// author: req.user.username,
content : req.body.content,
title: req.body.title
}
connection.query(sql, post, (err, res) => {
if(err) throw err;
console.log('success');
console.log(res);
});
});
If I use req.user.username I get this error message Cannot read property 'username' of undefined.
I also tried user.username and req.user.
In my main JS I have this function that shoud always give the user if logged in.
app.get('*', function(req, res, next) {
res.locals.user = req.user || null;
next();
});
In addition to this I want to include two redirects but I don't know where to put it.
successRedirect: '/',
failureRedirect: '/createarticle',
I appreciate every answer and pacience with me. :)
I can't comment so I have to post an answer:
What does your request object look like:
app.get('/createarticle', isLoggedIn, function(req, res){
console.log('request',req)
res.render('createarticle.ejs', {
user:req.user
});
});
If you're not populating the request object in your 'GET' from your front end,
you won't have the user you are asking for.
You may want to do some handling in the front to make sure that you only send populated request objects.
I am still new to nodejs and Javascript, I am sorry if my question appear to be very simple but I am struggling a lot and I can't seem to find an answer on the net.
What I want to do is basically calling a script (sqlRequest.js) and send an integer while calling it. This script will send an sql request to my database and will return the result (an object) to the original file.
Here are the codes:
router.post('/request', function(req, res, next){
var id = req.body.id;
var essai = require('./sqlRequest.js');
console.log("INDEX: "+essai.sendSQL(id)); });
And now the sqlRequest.js code:
exports.sendSQL = function(id) {
var mysql= require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'bcombes',
password : 'bertrand1994',
database : 'totalkpi'
});
connection.connect();
var sql ="SELECT * FROM tra_ticket where id=?";
var insert=[id];
sql=mysql.format(sql, insert);
connection.query(sql, function(err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
return rows;
}
});};
On the console I can see that the console.log("INDEX: "+essai.sendSQL(id)); appears to be undefined and is displayed before the console.log(rows).
Is it possible that the server does not wait for the function to finish and display the variable anyway ?
Anyway thank you for taking the time to help.
Your logic to pass a variable between files is fine. The reason your seeing essai.sendSQL(id) return undefined is because connection.query(...) is called asynchronously and, as you've mentioned in your question, the console.log fires before the DB query completes.
To fix that issue you just need to refactor your code slightly:
var essai = require('./sqlRequest.js');
router.post('/request', function(req, res, next){
var id = req.body.id;
// send callback to sendSQL
essai.sendSQL(id, function(index) {
// this will only fire once the callback has been called
console.log("INDEX: " + index)
})
});
And then in sqlRequest.js:
exports.sendSQL = function (id, cb) {
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'bcombes',
password: 'bertrand1994',
database: 'totalkpi'
});
connection.connect();
var sql = "SELECT * FROM tra_ticket where id=?";
var insert = [id];
sql = mysql.format(sql, insert);
connection.query(sql, function (err, rows, fields) {
if (err) {
console.log('Error while performing Query.');
connection.end();
}
else {
connection.end();
console.log(rows);
// call the callback
cb(rows);
}
});
};
I am new to node JS. I am working on authenticating users against backend MYSQL.
Here is the code snippet of authentication
function Authenticate(username, password, fn) {
connection.connect();
var user;
connection.query('SELECT * from Users where username = ' +
connection.escape(username) + ' and password =' + connection.escape(password),
function(err, rows) {
user = rows[0].username;
});
if (!user) {
return fn(new Error('cannot find user'));
} else {
return fn(null, user);
}
connection.end();
}
This is my call back function.
app.post('/Login', function(req, res) {
Authenticate(req.body.username, req.body.password, function(err, user) {
if (user) {
req.session.regenerate(function() {
req.session.user = user;
req.session.success = 'Authenticated as ' + user;
res.redirect('Home');
});
} else {
req.session.error = 'Authentication failed, please check your username and password.';
res.redirect('Login');
}
});
})
I am getting an error, which i cannot get my head around.
TypeError: Cannot set property 'error' of undefined
at /...../.../node_modules/app.js:42:23
at Authenticate (/..../..../node_modules/app.js:82:11).
Please share your thoughts!
Takes the else out and see if any other req.session functions properly if not check if middleware is configured correctly for express validator
I am newby in node.js and I try to implement the simplest authorization in Express. I want to set req.session.userId to users id from database. I can get user id from database using simple form and post request, but I can't set req.session.userId . The most incomprehensible thing for me - why sometimes req.session is working and sometimes is not.
My code for explanation.
in app.js:
Configure segment:
app.use(express.session({secret: 'asdads', key: 'sid', cookie: { maxAge: 600000, httpOnly: false }}));
After that I handle POST request with:
app.post('/login', routes.authorize);
My routes.authorize:
exports.authorize = function(req, res){
if(req.body){
var login = req.body.login;
var password = req.body.password;
//gET USER FROM DATABASE
db.getUser(login, password, function(err, results){
//ensure that results is correct
console.log(results);
if(err){ res.send("User not found", 500); return;}
//PLACE WITH BUG :)
req.session.userId = results[0].id;
});
}
res.render('login', { title: 'Express!' });
}
I think I couldnt set req.session.userId in this place because I access here via POST. If I am right please help me to get access to req.session in this place.
Thanks in advance.
I think the problem is that you're immediately responding to the request before your db.getUser() completes. IIRC the Express session middleware saves session changes when the response is sent, so try something like this instead:
exports.authorize = function(req, res) {
if (!req.body)
return res.render('login', { title: 'Express!' });
var login = req.body.login;
var password = req.body.password;
db.getUser(login, password, function(err, results) {
if (err)
return res.send("User not found", 500);
req.session.userId = results[0].id;
res.render('login', { title: 'Express!' });
});
}
Recently I put my interest in node.js and learned a great about it and quickly move to the express framework. I've tried to connect my express application with mysql database and succeeded. Now I try to authenticate a simple login from connected with mysql database but I can't do that. Still don't get it why it is happening. Bellow here is the code I've used. A help will be greatly welcome.
var mysql = require('mysql');
connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'express_db',
password: '12345'
});
connection.connect();
exports.admin_login = function (req, res) {
res.render('./admin/login', {title: 'Please provide your credentials to login'});
};
exports.admin_home = function (req, res) {
var parse = req.body;
var name = parse.name;
var password = parse.password;
var sql = "select * from user where name = " + connection.escape(name) + " and password = " + connection.escape(password);
connection.query(sql, function (err, results) {
if (err) throw err;
if (name == results[0].name && password == results[0].password) {
req.session.regenerate(function () {
req.session.name = results[0].id;
res.render('./admin/home', {username: results[0].name});
});
}
});