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.

245 lines
7.2 KiB

5 years ago
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. try {
  69. strategy.icon = await fs.readFile(path.join(WIKI.ROOTPATH, `assets/svg/auth-icon-${strategy.key}.svg`), 'utf8')
  70. } catch (err) {
  71. if (err.code === 'ENOENT') {
  72. strategy.icon = '[missing icon]'
  73. } else {
  74. WIKI.logger.warn(err)
  75. }
  76. }
  77. WIKI.auth.strategies[stg.key] = strategy
  78. WIKI.logger.info(`Authentication Strategy ${stg.key}: [ OK ]`)
  79. }
  80. } catch (err) {
  81. WIKI.logger.error(`Authentication Strategy: [ FAILED ]`)
  82. WIKI.logger.error(err)
  83. }
  84. },
  85. /**
  86. * Authenticate current request
  87. *
  88. * @param {Express Request} req
  89. * @param {Express Response} res
  90. * @param {Express Next Callback} next
  91. */
  92. authenticate(req, res, next) {
  93. WIKI.auth.passport.authenticate('jwt', {session: false}, async (err, user, info) => {
  94. if (err) { return next() }
  95. // Expired but still valid within N days, just renew
  96. if (info instanceof Error && info.name === 'TokenExpiredError' && moment().subtract(14, 'days').isBefore(info.expiredAt)) {
  97. const jwtPayload = jwt.decode(securityHelper.extractJWT(req))
  98. try {
  99. const newToken = await WIKI.models.users.refreshToken(jwtPayload.id)
  100. user = newToken.user
  101. req.user = user
  102. // Try headers, otherwise cookies for response
  103. if (req.get('content-type') === 'application/json') {
  104. res.set('new-jwt', newToken.token)
  105. } else {
  106. res.cookie('jwt', newToken.token, { expires: moment().add(365, 'days').toDate() })
  107. }
  108. } catch (err) {
  109. WIKI.logger.warn(err)
  110. return next()
  111. }
  112. }
  113. // JWT is NOT valid, set as guest
  114. if (!user) {
  115. if (WIKI.auth.guest.cacheExpiration.isSameOrBefore(moment.utc())) {
  116. WIKI.auth.guest = await WIKI.models.users.getGuestUser()
  117. WIKI.auth.guest.cacheExpiration = moment.utc().add(1, 'm')
  118. }
  119. req.user = WIKI.auth.guest
  120. return next()
  121. }
  122. // JWT is valid
  123. req.logIn(user, { session: false }, (err) => {
  124. if (err) { return next(err) }
  125. next()
  126. })
  127. })(req, res, next)
  128. },
  129. /**
  130. * Check if user has access to resource
  131. *
  132. * @param {User} user
  133. * @param {Array<String>} permissions
  134. * @param {String|Boolean} path
  135. */
  136. checkAccess(user, permissions = [], page = false) {
  137. const userPermissions = user.permissions ? user.permissions : user.getGlobalPermissions()
  138. // System Admin
  139. if (_.includes(userPermissions, 'manage:system')) {
  140. return true
  141. }
  142. // Check Global Permissions
  143. if (_.intersection(userPermissions, permissions).length < 1) {
  144. return false
  145. }
  146. // Check Page Rules
  147. if (path && user.groups) {
  148. let checkState = {
  149. deny: false,
  150. match: false,
  151. specificity: ''
  152. }
  153. user.groups.forEach(grp => {
  154. const grpId = _.isObject(grp) ? _.get(grp, 'id', 0) : grp
  155. _.get(WIKI.auth.groups, `${grpId}.pageRules`, []).forEach(rule => {
  156. switch (rule.match) {
  157. case 'START':
  158. if (_.startsWith(`/${page.path}`, `/${rule.path}`)) {
  159. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['END', 'REGEX', 'EXACT'] })
  160. }
  161. break
  162. case 'END':
  163. if (_.endsWith(page.path, rule.path)) {
  164. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['REGEX', 'EXACT'] })
  165. }
  166. break
  167. case 'REGEX':
  168. const reg = new RegExp(rule.path)
  169. if (reg.test(page.path)) {
  170. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['EXACT'] })
  171. }
  172. break
  173. case 'EXACT':
  174. if (`/${page.path}` === `/${rule.path}`) {
  175. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: [] })
  176. }
  177. break
  178. }
  179. })
  180. })
  181. return (checkState.match && !checkState.deny)
  182. }
  183. return false
  184. },
  185. /**
  186. * Check and apply Page Rule specificity
  187. *
  188. * @access private
  189. */
  190. _applyPageRuleSpecificity ({ rule, checkState, higherPriority = [] }) {
  191. if (rule.path.length === checkState.specificity.length) {
  192. // Do not override higher priority rules
  193. if (_.includes(higherPriority, checkState.match)) {
  194. return checkState
  195. }
  196. // Do not override a previous DENY rule with same match
  197. if (rule.match === checkState.match && checkState.deny && !rule.deny) {
  198. return checkState
  199. }
  200. } else if (rule.path.length < checkState.specificity.length) {
  201. // Do not override higher specificity rules
  202. return checkState
  203. }
  204. return {
  205. deny: rule.deny,
  206. match: rule.match,
  207. specificity: rule.path
  208. }
  209. },
  210. /**
  211. * Reload Groups from DB
  212. */
  213. async reloadGroups() {
  214. const groupsArray = await WIKI.models.groups.query()
  215. this.groups = _.keyBy(groupsArray, 'id')
  216. }
  217. }