I am trying to setup Redis for a session store, but is not working at. I'm using passport.js and express-flash, and if I try run the current Redis setup, it won't work:
var session = require('express-session');
var favicon = require('serve-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var redis = require("redis").createClient();
var RedisStore = require("connect-redis")(session);
var load = require('express-load');
var flash = require('express-flash');
var path = require('path');
var logger = require('morgan');
var i18n = require('i18n-2');
var passport = require('passport');
var mongoose = require('mongoose');
If I use this session setup:
app.use(session({
secret: 'keyboard cat'
}));
This will show an error saying that is not safe for use in production, however the passport.js and the express-flash will work.
Moving on to Redis:
app.use(session({
store: new RedisStore({
host: 54.94.171.197,
port: 3000,
client: redis
}),
secret: 'keyboard cat'
}));
Should I put the static IP in the host and the 3000 in the port? I am very confused with the proper values that I need pass to the new instance.
This is my middleware:
app.use(favicon(__dirname + '/public/images/icons/fav.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(flash());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({
store: new RedisStore({
host: global.config.site.host,
port: 6379,
client: redis
}),
secret: 'keyboard cat'
}));
// Productions Middlewares
if (process.env.NODE_ENV === 'production') {
app.use(passport.initialize());
app.use(passport.session());
app.use('/admin', middleware.ensureAuthenticated);
app.use(middleware.ensureHttps);
}
It’s bad practice to have your application’s configuration inside the code.
Use something like nconf to have your configuration out of the code.
For example you could use a config.json file:
{
"sessionSecret": "cat something",
"redis": {
"host": "localhost",
"port": 6379
}
}
Configure nconf to look for the configuration file
var nconf = require('nconf');
nconf.file({ file: '/path/to/config.json' })
Then use the configuration in your session middleware
app.use(session({
store: new RedisStore({
host: nconf.get('redis:host'),
port: nconf.get('redis:port'),
client: redis
}),
secret: nconf.get('sessionSecret')
}));
Related
please i need your help, i have pushed my glitch website to github and finally push to heroku for deployment. When i did deployment i have some errors, and i come to understand that my repo was not set to continuous integration. now where in github can i navigate to set the repo to continous integration, before going back to deploy from heroku, thank you.
//start server: node engine
const express = require("express");
const app = express();
const compression = require('compression')
const dbInitiation = require("./construct/dbs");
const bodyParser = require("body-parser");
const dotenv = require("dotenv").config({path: "./.env"});
const userRoute = require("./routes/user");
const passport = require("passport");
const session = require("express-session");
const cookieParser = require('cookie-parser');
const MemoryStore = require("memorystore")(session);
//set directory for views template files
app.set('views', './views');
//set view engine
app.set('view engine', 'pug');
//middleware
app.use(compression())
app.use("/public", express.static(__dirname + "/public"));;
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser(process.env.SESSION_SECRET))
app.use(express.json());
require("./passport/local")(passport);
dbInitiation();
app.use(cookieParser())
const sessionStore = new MemoryStore({
checkPeriod: 86400000
});
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: true,
saveUninitialized: true,
key: "express.sid",
store: sessionStore,
}));
//
app.use(passport.initialize());
app.use(passport.session());
//use routes function
userRoute(app);
app.listen(process.env.PORT, function(req, res) {
console.log("app running on port:", process.env.PORT);
});
After deployment of my app on hosting service i run into problem of this message displaying after 3-5 get requests:
Incomplete response received from application
after that more of those errors popped out and session reseted
code of app.js:
// native node and express
const path = require('path');
const express = require('express');
const app = express();
const session = require('express-session');
const env = require('dotenv');
env.config();
const ruteing = require('./routeing/main');
const messageRouteing = require('./routeing/messages');
const authenticationRoutering = require('./routeing/authentication');
//set extenction settings
app.set('views', path.join(__dirname, 'views'));
app.set('render engine', 'pug');
app.use(express.urlencoded({ extended: false}));
app.use(session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false
}));
// create access routing from exported rutering
app.use('/', ruteing);
app.use('/m', messageRouteing);
app.use('/a', authenticationRoutering);
app.get('*', (req, res) => {
res.render('404.pug');
});
app.listen(3000, () => console.log('i do not even know what am i doing'))```
My hosting is mydevil
For some reason, I keep getting this error every time i try to use {{#iff}
Is this not rendering my page as handlebars? Did I use the {{#iff}} statement correctly?
My console prints this out:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
This is my handlebars(login.hbs):
<h1><span class="fa fa-sign-in"></span> Login</h1>
{{#iff message.length '>' 0}}
<div class="alert alert-danger">{{message}}</div>
{{/iff}}
This is my server.js
var express = require('express');
var app = express();
var port = process.env.PORT || 8080;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
const hbs = require('hbs');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var configDB = require('./config/database.js');
mongoose.connect(configDB.url); // connect to our database
require('./config/passport')(passport); // pass passport for configuration
// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.json()); // get information from html forms
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'hbs'); // set up hbs for templating
// required for passport
app.use(session({
secret: 'ilovescotchscotchyscotchscotch', // session secret
resave: true,
saveUninitialized: true
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
app.listen(port);
console.log('The magic happens on port ' + port);
In routes.js:
app.get('/login', function(req, res) {
res.render('login.hbs', { message: req.flash('loginMessage') });
});
I am building an api that will interface with the MongoDB database and have mounted it as a subapplication. I have defined a session variable in my server controller.
However, any time that the server files need to talk to the api files the session variables are never passed off.
Heres the app.js file
//app.js file
'use strict';
process.env.NODE_ENV = 'development';
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var flash = require('connect-flash');
var helmet = require('helmet');
var app = express();
app.use(helmet());
var port = process.env.PORT || 3000;
mongoose.connect("mongodb://localhost:27017/striv4");
var db = mongoose.connection;
// mongo error
db.on('error', console.error.bind(console, 'connection error:'));
app.use(session({
secret: 'secret',
resave: true,
saveUninitialized: false,
store: new MongoStore({
mongooseConnection: db
})
}));
app.use(flash());
// make user ID available in templates
app.use(function (req, res, next) {
res.locals.currentUser = {
username:req.session.username,
id: req.session.userId
};
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser('secreter'));
app.use(logger('dev'));
var api = require('./app_api/routes/index');
var serverRoutes = require('./server/routes/index');
//static file middleware
app.use(express.static(__dirname + '/public'));
app.set('views',__dirname +'/server/views');
app.set('view engine','pug');
app.use('/',serverRoutes);
app.use('/api',api);
//custom error handler
app.use(function(error, req, res, next) {
res.status(error.status || 500);
res.send('Error: '+error.message);
});
app.listen(port);
console.log('Listening on port: '+port);
You've got the whole program listed so there is more than one way for this to have gone wrong. Here are my suggestions to fix this:
Check the version of express-session you've installed. (Just run npm ls in the terminal and in your root Node app folder where you're package.json file is). If it's equal to or greater than v1.5.0, you don't need the cookie-parser for sessions anymore. Comment out the app.use line for the cookie parser and see if this works.
If you still need cookie parser for some other reason, you should use the same secret for sessions and the cookie parser. In your code, you've set two different values for secret.
I've seen that the other big failure for sessions occurs if the session store is not correctly connected to your Node app. Cross-check that the database is available and working. In my experience, Express sessions will fail silently if it can't get to the DB.
Hope this helps.
I am trying to setup Redis Store like this:
var express = require('express');
var app = express();
.......
.......
var session = require('express-session');
var redis = require("redis").createClient();
var RedisStore = require("connect-redis")(session);
app.use(session({
store: new RedisStore({
host: 'localhost',
port: 6379,
client: redis
}),
secret: 'keyboard cat'
}));
But using like this the passport.js wont work and the express-flash will throw an error: `Error: req.flash() requires sessions.
I believe Redis is not working at all.
I am very confuse with the configuration also, should i put localhost in the host key? I am using Cloud 9, not my localhost.
What i am doing wrong?
Not sure I can help you with passport.js and express-flash, but this is how I've setup my session with express, redis and socket.io :
var express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var RedisStore = require('connect-redis')(session);
............
var cookieSecret = "secret phrase";
var sessionMiddleware = session({
store: new RedisStore({
host: '127.0.0.1',
port: 6379,
prefix: 'sess'
}),
secret: cookieSecret,
cookie: {httpOnly: true, secure: true}, //I'm using https, so you should remove secure: true
resave: true,
saveUninitialized: true
});
.....
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser(cookieSecret));
app.use(sessionMiddleware);
....
var io = require('socket.io')(https);
io.use(function(socket, next) {
sessionMiddleware(socket.request, socket.request.res, next);
});
io.on('connection', function(socket){
console.log("connected");
console.log(socket.request.session);
});
Hope this could help a bit
Had a similar problem. Yes, chances are you do not have a Redis server running for the client you created. Try installing and running redis-server on your machine, that did the trick for me.