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.

241 lines
7.0 KiB

5 years ago
  1. const passport = require('passport')
  2. const passportJWT = require('passport-jwt')
  3. const fs = require('fs-extra')
  4. const _ = require('lodash')
  5. const path = require('path')
  6. const jwt = require('jsonwebtoken')
  7. const moment = require('moment')
  8. const securityHelper = require('../helpers/security')
  9. /* global WIKI */
  10. module.exports = {
  11. strategies: {},
  12. guest: {
  13. cacheExpiration: moment.utc().subtract(1, 'd')
  14. },
  15. groups: {},
  16. /**
  17. * Initialize the authentication module
  18. */
  19. init() {
  20. this.passport = passport
  21. passport.serializeUser((user, done) => {
  22. done(null, user.id)
  23. })
  24. passport.deserializeUser(async (id, done) => {
  25. try {
  26. const user = await WIKI.models.users.query().findById(id).modifyEager('groups', builder => {
  27. builder.select('groups.id', 'permissions')
  28. })
  29. if (user) {
  30. done(null, user)
  31. } else {
  32. done(new Error(WIKI.lang.t('auth:errors:usernotfound')), null)
  33. }
  34. } catch (err) {
  35. done(err, null)
  36. }
  37. })
  38. this.reloadGroups()
  39. return this
  40. },
  41. /**
  42. * Load authentication strategies
  43. */
  44. async activateStrategies() {
  45. try {
  46. // Unload any active strategies
  47. WIKI.auth.strategies = {}
  48. const currentStrategies = _.keys(passport._strategies)
  49. _.pull(currentStrategies, 'session')
  50. _.forEach(currentStrategies, stg => { passport.unuse(stg) })
  51. // Load JWT
  52. passport.use('jwt', new passportJWT.Strategy({
  53. jwtFromRequest: securityHelper.extractJWT,
  54. secretOrKey: WIKI.config.certs.public,
  55. audience: WIKI.config.auth.audience,
  56. issuer: 'urn:wiki.js'
  57. }, (jwtPayload, cb) => {
  58. cb(null, jwtPayload)
  59. }))
  60. // Load enabled strategies
  61. const enabledStrategies = await WIKI.models.authentication.getStrategies()
  62. for (let idx in enabledStrategies) {
  63. const stg = enabledStrategies[idx]
  64. if (!stg.isEnabled) { continue }
  65. const strategy = require(`../modules/authentication/${stg.key}/authentication.js`)
  66. stg.config.callbackURL = `${WIKI.config.host}/login/${stg.key}/callback`
  67. strategy.init(passport, stg.config)
  68. strategy.config = stg.config
  69. WIKI.auth.strategies[stg.key] = {
  70. ...strategy,
  71. ...stg
  72. }
  73. WIKI.logger.info(`Authentication Strategy ${stg.key}: [ OK ]`)
  74. }
  75. } catch (err) {
  76. WIKI.logger.error(`Authentication Strategy: [ FAILED ]`)
  77. WIKI.logger.error(err)
  78. }
  79. },
  80. /**
  81. * Authenticate current request
  82. *
  83. * @param {Express Request} req
  84. * @param {Express Response} res
  85. * @param {Express Next Callback} next
  86. */
  87. authenticate(req, res, next) {
  88. WIKI.auth.passport.authenticate('jwt', {session: false}, async (err, user, info) => {
  89. if (err) { return next() }
  90. // Expired but still valid within N days, just renew
  91. if (info instanceof Error && info.name === 'TokenExpiredError' && moment().subtract(14, 'days').isBefore(info.expiredAt)) {
  92. const jwtPayload = jwt.decode(securityHelper.extractJWT(req))
  93. try {
  94. const newToken = await WIKI.models.users.refreshToken(jwtPayload.id)
  95. user = newToken.user
  96. user.permissions = user.getGlobalPermissions()
  97. req.user = user
  98. // Try headers, otherwise cookies for response
  99. if (req.get('content-type') === 'application/json') {
  100. res.set('new-jwt', newToken.token)
  101. } else {
  102. res.cookie('jwt', newToken.token, { expires: moment().add(365, 'days').toDate() })
  103. }
  104. } catch (err) {
  105. WIKI.logger.warn(err)
  106. return next()
  107. }
  108. }
  109. // JWT is NOT valid, set as guest
  110. if (!user) {
  111. if (WIKI.auth.guest.cacheExpiration.isSameOrBefore(moment.utc())) {
  112. WIKI.auth.guest = await WIKI.models.users.getGuestUser()
  113. WIKI.auth.guest.cacheExpiration = moment.utc().add(1, 'm')
  114. }
  115. req.user = WIKI.auth.guest
  116. return next()
  117. }
  118. // JWT is valid
  119. req.logIn(user, { session: false }, (err) => {
  120. if (err) { return next(err) }
  121. next()
  122. })
  123. })(req, res, next)
  124. },
  125. /**
  126. * Check if user has access to resource
  127. *
  128. * @param {User} user
  129. * @param {Array<String>} permissions
  130. * @param {String|Boolean} path
  131. */
  132. checkAccess(user, permissions = [], page = false) {
  133. const userPermissions = user.permissions ? user.permissions : user.getGlobalPermissions()
  134. // System Admin
  135. if (_.includes(userPermissions, 'manage:system')) {
  136. return true
  137. }
  138. // Check Global Permissions
  139. if (_.intersection(userPermissions, permissions).length < 1) {
  140. return false
  141. }
  142. // Check Page Rules
  143. if (path && user.groups) {
  144. let checkState = {
  145. deny: false,
  146. match: false,
  147. specificity: ''
  148. }
  149. user.groups.forEach(grp => {
  150. const grpId = _.isObject(grp) ? _.get(grp, 'id', 0) : grp
  151. _.get(WIKI.auth.groups, `${grpId}.pageRules`, []).forEach(rule => {
  152. switch (rule.match) {
  153. case 'START':
  154. if (_.startsWith(`/${page.path}`, `/${rule.path}`)) {
  155. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['END', 'REGEX', 'EXACT'] })
  156. }
  157. break
  158. case 'END':
  159. if (_.endsWith(page.path, rule.path)) {
  160. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['REGEX', 'EXACT'] })
  161. }
  162. break
  163. case 'REGEX':
  164. const reg = new RegExp(rule.path)
  165. if (reg.test(page.path)) {
  166. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['EXACT'] })
  167. }
  168. break
  169. case 'EXACT':
  170. if (`/${page.path}` === `/${rule.path}`) {
  171. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: [] })
  172. }
  173. break
  174. }
  175. })
  176. })
  177. return (checkState.match && !checkState.deny)
  178. }
  179. return false
  180. },
  181. /**
  182. * Check and apply Page Rule specificity
  183. *
  184. * @access private
  185. */
  186. _applyPageRuleSpecificity ({ rule, checkState, higherPriority = [] }) {
  187. if (rule.path.length === checkState.specificity.length) {
  188. // Do not override higher priority rules
  189. if (_.includes(higherPriority, checkState.match)) {
  190. return checkState
  191. }
  192. // Do not override a previous DENY rule with same match
  193. if (rule.match === checkState.match && checkState.deny && !rule.deny) {
  194. return checkState
  195. }
  196. } else if (rule.path.length < checkState.specificity.length) {
  197. // Do not override higher specificity rules
  198. return checkState
  199. }
  200. return {
  201. deny: rule.deny,
  202. match: rule.match,
  203. specificity: rule.path
  204. }
  205. },
  206. /**
  207. * Reload Groups from DB
  208. */
  209. async reloadGroups() {
  210. const groupsArray = await WIKI.models.groups.query()
  211. this.groups = _.keyBy(groupsArray, 'id')
  212. }
  213. }