Created
February 11, 2016 01:52
-
-
Save sgnl/99f6a39d56cce837504f to your computer and use it in GitHub Desktop.
Simple example of sessions in Express with 'Express-Session' package
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| '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'); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test routes and sessions with Postman or build out a front-end for this example.