官术网_书友最值得收藏!

The example-logging system

We've seen the main features of Express. Now let's build something real. The next few pages present a simple website where users can read only if they are logged in. Let's start and set up the application. We are going to use Express' command-line instrument. It should be installed using npm install -g express-generator. We create a new folder for the example, navigate to it via the terminal, and execute express --css less site. A new directory, site, will be created. If we go there and run npm install, Express will download all the required dependencies. As we saw earlier, by default, we have two routes and two controllers. To simplify the example, we will use only the first one: app.use('/', routes). Let's change the views/index.jade file content to the following HTML code:

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    h1= title
    hr
    p That's a simple application using Express.

Now, if we run node ./bin/www and open http://127.0.0.1:3000, we will see the page. Jade uses indentation to parse our template. So, we should not mix tabs and spaces. Otherwise, we will get an error.

Next, we need to protect our content. We check whether the current user has a session created; if not, a login form is shown. It's the perfect time to create a new middleware.

To use sessions in Express, install an additional module: express-session. We need to open our package.json file and add the following line of code:

"express-session": "~1.0.0"

Once we do that, a quick run of npm install will bring the module to our application. All we have to do is use it. The following code goes to app.js:

var session = require('express-session');
app.use(session({ secret: 'app', cookie: { maxAge: 60000 }}));
var verifyUser = function(req, res, next) {
    if(req.session.loggedIn) {
        next(); 
    } else {
        res.send("show login form");
    }   
}
app.use('/', verifyUser, routes);

Note that we changed the original app.use('/', routes) line. The session middleware is initialized and added to Express. The verifyUser function is called before the page rendering. It uses the req.session object, and checks whether there is a loggedIn variable defined and if its value is true. If we run the script again, we will see that the show login form text is shown for every request. It's like this because no code sets the session exactly the way we want it. We need a form where users can type their username and password. We will process the result of the form and if the credentials are correct, the loggedIn variable will be set to true. Let's create a new Jade template, /views/login.jade:

doctype html
html
  head
    title= title
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    h1= title
    hr
    form(method='post')
      label Username:
      br
      input(type='text', name='username')
      br
      label Password:
      br
      input(type='password', name='password')
      br
      input(type='submit')

Instead of sending just a text with res.send("show login form"); we should render the new template, as follows:

res.render("login", {title: "Please log in."});

We choose POST as the method for the form. So, we need to add the middleware that populates the req.body object with the user's data, as follows:

app.use(bodyParser());

Process the submitted username and password as follows:

var verifyUser = function(req, res, next) {
  if(req.session.loggedIn) {
    next();  
  } else {
    var username = "admin", password = "admin";
    if(req.body.username === username && 
    req.body.password === password) {
      req.session.loggedIn = true;
      res.redirect('/');
    } else {
      res.render("login", {title: "Please log in."});
    }
  }  
}

The valid credentials are set to admin/admin. In a real application, we may need to access a database or get this information from another place. It's not really a good idea to place the username and password in the code; however, for our little experiment, it is fine. The previous code checks whether the passed data matches our predefined values. If everything is correct, it sets the session, after which the user is forwarded to the home page.

Once you log in, you should be able to log out. Let's add a link for that just after the content on the index page (views/index.jade):

a(href='/logout') logout

Once users clicks on this link, they will be forward to a new page. We just need to create a handler for the new route, remove the session, and forward them to the index page where the login form is reflected. Here is what our logging out handler looks like:

// in app.js
var logout = function(req, res, next) {
  req.session.loggedIn = false;
  res.redirect('/');
}
app.all('/logout', logout);

Setting loggedIn to false is enough to make the session invalid. The redirect sends users to the same content page they came from. However, this time, the content is hidden and the login form pops up.

主站蜘蛛池模板: 莒南县| 南丹县| 清远市| 永吉县| 宁河县| 陆丰市| 龙山县| 长乐市| 通辽市| 克拉玛依市| 望江县| 罗甸县| 宝清县| 垦利县| 泽普县| 右玉县| 甘泉县| 浦北县| 鄂托克旗| 阿瓦提县| 文化| 新源县| 会同县| 苏尼特右旗| 盖州市| 筠连县| 冀州市| 楚雄市| 铁力市| 夏河县| 信宜市| 金秀| 五大连池市| 开远市| 竹北市| 碌曲县| 旌德县| 通化县| 海晏县| 尉犁县| 安远县|