connect
session takes over. To do this, add two rules: app.use(connect.cookieParser()); app.use(connect.session({ secret: 'your secret here'} ));
request
the session
field, through which the session data will be available (further with examples it will become clearer).connect.session
gets the following parameters:secret
is a phrase that is used to encrypt information in cookies.store
is the object that will be used to store session data. By default, connect keeps all data in memory, but, of course, in real applications, this is not possible. There are ready-made solutions for mongodb , redis , MySQL , etc.cookie
- a set of cookie settings. The most important is maxAge
, the lifetime in milliseconds (or null)connect
will add a session
field to each request, but by default there is nothing interesting. If we somehow "find out" the user (actually, if he enters the correct password), we will have to add information about him to the session. Something like this: if ((request.body.login==='Thor')&&(request.body.password==='111')) { request.session.authorized = true; request.session.username = request.body.login; console.log('Thor is here!'); }
username
variable would suffice (as the author of this article does). But then checking whether the user is authorized will look ugly: if (typeof req.session.username == 'undefined') { // , }
delete req.session.authorized; delete req.session.username ;
session
from the current request, and the next time this field is generated again.connect
. It is better to set a special rule that will check the user's rights and, if something goes wrong, redirect it to the error page. The idea is described here , in our case will be // , ; var siteUrls = [ {pattern:'^/login/?$', restricted: false} , {pattern:'^/logout/?$', restricted: true} , {pattern:'^/$', restricted: false} , {pattern:'^/single/\\w+/?$', restricted: true} ]; function authorizeUrls(urls) { function authorize(req, res, next) { var requestedUrl = url.parse(req.url).pathname; for (var ui in urls) { var pattern = urls[ui].pattern; var restricted = urls[ui].restricted; if (requestedUrl.match(pattern)) { if (restricted) { if (req.session.authorized) { // , next(); return; } else{ // , res.writeHead(303, {'Location': '/login'}); res.end(); return; } } else { next(); return; } } } // , console.log('common 404 for ', req.url); res.end('404: there is no ' + req.url + ' here'); } return authorize ; } app.use('/', authorizeUrls(siteUrls));
Source: https://habr.com/ru/post/145970/
All Articles