Redis with express and passport - node.js

I am trying to using Redis with my exsiting application
Here is my app.js code
var express = require('express'),
request = require('request'),
http = require('http'),
path = require('path');
var app = express();
var routes = require('./routes');
var passport = require('passport');
var flash = require('connect-flash');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var busboy = require('connect-busboy');
var policies = require('./policies/admin');
var config = require('./config');
require('./libs/passport')(passport);
app.configure(function () {
app.use(express.session({ secret: 'secertkey', cookie: { maxAge : 2592000000 } })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
});
Which is working fine.
I want to use Rediss along with passport,
Is this possible and how can i do
Thanks

Pass the express-session store into connect-redis to create a RedisStore constructor.
var session = require('express-session');
var RedisStore = require('connect-redis')(session);
app.use(session({
store: new RedisStore(options),
secret: 'keyboard cat'
}));
for reference
https://www.npmjs.com/package/connect-redis

Related

module priority cannot solve my 'passport.initialize() middleware not in use'

var express = require('express');
var app = express();
var session = require('express-session');
var MySQLStore = require('express-mysql-session')(session);
var cookieParser = require('cookie-parser');
var bkfd2Password = require('pbkdf2-password');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var hasher = bkfd2Password();
var conn = require('../db/db_con')();
var config = require('../db/db_selector');
app.use(cookieParser());
app.use(express.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());
app.use(session({
secret: '432984252#!%#!$',
resave: false,
saveUninitialized: true,
store: new MySQLStore(config.dbConfig, conn)
}));
var router = express.Router();
:: this is head of 'login.js',
Node, express, passport, session, mysql...
For solving middle-ware hell,
I took the solutions by stackoverflow, about 100~200 questions and answers, but failed.
And when I executed login process, the error is from routes/signup.js:70:25,
the part is,
console.log('LocalStrategy', account);
done(null, account);
I can show localstrategy and account,
and done() func makes hell.
signup.js is similar to login.js.

CSRF protection for Node.js Express 4 and passport.js not working

Using csurf, I am trying to integrate csrf protection into my node.js express 4 application. This is my code:
EDIT: The code below was updated according to the solution I found.
"use strict";
var http = require('http');
var https = require('https');
var port = process.env.PORT || 80,
express = require('express'),
csrf = require('csurf'),
bodyParser = require('body-parser');
var LocalStrategy = require('passport-local').Strategy,
csrfProtection = csrf({ cookie: true }),
mongoose = require('mongoose'),
conn = mongoose.createConnection('foo'),
cookieParser = require('cookie-parser'),
passport = require('passport'),
session = require('express-session'),
MongoStore = require('connect-mongo')(session),
app = express();
app.set('view engine', 'ejs');
var csrfProtection = csrf({ cookie: true }); // doesn't work either
require('passport')(passport);
app.use(cookieParser("foo"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true})); //extended: true|false does not make any difference
app.use(session({
//foo
}));
app.use(passport.initialize());
app.use(passport.session());
require('./app/routes.js')(app, passport); //routes inside here cause a ReferenceError: csrfProtection is not defined
http.createServer(app).listen(port);
https.createServer(options, app).listen(443, function () {
//foo
});
-- routes.js --
var csrf = require('csurf'), //this needs to go in here
csrfProtection = csrf(); //this needs to go in here
module.exports = function(app, passport) {
app.route('/somepage')
.get(csrfProtection, function(req, res) {
res.render('somepage', { csrfToken: req.csrfToken()});
});
};
-- routes.js end--
For some strange reason csrfProtection remains unknown inside my page routes causing a ReferenceError (see comment inside code). What am I missing?
EDIT:
ignoreMethods
An array of the methods for which CSRF token checking will disabled. Defaults to ['GET', 'HEAD', 'OPTIONS'].
Try and set it to ['HEAD','OPTIONS']
csrfProtection = csrf(
{ cookie: true, ignoreMethods:['HEAD','OPTIONS' ] }
)

Can't store session in MongoDB with passport

I'm new to Node JS and I'm trying to store session in mongoDB by using the connect-mongo npm package , once I add the following line - i get an error :
app.use(session({
saveUninitialized: true,
resave: true,
store : new MongoStore({ // adding this will cause an error
db: 'users'
})
}));
Here are the session parts of my code (i'm using express 4.16) :
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 session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var expressValidator = require('express-validator');
var multer = require('multer');
var upload = multer({dest: './uploads'});
var flash = require('connect-flash');
var bcrypt = require('bcryptjs');
var mongo = require('mongodb');
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(session);
var db = mongoose.connection;
session(app, mongo.initSessionStore);
app.use(session({
saveUninitialized: true,
resave: true,
store : new MongoStore({
db: 'users'
})
}));
// Passport
app.use(passport.initialize());
app.use(passport.session());
You haven't sent instance of MonogDB to MongoStore. You sent string 'user', and it expect database instance. So it can't connect to MonogDB.
If you are using Mongoose you need first to connect to database, and then you can usemongoose.connection for MongoStore:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
app.use(session({
saveUninitialized: true,
resave: true,
store : new MongoStore({
mongooseConnection: db
})
}));

Implement cookie based authentication in Node JS with Passport

Below is my server.js (app.js). I am using express with passport, for user authentication. But whenever I restart my node server user logsout.
I am very new to nodejs, I was wondering how I could implement a cookie based authentication. So that user does not log out even if the server starts. I'm sure theres some config change which I have not able to find.
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 80;
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
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');
// configuration ===============================================================
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()); // get information from html forms
app.set('view engine', 'ejs'); // set up ejs for templating
// required for passport
app.use(session({ secret: 'yassers' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
Its logout when you restart your start because its stored in MemoryStore(RAM). Use mongoStore to store your session mongodb. Try below code:
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
var mongoStore = new MongoStore({
url: 'your mongo db url'
});
app.use(session({
secret: 'your secret',
saveUninitialized: true, // don't create session until something stored
resave: false, //don't save session if unmodified
store: mongoStore,
cookie: {
domain: 'domain name',
maxAge: 1000 * 24 * 60
}
}));

Node js Session Creating Different cookies for every request using Postgres and expression session

Here is my code
var express = require('express');
var router = express.Router();
var path = require('path');
var bodyParser = require('body-parser');
var cookieparser = require('cookie-parser');
var cors = require('cors');
var session = require('express-session');
var PostgreSqlStore = require('connect-pg-simple')(session);
//var mongoose=require('mongoose');
var app = express();
app.use(bodyParser());
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
//session starts
app.use(cookieparser());
var sessionOptions = {
secret: "secret",
resave: true,
//cookie :{ maxAge : 30 * 24 * 60 * 60 * 1000},
cookie: { httpOnly: false },
saveUninitialized: false,
store: new PostgreSqlStore({
conString: "postgres://postgres:password#127.0.0.1:5432/session"
})
};
app.use(session(sessionOptions));
//session ends
require('./routes/routes.js')(app);
app.listen(4001);
//exports.start = start;
exports.app = app;
While inserting on login
req.session('userid')=email;
the database has one record , but for next request it inserts another cookie record . I want to make it only once for authentication purpose. and i want to know better way of simple auth using postgres.

Resources