Node + Redis not quite working - node.js

I have this initialisation code;
app.use(cookieParser);
var redis = require('redis');
var redisOptions = {}
redisOptions.client = redis.createClient(<removed>, 'pub-redis-12124.us-east-1-2.3.ec2.garantiadata.com');
app.use(session({
store: new RedisStore(redisOptions),
secret: 'keyboard cat',
resave: true,
saveUninitialized: true
}));
In my routing, I have this;
router.post('/login', function (req, res) {
var users = req.db.get('users');
users.findOne({email: req.body.email}, function (err, user) {
console.log(user);
if (req.body.password == user.password) {
req.session.id = user._id;
console.log("id:" );
res.send('successful login' + req.session.id);
} else {
// Make sure to log failed auth requests
var log = req.db.get('failed_auth');
var fail_info = {};
fail_info.email = req.body.email;
fail_info.ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
fail_info.timestamp = Date.now();
log.insert(fail_info, function(doc) {
res.send('bad creds');
});
}
});
});
However when I try to go through this code, I get this error;
TypeError: Cannot set property 'id' of undefined
My Redis server is one of the free hosted ones from redislabs. I'm not sure if I need to authenticate although I don't think that I do. Any tips on the way forward?
edit:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var bodyParser = require('body-parser')
var cookieParser = require('cookie-parser')();
var session=require('express-session');
var RedisStore = require('connect-redis')(session);
// New Code
var monk = require('monk');
var db = monk('localhost:27017/manpoints');
var routes = require('./routes/index');
var account = require('./routes/account')
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(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
Ignore the mess/unused stuff, I've been trying lots of different things trying to get this to work.

Related

req.isAuthenticated() returns false after successRedirect

I know that there are numerous posts already referring to the same problem, however, I couldn't find a solution for my case. Here is the relevant code for the issue :
users.js (route)
The login form is submits a POST request to this route.
var express = require('express');
var router = express.Router();
// Require controllers
var usersController = require('../../controllers/usersController');
/* POST login */
router.post('/login', usersController.loginAccount);
module.exports = router;
usersController.js
The passport authentication is handled here.
req.isAuthenticated() returns false here as well. However, successRedirect is executed, which should mean that the user was successfully authenticated.
'use strict';
var bodyParser = require('body-parser');
var mysql = require('mysql');
var bcrypt = require('bcryptjs');
var Client = require('../models/Client');
var passport = require('passport');
var Sequelize = require('sequelize');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
/* POST - Login */
module.exports.loginAccount = function (req, res, next) {
passport.authenticate('local', {
successRedirect: '../dashboard',
failureRedirect: '/users/login',
failureFlash: true
}) (req, res, next);
console.log("Exactly after authentication: " + req.isAuthenticated());
}
index.js (route)
Here, ensureAuthenticated always returns false
var express = require('express');
var router = express.Router();
// Require controllers
var indexController = require('../../controllers/indexController');
/* GET dashboard page */
router.get('/dashboard', ensureAuthenticated, indexController.dashboardPage);
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated())
{console.log("AUTHENTICATED"); return next();}
else{
console.log("NOT AUTHENTICATED");
req.flash('error_msg', 'Please log in to view this resource');
res.redirect('/users/login');
}
}
module.exports = router;
indexController.js
When submitting the login form, this code doesn't get executed, because ensureAuthenticated() is false.
'use strict';
var bodyParser = require('body-parser');
var mysql = require('mysql');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
/* GET - Dashboard page */
module.exports.dashboardPage = function(req, res) {
// console.log(req.user);
// console.log(req.isAuthenticated());
res.render('dashboard');
};
passport.js
const LocalStrategy = require('passport-local').Strategy;
const Sequelize = require('sequelize');
const bcrypt = require('bcryptjs');
// Load User Model
const Client = require('../models/Client');
module.exports = function(passport) {
passport.use(
new LocalStrategy({ usernameField: 'username'}, function(username, password, done) {
// Match User
Client.findOne({ where: {username: username} })
.then(function(user) {
if(!user) {
return done(null, false, { message: 'That username is not registered'});
}
// Match password
bcrypt.compare(password, user.password, function(err, isMatch) {
if(err) throw err;
if(isMatch) {
return done(null, user);
} else {
return done(null, false, { message: 'Password incorrect'});
}
});
})
.catch(function(err) { console.log(err) });
})
)
passport.serializeUser(function(user, done) {
console.log('Serializing user');
done(null, user.id);
});
passport.deserializeUser(function(id, done) {
console.log('Deserializing user');
console.log('User ID:', id);
Client.findByPk(id)
.then(function(err, user) {
console.log('User ID:', id);
done(err, user);
});
});
}
All the required middleware is setup in the correct order (express-session -> passport.initialize -> passport.session). cookieParser and express-session are set with the same secret (which is otherwise a problem as other posts suggest).
app.js
var createError = require('http-errors');
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var bodyParser = require('body-parser');
var cors = require('cors');
// Passport config
require('./config/passport')(passport);
var usersController = require('./controllers/usersController');
var indexRouter = require('./api/routes/index');
var usersRouter = require('./api/routes/users');
var roomsRouter = require('./api/routes/rooms');
var app = express();
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
// EJS
app.use(expressLayouts);
app.use(express.json());
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('secret'));
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
In your app.js the routes need to be defined after the passpor middleware is set up.
For Example:
var createError = require('http-errors');
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require('mysql');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var bodyParser = require('body-parser');
var cors = require('cors');
// Passport config
require('./config/passport')(passport);
var usersController = require('./controllers/usersController');
var app = express();
app.use(cors());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
// EJS
app.use(expressLayouts);
app.use(express.json());
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('secret'));
app.use(express.static(path.join(__dirname, 'public')));
// Express Session
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
var indexRouter = require('./api/routes/index');
var usersRouter = require('./api/routes/users');
var roomsRouter = require('./api/routes/rooms');
Try doing this and see the output

CANNOT GET / in Node app

I've checked the other related questions and can't pinpoint what's causing the issue (don't have a lot of experience here). I'm trying to launch this app locally basically with its default settings (other than some Twilio keys), have the dependencies installed, mongo is running, but localhost:5000 returns CANNOT GET /.
> node server.js
listening on port 5000
server.js:
// modules =================================================
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require('socket.io')(http); //real-time chat
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var cookieParser = require('cookie-parser');
// configuration ===========================================
// public folder for images, css,...
app.use(express.static(__dirname + '/public'))
// config files
// database
var db = require('./config/db');
// models
var User = require('./app/models/users');
var Message = require('./app/models/messages');
//parsing
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); //for parsing url encoded
//AUTH========================================================
app.use(cookieParser());
app.use(require('express-session')({
secret: 'white rabbit',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
// passport config
var Member = require('./app/models/members');
passport.use(new LocalStrategy(Member.authenticate()));
passport.serializeUser(Member.serializeUser());
passport.deserializeUser(Member.deserializeUser());
// view engine ejs
app.set('view engine', 'ejs');
//chat namespace
var chatSocket = io.of('/chat')
//routes
require('./app/routes/routes')(app, chatSocket);
//Heroku port
app.set('port', (process.env.PORT || 5000));
//ADMIN====================================================
//create an admin account if none exists
var admin = Member.find({admin: true}, function(err, admins) {
if (err) throw err
else if(admins.length == 0){
//no admin. create default account
Member.register(new Member({username: "admin", admin: true}), "mypassword", function(err, admin){
if(err) throw err;
console.log('Defaut account created successfully!');
})
}
else{
//at least one admin exists
console.log('Admin account already exists : ');
console.log(admins)
}
});
//START ===================================================
http.listen(app.get('port'), function(){
console.log('listening on port ' + app.get('port'));
});
//SOCKET ==================================================
require('./app/controllers/socket')(chatSocket, User, Message);
You didn't set any route that points to /
Point to that route by using app.get
app.get("/", function(req, res) {
res.send("home");
});
There are available routes in /app/routes/*.js files of the repository you cloned.

How to fix it..?? TypeError: Cannot read property 'FileSystem' of undefined

Am trying to split and merge the uploaded pdf file in nodejs,while am running i getting error" TypeError: Cannot read property 'FileSystem' of undefined","ReferenceError: FS is not defined" help me to fix it.
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 fileUpload = require('express-fileupload');
var routes = require('./routes/index');
var users = require('./routes/users');
var gm = require('gm');
var app = express();
var fs =require('fs');
app.use(fileUpload());
app.post('/upload', function(req, res) {
var sampleFile;
console.log("upload");
if (!req.files) {
res.send('No files were uploaded.');
return;
}
new FS.Store.FileSystem("thumbs", {
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name() + '[0]').resize('100', '100').stream('png').pipe(writeStream);
},
beforeWrite: function (fileObj) {
return {
extension: 'pdf',
type: 'pdf'
};
},
path: "./public/images/",
})
sampleFile = req.files.sampleFile;
console.log("statrttttttttt");
console.log(req);
var fileName=sampleFile.name;
sampleFile.mv('./public/images/'+fileName, function(err) {
if (err) {
res.status(500).send(err);
}
else {
res.send("<html><h1><object data='/images/"+fileName+"'</h1></object></html>");
}
});
})
// 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('/js',express.static(path.join(__dirname, 'public/javascripts')));
app.use('/', routes);
app.use('/users', users);
module.exports = app;
new FS.Store.FileSystem("thumbs", {
transformWrite: function(fileObj, readStream, writeStream) {
gm(readStream, fileObj.name() + '[0]').resize('100', '100').stream('png').pipe(writeStream);
},
javascript is case senesitive. you are referencing to fs module as:
var fs = require('fs');
and using FS.

How to url rewrite in nodejs and receive values on server end

i want to rewrite the url like this
http://localhost:3000/page?N1=568ff78634da
and receive value on the server end
app.get('/page', function(req, res){
var x=req.body.N1;
//do something with the value
});
my server is something like this:
var express = require('express');
var mongo = require('mongodb').MongoClient;
var app = express();
var path = require('path');
var bodyParser = require("body-parser");
var url = 'mongodb://localhost:27017/test';
var assert = require('assert');
var MongoClient = require('mongodb').MongoClient;
var session = require("express-session");
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var ObjectID = require('mongodb').ObjectID;
users = [];
connections = [];
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'views')));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({resave: false, saveUninitialized: true, secret:'xxxxxxxxxxxxx'}));
app.use(bodyParser.json());
using this way i am not able to receive values...
this is get request in get request the data is in query so write this
var someData=request.query.data;
in ur case
var someData=request.query.N1;
You can access the parameters using the query object, contained within the request e.g.
app.get('/page', function(req, res) {
var x = req.query.N1;
console.log('x = ' + x);
});

req.body becomes undefined after passing to res.render

My problem is that req.body becomes undefined when I try to render a page.
My app code:
var https = require('https');
var fs = require('fs');
var mongourl = "mongodb://localhost:27017/auntyinda";
var mongoose = require('mongoose');
fs.readdirSync(__dirname + '/models').forEach(function (filename) {
if (~filename.indexOf('.js')) require(__dirname + "/models/" + filename);
});
//var queries = require('./mongoq/query')
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 expressSession = require('express-session');
var passport = require('passport');
var myPass = require('./security/auth')
var routes = require('./routes/index');
//var users = require('./routes/users');
var app = express();
var server = https.createServer({
cert: fs.readFileSync(__dirname + '/my.crt'),
key: fs.readFileSync(__dirname + '/my.key')
},app).listen(4000);
// 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.configure(function(){
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//app.use(require('connect').bodyParser())
app.use(cookieParser());
app.use(expressSession( {
secret: process.env.SESSION_SECRET || 'sonic12',
resave: false,
saveUninitialized: false
}))
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
//});
mongoose.connect(mongourl)
//app.use('/', myPass);
app.use('/', routes);
//app.use('/users', users);
//app.locals.appdata = require("./data.json")
My route code:
router.post('/register', function(req, res, next) {
regcheck(req.body.username, req.body.password, req.body.passwordConfirm, function (error) {
if (error) {
console.log(req.body) //OUTPUT IS WHAT IS EXPECTED. NICE JSON FORMAT.
res.render('register', {
title: 'Register',
classname: 'register',
socialIcons: socialIcons,
isAuthenticated: false,
regdata: req.body,
err: error
})
}
})
})
I want the render to use the regdata object to refill data that was good back into the registration form. But for some strange reason it becomes undefined by the time it reaches the render.
My EJS file contains this line at the top:
<% console.log('Error recieved: '); console.log(err); console.log(regdata); %>
But the output of the console.log(regdata) is undefined. What is happening here? The err prints as it should. Thanks in Advance for your help.
Try this,
<pre><%= regdata %></pre>
I think you are missing out a = somewhere.
Consult the docs.

Resources