Skip to content

Instantly share code, notes, and snippets.

@sgnl
Created February 11, 2016 01:52
Show Gist options
  • Select an option

  • Save sgnl/99f6a39d56cce837504f to your computer and use it in GitHub Desktop.

Select an option

Save sgnl/99f6a39d56cce837504f to your computer and use it in GitHub Desktop.
Simple example of sessions in Express with 'Express-Session' package
'use strict';
const Express = require('express');
const Server = Express();
const BodyParser = require('body-parser');
const Session = require('express-session');
Server.use(BodyParser.json());
Server.use(Session({
secret: 'keyboard cat',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}));
Server.get('/', (req, res) => {
res.send('This is the Index Page.');
});
Server.post('/login', (req, res) => {
var validUserCredentials = { id: 1, name: "Ray", password: 1234 };
if (req.body.name === validUserCredentials.name && req.body.password === validUserCredentials.password) {
console.log('valid user, logging in and redirecting');
console.log(req.body);
req.session.user = {
name: validUserCredentials.name,
id: validUserCredentials.id
};
return res.redirect('/protected');
}
return res.send({ success: false });
});
Server.get('/protected', validateUser, (req, res) => {
res.send('YOU HAVE THE SECRET NOW. THREAD LIGHTLY');
});
Server.get('/logout', (req, res) => {
delete req.session.user;
res.send('you havebeen logged out.');
});
Server.listen(3334, () => {
console.log('server started on 3334');
});
function validateUser (req, res, next) {
console.log(req.session);
if (req.session.hasOwnProperty('user')) {
return next();
}
return res.send('must login first plz');
}
@sgnl
Copy link
Author

sgnl commented Feb 11, 2016

Test routes and sessions with Postman or build out a front-end for this example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment