2018-10-08 04:17:31 +00:00
|
|
|
const jwt = require('jsonwebtoken')
|
|
|
|
const moment = require('moment')
|
|
|
|
|
|
|
|
const securityHelper = require('../helpers/security')
|
|
|
|
|
2018-03-05 20:49:36 +00:00
|
|
|
/* global WIKI */
|
2017-04-02 23:56:47 +00:00
|
|
|
|
2016-08-17 00:56:55 +00:00
|
|
|
/**
|
|
|
|
* Authentication middleware
|
|
|
|
*/
|
2018-10-08 04:17:31 +00:00
|
|
|
module.exports = {
|
|
|
|
jwt(req, res, next) {
|
|
|
|
WIKI.auth.passport.authenticate('jwt', {session: false}, async (err, user, info) => {
|
|
|
|
if (err) { return next() }
|
|
|
|
|
|
|
|
// Expired but still valid within 7 days, just renew
|
2018-10-13 03:14:11 +00:00
|
|
|
if (info instanceof jwt.TokenExpiredError && moment().subtract(14, 'days').isBefore(info.expiredAt)) {
|
2018-10-08 04:17:31 +00:00
|
|
|
const jwtPayload = jwt.decode(securityHelper.extractJWT(req))
|
|
|
|
try {
|
|
|
|
const newToken = await WIKI.models.users.refreshToken(jwtPayload.id)
|
|
|
|
user = newToken.user
|
|
|
|
|
|
|
|
// Try headers, otherwise cookies for response
|
|
|
|
if (req.get('content-type') === 'application/json') {
|
2018-10-14 03:22:42 +00:00
|
|
|
res.set('new-jwt', newToken.token)
|
2018-10-08 04:17:31 +00:00
|
|
|
} else {
|
2018-10-13 03:14:11 +00:00
|
|
|
res.cookie('jwt', newToken.token, { expires: moment().add(365, 'days').toDate() })
|
2018-10-08 04:17:31 +00:00
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
}
|
2016-08-17 00:56:55 +00:00
|
|
|
|
2018-10-08 04:17:31 +00:00
|
|
|
// JWT is NOT valid
|
|
|
|
if (!user) { return next() }
|
|
|
|
|
|
|
|
// JWT is valid
|
|
|
|
req.logIn(user, { session: false }, (err) => {
|
|
|
|
if (err) { return next(err) }
|
|
|
|
next()
|
|
|
|
})
|
|
|
|
})(req, res, next)
|
|
|
|
},
|
|
|
|
checkPath(req, res, next) {
|
|
|
|
// Is user authenticated ?
|
|
|
|
|
|
|
|
if (!req.isAuthenticated()) {
|
|
|
|
if (WIKI.config.public !== true) {
|
|
|
|
return res.redirect('/login')
|
|
|
|
} else {
|
|
|
|
// req.user = rights.guest
|
|
|
|
res.locals.isGuest = true
|
|
|
|
}
|
2017-04-02 23:56:47 +00:00
|
|
|
} else {
|
2018-10-08 04:17:31 +00:00
|
|
|
res.locals.isGuest = false
|
2017-04-02 23:56:47 +00:00
|
|
|
}
|
2016-08-17 00:56:55 +00:00
|
|
|
|
2018-10-08 04:17:31 +00:00
|
|
|
// Check permissions
|
2016-08-17 00:56:55 +00:00
|
|
|
|
2018-10-08 04:17:31 +00:00
|
|
|
// res.locals.rights = rights.check(req)
|
2017-04-02 23:56:47 +00:00
|
|
|
|
2018-10-08 04:17:31 +00:00
|
|
|
// if (!res.locals.rights.read) {
|
|
|
|
// return res.render('error-forbidden')
|
|
|
|
// }
|
2016-11-01 02:44:00 +00:00
|
|
|
|
2018-10-08 04:17:31 +00:00
|
|
|
// Expose user data
|
2016-08-17 00:56:55 +00:00
|
|
|
|
2018-10-08 04:17:31 +00:00
|
|
|
res.locals.user = req.user
|
2016-08-17 00:56:55 +00:00
|
|
|
|
2018-10-08 04:17:31 +00:00
|
|
|
return next()
|
|
|
|
}
|
2017-02-09 01:52:37 +00:00
|
|
|
}
|