I got the problem on a route (register) :
TypeError: req.flash is not a function
at /Users/laurent/Projects/perso/express-live-stream/server/routes/register.js:11:32
Setup in app.js
const Session = require('express-session');
const flash = require('connect-flash');
app.use(require('cookie-parser')());
app.use(Session({
store: new FileStore({
path : './server/sessions'
}),
secret: config.server.secret,
cookie: {maxAge: Date().now + (60 * 1000 * 30) } ,
resave: false,
saveUninitialized: false
}));
app.use(flash());
Router (routes/register.js)
const express = require('express'),
router = express.Router(),
passport = require('passport');
router.get('/',
require('connect-ensure-login').ensureLoggedOut(),
(req, res) => {
res.render('register', {
user : null,
errors : {
username : req.flash('username'), <== problem here (line 11)
email : req.flash('email')
}
});
});
It seems my setup is ok as flash messages are stored in sessions.
I checked before in Google but didn't find anything
Thanks
Laurent
Fixed the problem
wrong order I should declare router before flash
Related
What's the best/common way to use an express-session in other files? I have trouble integrating the session into my code. I was using auth tokens, but I would like to use sessions instead.
I defined session in my server.js:
const express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser('secret'));
app.use(session({
key: 'user_sid',
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: {
expires: 600000
}
}));
// stuff
module.exports = {app, session};
And it works fine! But When I try to use it in my userController.js:
var express = require('express');
var {session} = require('./../server');
module.exports.login = (req, res) => {
var body = _.pick(req.body, ['email', 'password']);
User.findByEmailAndPassword(body.email, body.password).then((user) => {
// console.log(req.session); // is undefined
res.render('dashboard.hbs');
}).catch((e) => {
res.status(400).send();
});
}
then req.session is undefined.
I know what I'm doing isn't right, obviously, but what's the right way to do it?
Thanks!
I think you don't have to export session at all, as you are telling your app to use it in server.js.
So the working fiddle should be looking like the following:
const express = require('express');
var session = require('express-session');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser('secret'));
app.use(session({
key: 'user_sid',
secret: 'secret',
resave: false,
saveUninitialized: false,
cookie: {
expires: 600000
}
}));
// stuff
module.exports = app;
and your controller:
module.exports.login = (req, res) => {
var body = _.pick(req.body, ['email', 'password']);
User.findByEmailAndPassword(body.email, body.password).then((user) => {
// console.log(req.session); // is undefined
res.render('dashboard.hbs');
}).catch((e) => {
res.status(400).send();
});
}
I am considering that you are going to use this exported login function for a route, like
app.use('/login', require('yourCtrl.js').login);
This is my code:
const functions = require('firebase-functions');
const express = require('express');
const session = require('express-session');
const FirebaseStore = require('connect-session-firebase')(session);
const firebase = require('firebase-admin');
const cookieParser = require('cookie-parser');
const ref = firebase.initializeApp(
functions.config().firebase
);
const app = express();
app.use(cookieParser());
app.set('trust proxy', 1);
app.use(session({
store: new FirebaseStore({
database: ref.database()
}),
secret: 'abigsigrettotheseeiosnofthmbiith765huig',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
app.get('/', function(req, res, next) {
console.log(req.session);
req.session.username='xyz';
res.send('Filling the session with data');
});
app.get('/bar', function(req, res, next) {
console.log(req.session);
var sessionData = req.session.username;
res.send(`This will print the attribute I set earlier: ${sessionData}`);
});
exports.app = functions.https.onRequest(app);
When I run this, it creates new session in the DB.
And every time I refresh the page, there is a new session.
I want of course, that only one session would be created,
and that on refresh, this session would only be updated, or to get the data from there. not to create a new one every time.
Checking the cookies - showed me that no cookie is saved / created.
I've been working on this for hours...
this was frustrating when I was using firebase functions and hosting, but can be solved by simply setting name:"__session" in the session.
app.use(session({
store: new FirebaseStore({
database: ref.database()
}),
name:"__session
...
I am using Express Framework and socket.io. I am working on authentication part and I am unable to change the value of cookie. Please see the code.
var session = require('express-session');
app.use(cookieParser());
app.use(session({
secret: "kvkjsdsbj12334",
resave:false,
saveUninitialized: false,
cookie:{
authStatus: "NotLoggedIn",
secure: false
},
rolling: true
}));
app.use(function (req, res, next){
console.log(req.session.cookie.authStatus); // Logs NotLoggedIn after /login.
});
app.post('/login',(req,res)=>{
var body = _.pick(req.body,['email','password']);
var email = body.email;
var password = body.password;
Users.findByCredentials(body.email,body.password).then((user)=>{
req.session.user = user;
req.session.cookie.authStatus = "loggedIn";
req.session.save();
//Redirected from here
});
});
I use connect-mongo to store sessions in a DaaS, then I added a Remember me checkbox in the login page but when I don't check the textbox, it still writes the sessions in the sessions table. I wonder what I can be doing wrong:
server.js:
// server.js
// set up ======================================================================
// get all the tools we need
var express = require('express');
var app = express();
var port = process.env.PORT || 5000;
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 MongoStore = require('connect-mongo')(session);
var path = require('path'); //join method
var configDB = require('./config/database.js');
//pass passport for configuration
require('./config/passport')(passport);
// configuration ===============================================================
mongoose.connect(configDB.url, {useMongoClient : true}); // connect to our database
// set up our express application
app.use(express.static(path.join(__dirname, 'views'))); //angular and css files
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({
store: new MongoStore({ mongooseConnection: mongoose.connection, ttl: 14 * 24 * 60 * 60, autoRemove:'native', collection:'AllSessions' }),
secret: 'foo'
}));
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
// use connect-flash for flash messages stored in session
app.use(flash());
// routes ======================================================================
require('./app/routes.js')(app, passport); // load our routes and pass in our app and fully configured passport
//log all other requests here
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'views'));
});
// launch ======================================================================
app.listen(port);
console.log('The magic happens on port ' + port);
routes.js (POST code):
// process the login form
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile', // redirect to the secure profile section
failureRedirect: '/login', // redirect back to the signup page if there is an error
failureFlash: true // allow flash messages
}),
function(req, res, next)
{
if (!req.body.remember_me)
{
return next();
}
else{
app.use(session({
store: new MongoStore({ mongooseConnection: mongoose.connection, ttl: 14 * 24 * 60 * 60, autoRemove:'native', collection:'AllSessions' }),
secret: 'foo'
}));
}
});
Any suggestions are appreciated. Thanks in advance.
You're trying to initialize session when remember me is clicked, so rather than doing that. Initialize the session with a bare-minimum timeout and then use the code below:
app.use(session({
store: new MongoStore({ mongooseConnection: mongoose.connection, ttl: 3600000, autoRemove:'native', collection:'AllSessions' }),
secret: 'foo'
}));
app.post('/login', passport.authenticate('local-login', {
successRedirect: '/profile', // redirect to the secure profile section
failureRedirect: '/login', // redirect back to the signup page if there is an error
failureFlash: true // allow flash messages
}),
function(req, res, next)
{
if (!req.body.remember_me)
{
req.session.cookie.expires = false;
return next();
}
else{
req.session.cookie.maxAge = 2628000000; // for one month.
}
});
I developing login page.
If user successfully logs in , then I want to store user_Id into session variable,which I will be using to authenticate other pages.
App.js
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var passport = require('passport');
var cookieParser = require('cookie-parser');
var session = require('express-session');
app.use(bodyParser.json());
app.use('/user', userRoutes);
app.use('/', index);
app.use(cookieParser());
app.use(session({
secret: "helloKey",
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection}),
cookie: { maxAge: 180 * 60 * 1000 }
}));
User router
var express = require('express');
var router = express.Router();
User = require('../models/user');
//Login User
router.post('/login', function (req, res) {
var user = new User(req.body);
User.login(user, function (err, user) {
if (err) {
res.sendStatus(500);
throw err;
}
if (!user) {
res.sendStatus(404);
return;
}
req.session.name = user.id;
res.json(user.id);
});
});
Problem is if I execute this code I am getting Cannot set property 'name' of undefined
What I am doing wrong?
Please Help.
Problem is that your routes are already setup before session so you have to reorder the code.
Move these lines
app.use('/user', userRoutes);
app.use('/', index);
Below the app.use(session) declaration.
app.use(session({
secret: "helloKey",
resave: false,
saveUninitialized: true,
store: new MongoStore({ mongooseConnection: mongoose.connection}),
cookie: { maxAge: 180 * 60 * 1000 }
}))