wikijs-fork/server/middlewares/auth.js

51 lines
1.1 KiB
JavaScript
Raw Normal View History

2017-02-09 01:52:37 +00:00
'use strict'
2016-08-17 00:56:55 +00:00
2017-04-02 23:56:47 +00:00
/* global appdata, rights */
2017-02-09 01:52:37 +00:00
const moment = require('moment-timezone')
2016-08-17 00:56:55 +00:00
/**
* Authentication middleware
*
* @param {Express Request} req Express Request object
* @param {Express Response} res Express Response object
* @param {Function} next Next callback function
* @return {any} void
*/
module.exports = (req, res, next) => {
2017-02-09 01:52:37 +00:00
// Is user authenticated ?
2016-08-17 00:56:55 +00:00
2017-02-09 01:52:37 +00:00
if (!req.isAuthenticated()) {
2017-04-02 23:56:47 +00:00
if (!appdata.capabilities.guest || req.app.locals.appconfig.public !== true) {
return res.redirect('/login')
} else {
req.user = rights.guest
res.locals.isGuest = true
}
} else if (appdata.capabilities.guest) {
res.locals.isGuest = false
2017-02-09 01:52:37 +00:00
}
2016-08-17 00:56:55 +00:00
2017-02-09 01:52:37 +00:00
// Check permissions
2016-08-17 00:56:55 +00:00
2017-04-02 23:56:47 +00:00
if (appdata.capabilities.rights) {
res.locals.rights = rights.check(req)
if (!res.locals.rights.read) {
return res.render('error-forbidden')
}
2017-02-09 01:52:37 +00:00
}
2017-02-09 01:52:37 +00:00
// Set i18n locale
2017-02-09 01:52:37 +00:00
req.i18n.changeLanguage(req.user.lang)
res.locals.userMoment = moment
res.locals.userMoment.locale(req.user.lang)
2016-08-17 00:56:55 +00:00
2017-02-09 01:52:37 +00:00
// Expose user data
2016-08-17 00:56:55 +00:00
2017-02-09 01:52:37 +00:00
res.locals.user = req.user
2016-08-17 00:56:55 +00:00
2017-02-09 01:52:37 +00:00
return next()
}