Express-Intro to Passport.js part II

This is the second part on my Passport tutorial. Please read first part if you haven’t.

  1. Import session, express-validator, connect flash into app.js

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    var session = require('express-session');
    var flash = require('connect-flash');
    var expressValidator = require('express-validator');


    // Express Session
    app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: true
    }));

    // Express Validator
    app.use(expressValidator({
    errorFormatter: function(param, msg, value) {
    var namespace = param.split('.')
    , root = namespace.shift()
    , formParam = root;

    while(namespace.length) {
    formParam += '[' + namespace.shift() + ']';
    }
    return {
    param : formParam,
    msg : msg,
    value : value
    };
    }
    }));

    // Connect Flash
    app.use(flash());

    // setup local variables so we can use it anywhere in our app
    app.use(function (req, res, next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    res.locals.user = req.user || null;
    next();
    });
  2. Add flash and validation into routes/users.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// REVISED with validation feature. Post Sign Up
router.post('/signup', function(req, res, next) {
// Parse Info
var username = req.body.username
var password = req.body.password

// Validation
req.checkBody('username', 'Username is required').notEmpty()
req.checkBody('password', 'Password is required').notEmpty()

var errors = req.validationErrors();
if(errors) {
res.render('signup', {errors: errors})
} else {
//Create User
...
}

router.get('/logout', function(req, res, next) {
...
req.flash('success_msg', 'You are logged out')
...
})
});
  1. Implement the flash message to sign in & sign up views.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    //signin.ejs
    <% if(success_msg) { %>
    <div class="success">
    <%= success_msg %>
    </div>
    <% } %>

    //signup.ejs
    <% if(errors){ %>
    <% errors.forEach(function(error){ %>
    <div class="error"><%= error.msg %></div>
    <% }) %>
    <% } %>

This is it on how to implement passportJS to your express app. A lot of code is the same from the library’s document. I recommend you going to each individual library and read their docs. This post is to show you on how to implement them together.