接下來我們要用一些別的套件來強化我們的認證. 我會交如何使用 connect-flash, express-validator, express-seession
我先稍微介紹每一個套件
connect-flash: 用來顯示錯誤或成功訊息.
express-validator: 用來驗證使用者的input
express-seession: 用來create session
var session = require('express-session');
var flash = require('connect-flash');
var expressValidator = require('express-validator');
// 先設定好session, 如果不懂可以看官方的教學
app.use(session({
secret: 'secret',
saveUninitialized: true,
resave: true
}));
// expressValidator設定好格式如何顯示.
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();
});
// 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')
...
})
});
//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>
<% }) %>
<% } %>