wikijs-fork/server/middlewares/auth.js

73 lines
1.8 KiB
JavaScript
Raw Normal View History

const jwt = require('jsonwebtoken')
const moment = require('moment')
const securityHelper = require('../helpers/security')
/* global WIKI */
2017-04-02 23:56:47 +00:00
2016-08-17 00:56:55 +00:00
/**
* Authentication middleware
*/
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
if (info instanceof Error && info.name === 'TokenExpiredError' && moment().subtract(14, 'days').isBefore(info.expiredAt)) {
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') {
res.set('new-jwt', newToken.token)
} else {
res.cookie('jwt', newToken.token, { expires: moment().add(365, 'days').toDate() })
}
} catch (err) {
return next()
}
}
2016-08-17 00:56:55 +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 {
res.locals.isGuest = false
2017-04-02 23:56:47 +00:00
}
2016-08-17 00:56:55 +00:00
// Check permissions
2016-08-17 00:56:55 +00:00
// res.locals.rights = rights.check(req)
2017-04-02 23:56:47 +00:00
// if (!res.locals.rights.read) {
// return res.render('error-forbidden')
// }
// Expose user data
2016-08-17 00:56:55 +00:00
res.locals.user = req.user
2016-08-17 00:56:55 +00:00
return next()
}
2017-02-09 01:52:37 +00:00
}