How to clear browser's sid cookie in an express session? - express

On my express js app, I have set a session cookie, however even after logging out, my cookie is not removed from the browser. Hence clicking signing in, I can log back in without valid authentication.
Here is my app.js:
'use strict';
var auth = require('http-auth');
var bodyParser = require('body-parser');
var config = require('./test/lib/utils/config');
var cookieParser = require('cookie-parser');
var express = require('express');
var mysql = require('mysql2');
var passport = require('passport');
var path = require('path');
var session = require('express-session');
var favicon = require('serve-favicon');
var Auth = require('./lib/auth');
var Utils = require('./lib/utils');
var admin = require('./routes/admin');
var committee = require('./routes/committee');
var index = require('./routes/index');
var logout = require('./routes/logout');
var professor = require('./routes/professor');
var roles = require('./routes/roles');
var creds = config.credentials.database;
var connection = mysql.createConnection(creds);
connection.connect();
var authentication = new Auth(connection);
var utils = new Utils(connection);
var basic = auth.basic({
realm: 'Welcome to My App',
file: path.resolve(__dirname, '.private', '.htpasswd')
}, function(username, password, cb) {
utils.getMemberId(username, function(err, id) {
if (err) return cb(err);
utils.isLoggedIn(id, function(err, isLoggedIn) {
if (err) return cb(err);
if (!isLoggedIn) {
authentication.logIn(id, function(err) {
if (err) return cb(err);
return cb(id);
});
} else {
return cb(id);
}
});
});
});
var app = express();
passport.use(auth.passport(basic));
// Setup strategy.
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
app.use(favicon(path.join(__dirname, 'public', 'image', 'favicon.ico')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({ name: 'sid', rolling: true, secret: 'keyboard cat', cookie: { maxAge: 30000, httpOnly: true }}));
app.use(passport.initialize());
app.use(passport.session());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use('/', index);
app.use('/roles', [passport.authenticate('http', {session: true}), setUserId,
setUserRoles, setUserFirstName, setUserFullName], roles);
app.use('/roles/admin', admin);
app.use('/roles/committee', committee);
app.use('/roles/professor', professor);
app.use('/logout', performLogout, logout);
// 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 handler
app.use(function(err, req, res) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
function setUserId(req, res, next) {
console.log(JSON.stringify(req.session));
utils.getMemberId(req.session.passport.user, function(err, id) {
if (err) next(err);
req.session.passport.id = id;
next();
});
}
function setUserRoles(req, res, next) {
utils.getRoles(req.session.passport.id, function(err, roles) {
if (err) next(err);
req.session.passport.roles = roles;
next();
});
}
function setUserFullName(req, res, next) {
utils.getMemberFullName(req.session.passport.id, function(err, fname) {
if (err) next(err);
req.session.passport.fullname = fname;
next();
});
}
function setUserFirstName(req, res, next) {
utils.getMemberFirstName(req.session.passport.id, function(err, fname) {
if (err) next(err);
req.session.passport.fname = fname;
next();
});
}
function performLogout(req, res, next) {
authentication.logOut(req.session.passport.id, function(err) {
if (err) next(err);
next();
});
}
module.exports = app;
Here is my logout.js router:
'use strict';
var express = require('express');
var router = express.Router();
router.get('*', function(req, res) {
console.log('Session before logging out: ' + JSON.stringify(req.session));
req.session.destroy(function() {
res.clearCookie('connect.sid', { name: 'sid', rolling: true, secret: 'keyboard cat', cookie: { maxAge: 30000, httpOnly: true }});
res.redirect('/');
console.log('Session after logging out: ' + JSON.stringify(req.session));
});
});
module.exports = router;
I am unsure of what I am doing wrong to not clear the session cookie properly. Any help with guiding the right away will be appreciated.

Related

express js session property undefined

I have a few Problem with the session in express.
When i log in i'm setting the session.uid session.user and session.isAuth to its Parameter.
When i click on some other Sides where i need the Info of the Session. It sometimes work, sometimes it doesn't. Sometime i got the Error that 'user' is undefined....
I have this Code. And when i click for Example on editQuestion i got the Error. When i do the console.log in the '/' route it works.
Can someone tell me what i'm missing here?
var express = require("express");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const flush = require("connect-flash");
var path = require("path");
const w2v = require("word2vec");
const port = 3000;
const background = require("./public/js/background.js")
const datahandler = require("./public/js/data_handling.js")
//var routes = require("./routes");
var app = express();
app.set("port", process.env.PORT || 3000);
app.set("views", path.join(__dirname, "public/html"));
//app.set("view engine", "ejs");
app.engine('html', require('ejs').renderFile);
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(session({
cookie:{maxAge:60000},
resave: false,
saveUninitialized: false,
secret: "secret"
}));
//app.use(flush());
//Bodyparser
app.use(express.urlencoded({extended:true}));
const isAuth = (req, res, next)=>{
if(req.session.isAuth){
next();
}else{
res.redirect("/login");
}
}
app.get("/", function(req, res) {
res.render("index.html");
});
app.get("/question", function(req,res){
var Qid = Number(req.query.id)
})
app.get("/search", function(req,res){
var searchWords = req.query.search.split(' ');
w2v.loadModel('public/data/word_vectors.txt', (error, model) =>{
var word_vectors = model.getVectors(searchWords)
var avg_vector = background.averageVectors(word_vectors, model);
var questions = background.mostSimilarQuestions('/../data/qentities.txt', avg_vector);
var resultjson = datahandler.getQuestionsFromSimilar(questions);
res.json(resultjson)
})
});
app.get("/search/new", function(req,res){
var resultjson = datahandler.getNewestQuestions();
//console.log(resultjson);
res.json(resultjson);
});
app.get("/LogIn", function(req, res){
console.log(req.session.user);
res.render("LogIn.html");
})
app.post("/logIn",async(req, res) =>{
//LogIn
const{username, password} = req.body;
const user = datahandler.logIn(username, password);
if(!user){
return res.send("Log In failed!")
}else{
req.session.uid = user[0];
req.session.user = user[1];
req.session.isAuth = true;
req.session.save();
res.redirect("/");
}
});
app.get("/user",isAuth, (res, req)=>{
//res.send(req.session.user);
//res.json(req.session.user)
res.redirect("Profil.html");//Doesn't work ;(
});
app.get("/editQuestion", isAuth,(res, req)=>{
//console.log(req.session.user); Not working here. WHY?????
res.render("editQuestion.html");
});
app.get("/viewQuestion", isAuth,(res, req)=>{
console.log(req.session.user);
res.render("viewQuestion.html");
});
app.get('/logout',function(req,res){
console.log(req.session);
req.session.destroy(function(err) {
if(err) {
console.log(err);
} else {
res.redirect('/');
}
});
});
app.get("/Register", function(req,res){
res.render("Register.html")
})
app.post("/register", async(req,res)=>{
const{newUsername, password} = req.body;
const newuser = datahandler.registerNewUser(newUsername, password);
if(!newuser){
res.redirect("/Register");
}
else{
res.redirect("/");
}
})
app.get("/about", function(req, res) {
res.render("about.html");
});
app.all('*',(req,res)=>{
res.status(404).render('404.html');
});
app.listen(app.get("port"), function() {
console.log(`Example app listening at http://localhost:${port}`);
});
This is the Out i get when i click on editQuestion:
TypeError: Cannot read property 'user' of undefined
And this in the '/' what is correct:
TP
Ok. I solved it....
I swapped req and res in the functions...

ExpressJS - JWT and Passport Implementation

I'm currently trying to learn JWT and Passport for ExpressJS while trying them out but I can't seem to grasp the idea of how Passport works.
Here's what I have done initially in my ExpressJS application.
/api/login POST API
Accepts username and password
/api/login then creates a JWT with the username and password as the payload
The token is then responded to the client
I think my /api/login API simulates the general idea of JWT of hard authenticate once and respond with token.
/api/test GET API on the other hand
Only authenticated users can access
Simply returns "Hello World!"
What is the problem/s?
My code doesn't seem to validate the token (I tried putting the token in Authenticate header.
Where in my request should I include the token returned from /api/login when requesting to /api/test?
Now to my actual code:
app.js
var express = require("express");
var bodyParser = require("body-parser");
var jwt = require("jsonwebtoken");
var passport = require("passport");
var LocalStrategy = require('passport-local').Strategy;
var mySecret = "mySecret";
var app = express();
var port = process.env.PORT || 3000;
app.use(bodyParser.json());
passport.use(new LocalStrategy(
function (token, done) {
var credentials = jwt.verify(token, mySecret);
if (credentials.username == "test" && credentials.password == "test") {
return done(null, credentials);
} else {
return done(null, false);
}
}
));
app.use(passport.initialize());
app.post("/api/login", function (request, response) {
var user = {
"username": request.body.username,
"password": request.body.password
};
response.send(jwt.sign(user, "mySecret"));
});
app.get("/api/test", passport.authenticate("local", {
"session": false
}), function (request, response) {
response.send("Hello World!");
});
app.listen(port, function () {
console.log("Listening on port: " + port);
});
You need to configure jwtStratagy also to authenticate the user.
here is working example: -
const express = require("express");
const bodyParser = require("body-parser");
const jwt = require("jsonwebtoken");
console.log(jwt.verify);
const passport = require("passport"),
LocalStrategy = require("passport-local").Strategy;
const cors = require("cors");
const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(passport.initialize());
var secret = '11210646';
var JwtStrategy = require('passport-jwt').Strategy,
ExtractJwt = require('passport-jwt').ExtractJwt;
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password',
passReqToCallback: true
},
function(req, username, password, done) {
console.log('ohh', username, password);
let err = null;
if (err) { return done(err); }
if (username != 'abhi') {
return done(null, false, { message: 'Incorrect username.' });
}
if (password != 'pass') {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, username);
}
));
app.post('/login', function(req, res, next) {
passport.authenticate('local', function(err, user, info) {
console.log(err, user, info);
if (err) { return next(err); }
if (!user) { res.send({ "status": info.message }); }
res.send({ "status": user });
})(req, res, next);
});
var opts = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: secret,
issuer: 'jonu',
audience: 'jonu bhai',
passReqToCallback: false
};
app.post('/me2', function(req, res, next) {
passport.authenticate('jwt', { session: false }, function(err,user, info) {
if (err) { return next(err); }
if (!user) { res.send({ "status": info.message }); }
res.send({ "status": user });
})(req, res, next);
});
//jwt
passport.use(new JwtStrategy(opts, function(jwt_payload, done) {
let err = null;
if (err) {
return done(err, false);
}
if (jwt_payload) {
return done(null, jwt_payload);
}
else {
return done(null, false);
// or you could create a new account
}
}));
app.post('/signup', (req, res) => {
let token = jwt.sign({
user: {
id: "idididid",
name: "Abhishek Singh",
username: "abhishek11210646"
}
},
secret, {
algorithm: 'HS256',
expiresIn: '5h',
issuer: 'jonu',
audience: 'jonu bhai'
});
res.send({ "token": token });
});
app.get('/', (req, res) => {
res.send({ "status": "Up and Running..." });
});
app.listen(8080, () => {
console.log('server running');
});

how to manage multiple session in express js

i am building a site that as two url ('/','/admin') session are conflicting
here is my app.js session code
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(session({
secret: "JHGF>,./?;;LJ8#$?,KL:>>>,,KJJJDHE",
resave: true,
saveUninitialized: true
}));
app.use(flash());
app.use(passport.initialize());
app.use(passport.session());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/admin', admin);
please how can i fix this?
here is index.js
var express = require('express');
var User = require('../models/user');
var Admin = require('../models/admin');
var Pandingpay = require('../models/pandingpay');
var Confirmpay = require('../models/confirmpay');
var passport = require('passport');
var moment = require('moment');
var router = express.Router();
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
req.flash("info", "You must be logged in to see this page.");
res.redirect("/user/login");
}
};
function Authenticated(req, res, next) {
if (req.isAuthenticated()) {
res.redirect('/user/dashboard/');
}else {
next();
}
};
router.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.errors = req.flash("error");
res.locals.infos = req.flash("info");
next();
});
/* GET home page. */
router.get('/', function(req, res) {
res.render('index',{
title: 'Home'
});
});
router.post('/login', function(req, res, next) {
passport.authenticate('user-local', {failureFlash:true}, function(err, user, info) {
if(!req.body.password || !req.body.username){
req.flash("error", "Please enter your username and password");
return res.redirect("/login");
}
if (err) { return next(err); }
if (!user) {
req.flash("error", "Sorry username or password is invalied!");
return res.redirect('/login');
}
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/dashboard');
});
})(req, res, next);
});
and here is my admin.js
var express = require('express');
var User = require('../models/user');
var Admin = require('../models/admin');
var Pandingpay = require('../models/pandingpay');
var Confirmpay = require('../models/confirmpay');
var passport = require('passport');
var moment = require('moment');
var routeradmin = express.Router();
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) {
next();
} else {
req.flash("info", "You must be logged in to see this page.");
res.redirect("/admin/login");
}
};
routeradmin.use(function(req, res, next){
res.locals.currentUser = req.user;
res.locals.errors = req.flash("error");
res.locals.infos = req.flash("info");
next();
});
/* GET home page. */
routeradmin.get('/login', function(req, res) {
res.render('adminlogin');
});
routeradmin.post('/login', function(req, res, next) {
passport.authenticate('admin-local', {failureFlash:true}, function(err, user, info) {
if(!req.body.password || !req.body.username){
req.flash("error", "Please enter your username and password");
return res.redirect("/admin/login");
}
if (err) { return next(err); }
if (!user) {
req.flash("error", "Sorry username or password is invalied!");
return res.redirect('/admin/login');
}
req.logIn(user, function(err) {
if (err) { return next(err); }
return res.redirect('/admin/allusers/' + user.username);
});
})(req, res, next);
});
what i mean by conflicting is that the when an admin login instead of creating a new session for admin it uses the session of an already login useruser
If you want two separate session objects, one for regular usage and one for admin usage with no overlap between them, then you have to do two separate app.use('/path1', session(...)) and app.use('/path2', session(...)) statements so you have two separate session managers for different paths and make sure each has a different cookie name (using the name parameter to the session() options). And, then you have to design your URLs to be sub-paths of those so they get the right path.
Usually, people only use one session and then just keep a flag in the session whether it's admin login or not and you can check that flag when needed.
I think it is possible that the flash widget is somewhere in the shared app? Rather than split out into the different paths?
Does that make sense

Parse-SDK-JS Express Webapplication and Passportjs Mixed Up Logged in Users Page

issue is:
page content of logged in users mixed up with another logged in user
project attributes:
I run project on
aws ec2 instance with
nginx as proxy to
pm2 started index.js of
expressjs website with
below library for my project
"aws-ses-mail": "^2.1.1",
"body-parser": "^1.15.2",
"cookie-parser": "^1.4.3",
"ejs": "^1.0.0",
"express": "~4.11.x",
"express-ejs-layouts": "^2.2.0",
"express-session": "^1.14.1",
"kerberos": "~0.0.x",
"mandrill": "^0.1.0",
"moment": "^2.14.1",
"parse": "~1.8.0",
"passport": "^0.3.2",
"passport-parse": "0.0.5",
"underscore": "^1.8.3"
also this code did not solve my problem:
app.disable('view cache');
app.use(function (req, res, next) {
res.removeHeader("X-Powered-By");
res.setHeader('Cache-Control', 'no-cache');
next();
});
with the following index.js code:
var express = require('express');
var cookieParser = require('cookie-parser');
var _ = require('underscore');
var moment = require('moment');
var path = require('path');
var ejs = require('ejs');
var bodyParser = require('body-parser');
var session = require('express-session');
var ParseStrategy = require('passport-parse');
var expressLayouts = require('express-ejs-layouts');
var postActions = require('./post-actions');
var Utility = require('./libs/utilities');
var requireUser = require('./require-user');
var userAgentDetector = require('./user-agent-detector');
var passport = require('passport');
Parse = require('parse/node').Parse;
Parse.initialize("hashcode", "hashcode","hashcode");
Parse.CoreManager.set('SERVER_URL', 'http://localhost:1337/parse');
Parse.CoreManager.set('USE_MASTER_KEY', true);
var app = express();
app.use(bodyParser.json()); // for parsing application/json
app.set('views', __dirname+'/views');
app.set('view engine', 'ejs');
app.use(expressLayouts);
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
var parseStrategy = new ParseStrategy({parseClient: Parse});
passport.use(parseStrategy);
code continue :
app.use(session({
name: 'session-cookie-id',
secret: 'secret',
saveUninitialized: false,
resave: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.serializeUser(function(user, done) {
// done(null, user);
done(null, user.getSessionToken());
});
passport.deserializeUser(function(user, done) {
// user.className = "_User";
// user = Parse.Object.fromJSON(user);
// done(null, user);
var sessionToken = user;
var query = new Parse.Query('_Session');
query.equalTo('sessionToken', sessionToken);
query.include('user');
return query.first({useMasterKey: true}).then(function(session) {
user = session.get('user');
if (user) {
done(null, user);
} else {
done();
}
}, function(err) {
done();
});
});
app.use(userAgentDetector);
app.use(postActions);
code continue :
app.locals._ = _;
app.locals.moment = moment;
ejs.filters.videoMessageStr = function(str){
//return some code;
};
ejs.filters.secureImageUrl = function (url) {
return url.replace("http://", "https://s3.amazonaws.com/");
};
ejs.filters.getObjectThumb = function (userObject, params) {
//return some code;
};
ejs.filters.getImageThumb = function (imageObject, params) {
//return some code;
};
app.disable('view cache');
app.use(function (req, res, next) {
res.removeHeader("X-Powered-By");
res.setHeader('Cache-Control', 'no-cache');
next();
});
// Controller code in separate files.
var homeController = require('./controllers/home');
var usersController = require('./controllers/users');
app.get('/', homeController.index);
app.get('/home', homeController.getHomePage);
app.get('/home/page/:page', homeController.getHomePage);
app.get('/messages', requireUser, messagesController.index);
app.get('/login-and-save', usersController.loginAndSave);
code continue :
app.get('/login', usersController.getLogin);
app.post('/login', function(req, res, next){
passport.authenticate('parse',function(err, user, info) {
if (err || !user) {
return res.status(400).json(info);
}
req.logIn(user, function(err) {
if (err) {
return res.status(400).json(err);
}
res.end("ok");
});
})(req, res);
});
app.get('/logout', function(req, res, next){
req.logOut();
res.redirect('/');
});
app.get('*', function(req, res) {
res.render('home/404.ejs', { layout: false, url: req.url });
});
var port = process.env.PORT || 9000;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server running on port ' + port + '.');
});
There are several things you need to take into consideration when porting your Cloud Code to parse-server, especially around authentication. The passport-parse library you're using to handle authentication appears to be written with parse.com apps in mind, and has not been updated in two years as of this writing. I highly suspect that module is depending on the old currentUser behavior of hosted Parse.com apps.
Take a look at the Parse Server Guide to learn more about what needs to be updated when moving over to parse-server.

stormpath error If you do not specify a \'requestAuthenticator\' field, y

I'm getting the error specified above when trying to build a express-stormpath app. I'll list the applicable code:
Error: If you do not specify a 'requestAuthenticator' field, you must specify an ApiKey.
at Object.getAuthenticator (d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express- stormpath\node_modules\stormpath\lib\authc\index.js:24:11)
at new RequestExecutor (d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\node_modules\stormpath\lib\ds\RequestExecutor.js:37:37)
at new DataStore (d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\node_modules\stormpath\lib\ds\DataStore.js:46:52)
at new Client (d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\node_modules\stormpath\lib\Client.js:8:21)
at d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\lib\stormpath.js:60:36
at d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\node_modules\stormpath\lib\authc\ApiKeyLoader.js:14:14
at d:\dev\git-repos\bps\VolumeGridDataEntry\node_modules\express-stormpath\node_modules\stormpath\node_modules\properties-parser\index.js:348:20
at fs.js:208:20
at Object.oncomplete (fs.js:108:15)
[Updated] server.js
var express = require('express'),
session = require('express-session'),
crypto = require('crypto'),
formidable = require('formidable'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
index = require('./routes/index'),
users = require('./routes/users'),
stormpath = require('express-stormpath'),
config = require('./config/credentials.js'),
app = express();
function hashPwd(pwd) {
return crypto.createHash('sha256').update(pwd).digest('base64').toString();
}
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(stormpath.init(app, {
apiKeyFile: config.stormpathapi.apiKeyFile,
application: config.stormpathapi.application,
secretKey: config.stormpathapi.secretKey,
sessionDuration: 1000 * 60 * 30
}));
// domains for better error handling
app.use(function(req, res, next){
// create a domain for this request
var domain = require('domain').create();
// handle errors on this domain
domain.on('error', function(err){
console.error('DOMAIN ERROR CAUGHT\n', err.stack);
try {
// failsafe shutdown in 5 seconds
setTimeout(function(){
console.error('Failsafe shutdown.');
process.exit(1);
}, 5000);
// stop taking new requests
server.close();
try {
// attempt to use Express error route
next(err);
} catch(error){
// if Express error route failed, try
// plain Node response
console.error('Express error mechanism failed.\n', error.stack);
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Server error.');
}
} catch(error){
console.error('Unable to send 500 response.\n', error.stack);
}
});
// add the request and response objects to the domain
domain.add(req);
domain.add(res);
// execute the rest of the request chain in the domain
domain.run(next);
});
// cross-site request forgery protection
app.use(require('csurf')());
app.use(function(req, res, next){
res.locals._csrfToken = req.csrfToken();
next();
});
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'client')));
//name: cookie_name,
//store: sessionStore, // connect-mongo session store
app.use(session({
secret: config.cookieSecret,
resave: false,
saveUninitialized: true
}));
app.use('/', index);
app.use('/users', users);
// 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: {}
});
});
module.exports = app;
route index.js
var express = require('express'),
stormpath = require('express-stormpath'),
router = express.Router();
router.get('/', stormpath.groupsRequired(['dataentry']), function(req, res) {
res.render('index', { title: 'Volume Grid Data Entry' });
});
module.exports = router;
Initially the route signature was this but that didn't work either. I will need the ability in the future to base page security on groups...so, I'm not sure if I should use loginRequired or groupsRequired or both :-/
router.get('/', stormpath.loginRequired, function(req, res) {
Thanks!
That code looks correct -- but where is your app.use(require('./index')); code? That will be necessary after the app.use(stormpath.init(...)) stuff above =)
NOTE: I'm the author of the express-stormpath library.
EDIT: Here's a full example:
var express = require('express'),
stormpath = require('express-stormpath'),
router = express.Router();
var app = express();
router.get('/', stormpath.groupsRequired(['dataentry']), function(req, res) {
res.render('index', { title: 'Volume Grid Data Entry' });
});
app.use('/', router);
app.listen(3000);