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

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.

主站蜘蛛池模板: 翼城县| 西林县| 茂名市| 盐亭县| 高台县| 林甸县| 菏泽市| 饶平县| 高雄县| 曲阜市| 阳信县| 仪征市| 楚雄市| 化州市| 岱山县| 杭锦后旗| 乌鲁木齐市| 普安县| 胶南市| 行唐县| 山丹县| 兴隆县| 上虞市| 沧州市| 民县| 仲巴县| 黄山市| 华阴市| 静乐县| 大渡口区| 宁海县| 甘洛县| 调兵山市| 天全县| 万安县| 宕昌县| 上杭县| 凤阳县| 龙州县| 西乌| 福泉市|