There's more...

One of the trickiest parts of working with authentication is debugging it. Luckily, we can update our custom Morgan logging middleware to log details about authenticated user behaviors.

By adding custom tokens for email and role, we can automatically log these properties on authenticated requests. We can also provide the callback skip to Morgan to tell it to only log requests that have an authorized user session on them already:

var fs = require('fs');
var path = require('path');
var JSONAPIError = require('jsonapi-serializer').Error;

module.exports = {
logger: function(morgan, filename) {
if (!filename) filename = 'admin.log';
var adminLogFilePath = path.resolve(__dirname, "../", filename);
var adminLogStream = fs.createWriteStream(adminLogFilePath, {flags: 'a'});

morgan.token('role', function (req, res) {
return req.session.user.role;
});

morgan.token('email', function (req, res) {

return req.session.user.email;
})
;

return morgan(':email :role - :method :status :url', {
skip: function (req, res) {
return !req.session.user
}
,
stream: adminLogStream
});
},
...
};

Then, we can add this custom logger after our normal application logger in our /app.js Express configuration:

app.use(logger('short'));
app.use(auth.logger(logger));

Now, our user's behavior in our application will be logged to an /admin.log file in our application and will include their username and role for each request.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.184.122