node. JS implements a simple login blocker

Source: Internet
Author: User

Interceptors are ubiquitous in web development, such as the site's management background, not everyone can enter, so you need to do an interceptor and friendly jump to the tip page.

Below we simply implement a, to determine whether the user is logged on successfully, the login is not successful users automatically redirect to the login page.

First we implement a filter

Exports.checkauth=function (Req, res, next)  {    var token =  req.signedcookies.token;    if  (token && req.session.user  && req.session.user.token === token)          Next ();    else if  (token)  {         //if invalid token or no session, should rebuild         var authinfo = user.getauthinfo (token);         if  (Authinfo && authinfo.isauth)  {             req.session.user = {                 userID: authInfo.userID,                 username: authinfo.username,                 isAuth: authInfo.isAuth,                 token: token             }             next ();        } else             res.redirect ('/user/login ');     } else        res.redirect ('/user/login ');}

Then define the route and add the filter

Module.exports = function (APP) {app.get ('/user/bloglist ', Pageadmin.checkauth, pageadmin.pagelist); App.all ('/user/post ', Pageadmin.checkauth, pageadmin.pagepost);}

The above route definition receives 3 parameters, the first one is the URL path of the request, the second is the filter, and if the filter is satisfied the next step into the route handler function, if not satisfied will not go to the back of the route definition function.

node. JS implements a simple login blocker

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.