You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.8 KiB

  1. const jwt = require('jsonwebtoken')
  2. const moment = require('moment')
  3. const securityHelper = require('../helpers/security')
  4. /* global WIKI */
  5. /**
  6. * Authentication middleware
  7. */
  8. module.exports = {
  9. jwt(req, res, next) {
  10. WIKI.auth.passport.authenticate('jwt', {session: false}, async (err, user, info) => {
  11. if (err) { return next() }
  12. // Expired but still valid within 7 days, just renew
  13. if (info instanceof jwt.TokenExpiredError && moment().subtract(14, 'days').isBefore(info.expiredAt)) {
  14. const jwtPayload = jwt.decode(securityHelper.extractJWT(req))
  15. try {
  16. const newToken = await WIKI.models.users.refreshToken(jwtPayload.id)
  17. user = newToken.user
  18. // Try headers, otherwise cookies for response
  19. if (req.get('content-type') === 'application/json') {
  20. res.set('new-jwt', newToken.token)
  21. } else {
  22. res.cookie('jwt', newToken.token, { expires: moment().add(365, 'days').toDate() })
  23. }
  24. } catch (err) {
  25. return next()
  26. }
  27. }
  28. // JWT is NOT valid
  29. if (!user) { return next() }
  30. // JWT is valid
  31. req.logIn(user, { session: false }, (err) => {
  32. if (err) { return next(err) }
  33. next()
  34. })
  35. })(req, res, next)
  36. },
  37. checkPath(req, res, next) {
  38. // Is user authenticated ?
  39. if (!req.isAuthenticated()) {
  40. if (WIKI.config.public !== true) {
  41. return res.redirect('/login')
  42. } else {
  43. // req.user = rights.guest
  44. res.locals.isGuest = true
  45. }
  46. } else {
  47. res.locals.isGuest = false
  48. }
  49. // Check permissions
  50. // res.locals.rights = rights.check(req)
  51. // if (!res.locals.rights.read) {
  52. // return res.render('error-forbidden')
  53. // }
  54. // Expose user data
  55. res.locals.user = req.user
  56. return next()
  57. }
  58. }