Created
January 27, 2019 12:23
-
-
Save Reshetnyak/da23728bea3381d52c02312d96e33a98 to your computer and use it in GitHub Desktop.
This file contains 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
//@ts-check | |
const express = require('express'); | |
const session = require('express-session'); | |
const app = express(); | |
const MAX_AGE = 5000; | |
// Use the session middleware | |
app.use(session({ secret: 'keyboard cat', cookie: { maxAge: MAX_AGE }})); | |
app.use(function(req, res, next){ | |
console.log('every request', 22222); | |
next(); | |
}); | |
/* | |
on any request | |
if (logged in) { | |
// if session expired | |
if (session.cookie.maxAge > new Date()) { | |
redirect to login | |
} else { | |
// update session coockie | |
session.cookie.maxAge = MAX_AGE; | |
} | |
if ( Doesn't have MVPAccess ) { | |
redirect to login | |
} | |
} esle { | |
redirect to login | |
} | |
*/ | |
// Access the session as req.session | |
app.get('/', function(req, res, next) { | |
// if logged in | |
if (req.session.views) { | |
req.session.views++ | |
res.setHeader('Content-Type', 'text/html') | |
res.write('<p>views: ' + req.session.views + '</p>') | |
res.write('<p>expires in: ' + (req.session.cookie.maxAge / 1000) + 's</p>'); | |
res.write(`<form action="api/change" method="post"> | |
<input type="text" name="data" value="mydata" /> | |
<button type="submit">Change coockie age</button> | |
</form>`); | |
console.log(req.session.cookie); | |
next(); | |
// res.end() | |
// if logged out | |
} else { | |
req.session.views = 1; | |
res.redirect('/.sso/login'); | |
// res.end('welcome to the session demo. refresh!') | |
} | |
}, function(req, res, next) { | |
res.write('<p>Added by middleware</p>'); | |
res.end(); | |
}); | |
app.get('/.sso/login', function(req, res, next) { | |
res.send('Redirected to Login <a href="/">LOGIN</a>'); | |
}); | |
app.get('/.sso/logout', function(req, res, next) { | |
res.send('Redirected to Logout <script>setTimeout(() => { window.location.href = "/.sso/login"}, 3000)</script>'); | |
}); | |
app.post('/api/change', function(req, res, next) { | |
// console.log('req body is: ',); | |
req.session.cookie.maxAge = 5000; | |
res.redirect('/'); | |
}); | |
app.get('/app', function (req, res) { | |
res.send('Hello World!'); | |
}); | |
app.listen(3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment