Why i cant save and check session in nodejs? - javascript

I am learning nodejs and I want to check if user is logged in by checking session.login value but when session.login is created and then user is redirected to main page, session.login is again undefined.
emit 'logged' is just redirecting user to the dashboard but dashboard checks if session.login exists, it shows undefined and user is redirected again to the login page.
var app = require('express')(); //load and initialize express
var http = require('http').Server(app); //create http server
var io = require('socket.io')(http); //add socket to http server
var path = require('path') //initialize path module
var port = 3000; //define port
var mysql = require('mysql'); //load mysql module
var session = require('express-session'); //sessions module
var login; //login
var md5 = require('md5');
//connecting to the database
var con = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'chat'
});
con.connect((error) => {
if(error) console.log('Error with database connection.');
else console.log("Connected to the database!");
});
//define default path
app.use(require('express').static(path.join(__dirname, 'public')));
//session
app.use(session({
secret: 'randomstringhere',
resave: false,
saveUninitialized: false,
cookie: {
}
}));
app.get('/', (req, res) => {
if (req.session.login) {
res.redirect('/dashboard');
}
else {
res.sendFile(__dirname + '/views/login.html');
console.log("Someone has joined to the server.");
io.on('connection', (socket) => {
//login
socket.on('login', (login, password) => {
con.query('SELECT * FROM users WHERE login="'+login+'" AND password="'+md5(password)+'"', (error, results, fields) => {
if (error) console.log('Error');
if (results[0]) {
req.session.login = results[0].login;
console.log(req.session.login+": Succesfully logged.");
req.session.save();
socket.emit('logged', 'You will be logged, please wait!');//redirects to /dashboard
}
else {
socket.emit('cant login', 'Login or password incorrect!');
console.log("Incorrect login or password.");
}
});
});
});
}
});
app.get('/dashboard', (req, res) => {
if (req.session.login) {
res.sendFile(__dirname + '/views/index.html');
console.log(req.session.login + " has joined to the server.");
io.on('connection', (socket) => {
socket.on('message', (msg) => {
io.emit('message', req.session.login + ": " + msg);
console.log(req.session.login + ": " + msg);
});
//logout
socket.on('logout', () => {
socket.emit('logging out');
req.session.destroy();
});
});
}
else {
res.redirect('/');
}
});

Related

node.js Express - how to do login sessions?

I'm working doing a login function with node.js Express and are having trouble with sending the session data so my app.js routes know the user is allowed to enter the various sites.
My first thought was to send it when i approve of the login information and redirect to the frontpage in my Auth.js but i can't figure out how to send it so that my frontpage route can see it and handle it with my checkAuth function.
The other idea i had was using a couple of "set/get" routes as shown in my users.js. But can't figure out how i would further implement that.
I don't know which way would be optimal for this sort of application.
This is the Auth.js which is responsible for the login:
const router = require('express').Router();
const User = require("../models/User.js");
const bcrypt = require('bcrypt');
const saltRounds = 12;
router.post('/login', (req, res) => {
// get request from body
const { username, password } = req.body;
//console.log(req.body);
// ask if this is a username with a password
if (username && password) {
// goes through db to see if username exists
User.query().select('username').where('username', username).then(foundUsername => {
try {
if (foundUsername[0].username == username) {
console.log(foundUsername[0].username);
User.query().select("password").where('username', foundUsername[0].username).then(foundPassword => {
console.log(foundPassword[0].password);
bcrypt.compare(password, foundPassword[0].password).then(result => {
console.log(result)
if (result == true) {
// this is where i want to set the req.session.user_id = true;
// and send it to my /frontpage
return res.redirect("/frontpage");
} else {
return res.status(400).send({ response: "wrong username or password" });
};
});
});
} else {
return res.status(400).send({ response: "wrong username or password" });
};
} catch (error) {
return res.status(400).send({ response: "wrong username or password" });
};
});
};
});
module.exports = router;
This is my app.js which checks the incoming request for req.session.user_id
const express = require('express');
const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.static('public'));
app.use(express.json());
// You need to copy the config.template.json file and fill out your own secret
const session = require('express-session');
const config = require('./config/config.json');
app.use(session({
secret: config.sessionSecret,
resave: false,
saveUninitialized: true
}));
const rateLimit = require('express-rate-limit');
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
app.use(limiter);
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 8 // limit each IP to 8 requests per windowMs
});
app.use('/signup', authLimiter);
app.use('/login', authLimiter);
/* Setup Knex with Objection */
const { Model } = require('objection');
const Knex = require('knex');
const knexfile = require('./knexfile.js');
const knex = Knex(knexfile.development);
Model.knex(knex);
app.get("/", (req, res) => {
return res.sendFile(__dirname + "/public/login.html");
});
function checkAuth(req, res, next) {
if (!req.session.user_id) {
res.send('You are not authorized to view this page');
} else {
next();
}
}
app.get("/frontpage", checkAuth, (req, res) => {
console.log(req.body);
return res.sendFile(__dirname + "/public/frontpage.html");
});
const authRoute = require('./routes/auth.js');
const usersRoute = require('./routes/users.js');
app.use(authRoute);
app.use(usersRoute);
const PORT = 3000;
app.listen(PORT, (error) => {
if (error) {
console.log(error);
}
console.log("Server is running on the port", PORT);
})
});
This is my users.js. This is another way i thought of getting and setting my session value:
router.get('/setsessionvalue', (req, res) => {
req.session.user_id = true;
return res.send({ response: "OK" });
});
router.get('/getsessionvalue', (req, res) => {
return res.send({ response: req.session.user_id });
});

nodejs expressjs ERR_TOO_MANY_REDIRECTS

I have error with "ERR_TOO_MANY_REDIRECTS" in browser.
On linux server it looks like:
Error: Can't set headers after they are sent.
This is my app.js:
const express = require('express');
const bodyParser = require('body-parser');
const mysql = require('mysql');
const path = require('path');
const app = express();
const session = require('express-session');
const {getHomePage} = require('./routes/index');
const {getmain, addUserPage, addUser, deleteUser, editUser, editUserPage, addTemplates, getHistory} = require('./routes/user');
const port = 5000;
var auth = function(req, res, next) {
if (req.session && req.session.user === "amy" && req.session.admin)
return next();
else
return res.sendStatus(401);
};
// create connection to database
// the mysql.createConnection function takes in a configuration object which contains host, user, password and the database name.
const db = mysql.createConnection ({
host: 'localhost',
user: '*****',
password: '*****',
database: '*****',
charset : 'utf8mb4'
});
// connect to database
db.connect((err) => {
if (err) {
throw err;
}
console.log('Connected to database');
});
global.db = db;
// configure middleware
app.set('port', process.env.port || port); // set express to use this port
app.set('views', __dirname + '/views'); // set express to look in this folder to render our view
app.set('view engine', 'ejs'); // configure template engine
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); // parse form data client
app.use(express.static(path.join(__dirname, 'public'))); // configure express to use public folder
app.locals.moment = require('moment');
app.use(session({
secret: '2C44-4D44-WppQ38S',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 1800000}
}));
// routes for the app
app.get('/', getHomePage);
app.get('/main', auth, getmain);
app.get('/add', auth, addUserPage);
app.get('/edit/:id', auth, editUserPage);
app.get('/delete/:id', auth, deleteUser);
app.get('/addtemp/:login', auth, addTemplates);
app.get('/history', auth, getHistory)
app.post('/add', auth, addUser);
app.post('/edit/:id', auth, editUser);
app.post('/addtemp/:login', auth, addTemplates);
// Login endpoint
app.get('/login', function (req, res) {
if (!req.query.username || !req.query.password) {
res.send('login failed');
} else if(req.query.username === "amy" || req.query.password === "amy") {
req.session.user = "amy";
req.session.admin = true;
res.redirect('/main');
}
});
// Logout endpoint
app.get('/logout', function (req, res) {
req.session.destroy();
res.redirect("/");
});
// set the app to listen on the port
app.listen(port, () => {
console.log(`Server running on port: ${port}`);
});
I know I have some problems in
app.get('login...
Theres everything ok with success login using correct username and password but when I use incorrect nothing happend.
This is my module getmain (after correct login):
getmain: (req, res) => {
let query = "SELECT * FROM `users` ORDER BY id ASC";
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/main');
}
res.render('main.ejs', {
title: "blablabla"
,users: result
});
});
},
And this is index.js:
module.exports = {
getHomePage: (req, res) => {
let query = "SELECT * FROM `users` ORDER BY id ASC";
// execute query
db.query(query, (err, result) => {
if (err) {
res.redirect('/');
}
res.render('index.ejs', {
title: "blablabla"
,users: result
});
});
},
};
I read that's all because by looping but I can not figure it out.
I will be grateful for directing me to the source of the problem.

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());

How do I send a variable from nodejs to all the connected clients?

I'm currently working on a project for school, my idea is to create a roulette game with a chat, so I'm working with nodejs and socket IO my question is how do I send the value of the random number generated in the server to all my clients and then execute the javascript function to spin the roulette?
app.js
var express = require('express');
var path = require('path');
var debug = require('debug')('workspace:server');
var http = require('http');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var jquery = require('jquery');
var session = require('express-session')({
secret: "secret",
key: 'secret.sid',
resave: true,
saveUninitialized: true,
cookie: {
maxAge: 3600000
}
});
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'password',
database : 'database'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
var openid = require('openid');
var app = express();
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
var server = http.Server(app);
var socket = require('socket.io')(server);
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string' ? 'Pipe ' + port : 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string' ? 'pipe ' + addr : 'port ' + addr.port;
console.log('Listening on ' + bind);
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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);
function createRelyingParty(req) {
var baseUrl = req.protocol + "://" + req.get("host");
return new openid.RelyingParty(baseUrl + "/verify", baseUrl, true, false, []);
}
// for every request lets make the user session available to the templates
app.use(function(req, res, next) {
res.locals.user = req.session.user;
next();
});
app.get("/", function(req, res) {
res.render('index', {
title: 'Roulette',
session: (typeof req.session.user !== 'undefined') ? req.session.user : ''
});
});
socket.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
socket.on('connection', function(socket){
socket.on('chat message', function(msg){
socket.emit('chat message', msg);
console.log('message: ' + msg);
});
});
var r = require('./SpinGen');
// 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: {}
});
});
SpinGen.js (js to generate and send the number to the client)
var express = require('express');
var http = require('http');
var app = express();
var server = http.Server(app);
var socket = require('socket.io')(server);
setInterval(function() {
var rndNum = Math.floor((Math.random() * 34) + 0);
var winningNum = rndNum;
console.log(winningNum);
socket.emit('roulette', winningNum);
},10000);
client-side.js
var socket = io('http://localhost:3000');
$('form').submit(function(){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
socket.on('roulette', function(spin){
spinTo(spin);
});
socket.on('error', function(evData){
console.error('Connection Error:',evData);
});
You would send (emit) the random number to all connected clients - it would look something like this:
io.emit('random number', randomNumber);
You would then listen for the event on the client side like so:
socket.on('random number', function(num){
// num contains the random number
// spin the wheel to the random number
spinTo(num)
});
Try using io.sockets.emit instead of socket.emit. That will emit to all connected clients

can't send headers after they send

ı have tis error
:can't send headers after they send.ı get from url and browser redireck url but ı dont get content from home.html
ı have tis error
:can't send headers after they send.ı get from url and browser redireck url but ı dont get content from home.html
var path = require('path');
var express = require('express');
var app = express();
var server = app.listen(80);
var io = require('socket.io').listen(server);
var session = require('express-session'); //session işlemleri
mongodb = require('mongodb'); //veritabanı işlemleri
var mongoclient = mongodb.MongoClient;
var bodyparser = require('body-parser'); //form submit için
var multer = require('multer'); //dosya yükleme
app.use("/style", express.static(__dirname + "/style"));
app.use("/images", express.static(__dirname + "/images"));
app.use("/scripts", express.static(__dirname + "/scripts"));
app.use(bodyparser.urlencoded({
'extended': 'true'
}));
app.use(bodyparser.json());
app.use(session({
'secret': 'hhhhh',
resave: true,
saveUninitialized: true
}));
//register
app.get("/register", function(req, res) {
if (req.session.userid) {
res.redirect("/home")
};
res.sendFile(__dirname + "/register.html");
});
//register
//register post
app.post("/register", function(req, res) {
var reguserame = req.body['username'].trim();
var regpassword = req.body['password'].trim();
mongoclient.connect("mongodb://127.0.0.1/deneme", function(err, db) {
if (err) {
res.sendStatus("veritabanı ile ilgili bir hatta algılandı");
} else {
var users = db.collection("users");
users.count({
"name": reguserame
}, function(err, count) {
if (count == 1) {
res.send("bu kullanıcı adı daha önce alınmış");
res.end();
} else {
var kayit = db.collection("users").insert({
"name": reguserame,
"pass": regpassword
});
if (kayit) {
res.send('kayıt basarılı giriş yap');
} else {
res.send("kayit basarısız");
}
res.end();
}
});
}
});
});
//register post
//logout
app.get("/logout", function(req, res) {
req.session.destroy();
res.redirect("/login");
});
//logout
app.get("/login", function(req, res) {
if (req.session.userid) {
res.redirect("/home");
}
res.sendFile(__dirname + "/login.html");
});
//login kontrol
app.post("/login", function(req, res) {
var username = req.body['username'].trim();
var password = req.body['password'].trim();
mongoclient.connect("mongodb://127.0.0.1:27017/deneme", function(err, db) {
db.collection("users").find({
"name": username,
"pass": password
}).toArray(function(err, result) {
var sayisi = result.length;
///uye kontrol
if (sayisi == 1) {
res.status(200);
req.session.userid = result[0]._id;
res.redirect("/home");
} else {
res.sendStatus("hatalı parola");
res.end();
}
db.close();
//uye kontrol
});
});
});
//home sayfası
app.get("/home", function(req, res) {
if (req.session.userid) {
res.sendFile(path.join(__dirname + "/home.html"));
res.end();
} else {
res.send("henüz giriş yapılmamış");
res.end();
}
});
//login kontrol
app.use(function(req, res) {
res.status("404");
res.write("<div style='height:100%; top:0px; left:0px; position:absolute; text-align: center; vertical-align: center; width:100%; background: #eee;'><h1 style='border:1px solid #999; color:#f63; margin-top:20%;'>sayfa yok</h1></div>");
res.end();
});
res.redicert("/home") this row by ı get error
> Blockquote
///please
In this part of the code, it is sending the status 200 and the redirect wants to send status 302:
res.status(200);
req.session.userid=result[0]._id;
res.redirect("/home");
It can't send the status 302 because it already sent the status 200. Try removing the res.status(200).
There are other trouble spots like this:
if(req.session.userid){ res.redirect("/home");}
res.sendFile(__dirname+"/login.html");
It either needs a return after the redirect() or the sendFile() part needs to go in an else block. The redirect() is sending 302 and then the sendFile() executes and wants to send a 200.
Not sure if this is all of your problemms, but you have a spelling mistake
// res.redicert("/home") -->
res.redirect("/home")

Categories