auth.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. const passport = require('passport')
  2. const passportJWT = require('passport-jwt')
  3. const _ = require('lodash')
  4. const jwt = require('jsonwebtoken')
  5. const moment = require('moment')
  6. const Promise = require('bluebird')
  7. const crypto = Promise.promisifyAll(require('crypto'))
  8. const pem2jwk = require('pem-jwk').pem2jwk
  9. const securityHelper = require('../helpers/security')
  10. /* global WIKI */
  11. module.exports = {
  12. strategies: {},
  13. guest: {
  14. cacheExpiration: moment.utc().subtract(1, 'd')
  15. },
  16. groups: {},
  17. validApiKeys: [],
  18. /**
  19. * Initialize the authentication module
  20. */
  21. init() {
  22. this.passport = passport
  23. passport.serializeUser((user, done) => {
  24. done(null, user.id)
  25. })
  26. passport.deserializeUser(async (id, done) => {
  27. try {
  28. const user = await WIKI.models.users.query().findById(id).withGraphFetched('groups').modifyGraph('groups', builder => {
  29. builder.select('groups.id', 'permissions')
  30. })
  31. if (user) {
  32. done(null, user)
  33. } else {
  34. done(new Error(WIKI.lang.t('auth:errors:usernotfound')), null)
  35. }
  36. } catch (err) {
  37. done(err, null)
  38. }
  39. })
  40. this.reloadGroups()
  41. this.reloadApiKeys()
  42. return this
  43. },
  44. /**
  45. * Load authentication strategies
  46. */
  47. async activateStrategies() {
  48. try {
  49. // Unload any active strategies
  50. WIKI.auth.strategies = {}
  51. const currentStrategies = _.keys(passport._strategies)
  52. _.pull(currentStrategies, 'session')
  53. _.forEach(currentStrategies, stg => { passport.unuse(stg) })
  54. // Load JWT
  55. passport.use('jwt', new passportJWT.Strategy({
  56. jwtFromRequest: securityHelper.extractJWT,
  57. secretOrKey: WIKI.config.certs.public,
  58. audience: WIKI.config.auth.audience,
  59. issuer: 'urn:wiki.js',
  60. algorithms: ['RS256']
  61. }, (jwtPayload, cb) => {
  62. cb(null, jwtPayload)
  63. }))
  64. // Load enabled strategies
  65. const enabledStrategies = await WIKI.models.authentication.getStrategies()
  66. for (let idx in enabledStrategies) {
  67. const stg = enabledStrategies[idx]
  68. if (!stg.isEnabled) { continue }
  69. const strategy = require(`../modules/authentication/${stg.key}/authentication.js`)
  70. stg.config.callbackURL = `${WIKI.config.host}/login/${stg.key}/callback`
  71. strategy.init(passport, stg.config)
  72. strategy.config = stg.config
  73. WIKI.auth.strategies[stg.key] = {
  74. ...strategy,
  75. ...stg
  76. }
  77. WIKI.logger.info(`Authentication Strategy ${stg.key}: [ OK ]`)
  78. }
  79. } catch (err) {
  80. WIKI.logger.error(`Authentication Strategy: [ FAILED ]`)
  81. WIKI.logger.error(err)
  82. }
  83. },
  84. /**
  85. * Authenticate current request
  86. *
  87. * @param {Express Request} req
  88. * @param {Express Response} res
  89. * @param {Express Next Callback} next
  90. */
  91. authenticate(req, res, next) {
  92. WIKI.auth.passport.authenticate('jwt', {session: false}, async (err, user, info) => {
  93. if (err) { return next() }
  94. // Expired but still valid within N days, just renew
  95. if (info instanceof Error && info.name === 'TokenExpiredError' && moment().subtract(14, 'days').isBefore(info.expiredAt)) {
  96. const jwtPayload = jwt.decode(securityHelper.extractJWT(req))
  97. try {
  98. const newToken = await WIKI.models.users.refreshToken(jwtPayload.id)
  99. user = newToken.user
  100. user.permissions = user.getGlobalPermissions()
  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 (errc) {
  109. WIKI.logger.warn(errc)
  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. // Process API tokens
  123. if (_.has(user, 'api')) {
  124. if (_.includes(WIKI.auth.validApiKeys, user.api)) {
  125. req.user = {
  126. id: 1,
  127. email: 'api@localhost',
  128. name: 'API',
  129. pictureUrl: null,
  130. timezone: 'America/New_York',
  131. localeCode: 'en',
  132. permissions: _.get(WIKI.auth.groups, `${user.grp}.permissions`, []),
  133. groups: [user.grp],
  134. getGlobalPermissions () {
  135. return req.user.permissions
  136. },
  137. getGroups () {
  138. return req.user.groups
  139. }
  140. }
  141. return next()
  142. } else {
  143. return next(new Error('API Key is invalid or was revoked.'))
  144. }
  145. }
  146. // JWT is valid
  147. req.logIn(user, { session: false }, (errc) => {
  148. if (errc) { return next(errc) }
  149. next()
  150. })
  151. })(req, res, next)
  152. },
  153. /**
  154. * Check if user has access to resource
  155. *
  156. * @param {User} user
  157. * @param {Array<String>} permissions
  158. * @param {String|Boolean} path
  159. */
  160. checkAccess(user, permissions = [], page = false) {
  161. const userPermissions = user.permissions ? user.permissions : user.getGlobalPermissions()
  162. // System Admin
  163. if (_.includes(userPermissions, 'manage:system')) {
  164. return true
  165. }
  166. // Check Global Permissions
  167. if (_.intersection(userPermissions, permissions).length < 1) {
  168. return false
  169. }
  170. // Check Page Rules
  171. if (page && user.groups) {
  172. let checkState = {
  173. deny: false,
  174. match: false,
  175. specificity: ''
  176. }
  177. user.groups.forEach(grp => {
  178. const grpId = _.isObject(grp) ? _.get(grp, 'id', 0) : grp
  179. _.get(WIKI.auth.groups, `${grpId}.pageRules`, []).forEach(rule => {
  180. if (_.intersection(rule.roles, permissions).length > 0) {
  181. switch (rule.match) {
  182. case 'START':
  183. if (_.startsWith(`/${page.path}`, `/${rule.path}`)) {
  184. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['END', 'REGEX', 'EXACT', 'TAG'] })
  185. }
  186. break
  187. case 'END':
  188. if (_.endsWith(page.path, rule.path)) {
  189. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['REGEX', 'EXACT', 'TAG'] })
  190. }
  191. break
  192. case 'REGEX':
  193. const reg = new RegExp(rule.path)
  194. if (reg.test(page.path)) {
  195. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['EXACT', 'TAG'] })
  196. }
  197. break
  198. case 'TAG':
  199. _.get(page, 'tags', []).forEach(tag => {
  200. if (tag.tag === rule.path) {
  201. checkState = this._applyPageRuleSpecificity({
  202. rule,
  203. checkState,
  204. higherPriority: ['EXACT']
  205. })
  206. }
  207. })
  208. break
  209. case 'EXACT':
  210. if (`/${page.path}` === `/${rule.path}`) {
  211. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: [] })
  212. }
  213. break
  214. }
  215. }
  216. })
  217. })
  218. return (checkState.match && !checkState.deny)
  219. }
  220. return false
  221. },
  222. /**
  223. * Check and apply Page Rule specificity
  224. *
  225. * @access private
  226. */
  227. _applyPageRuleSpecificity ({ rule, checkState, higherPriority = [] }) {
  228. if (rule.path.length === checkState.specificity.length) {
  229. // Do not override higher priority rules
  230. if (_.includes(higherPriority, checkState.match)) {
  231. return checkState
  232. }
  233. // Do not override a previous DENY rule with same match
  234. if (rule.match === checkState.match && checkState.deny && !rule.deny) {
  235. return checkState
  236. }
  237. } else if (rule.path.length < checkState.specificity.length) {
  238. // Do not override higher specificity rules
  239. return checkState
  240. }
  241. return {
  242. deny: rule.deny,
  243. match: rule.match,
  244. specificity: rule.path
  245. }
  246. },
  247. /**
  248. * Reload Groups from DB
  249. */
  250. async reloadGroups () {
  251. const groupsArray = await WIKI.models.groups.query()
  252. this.groups = _.keyBy(groupsArray, 'id')
  253. },
  254. /**
  255. * Reload valid API Keys from DB
  256. */
  257. async reloadApiKeys () {
  258. const keys = await WIKI.models.apiKeys.query().select('id').where('isRevoked', false).andWhere('expiration', '>', moment.utc().toISOString())
  259. this.validApiKeys = _.map(keys, 'id')
  260. },
  261. /**
  262. * Generate New Authentication Public / Private Key Certificates
  263. */
  264. async regenerateCertificates () {
  265. WIKI.logger.info('Regenerating certificates...')
  266. _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
  267. const certs = crypto.generateKeyPairSync('rsa', {
  268. modulusLength: 2048,
  269. publicKeyEncoding: {
  270. type: 'pkcs1',
  271. format: 'pem'
  272. },
  273. privateKeyEncoding: {
  274. type: 'pkcs1',
  275. format: 'pem',
  276. cipher: 'aes-256-cbc',
  277. passphrase: WIKI.config.sessionSecret
  278. }
  279. })
  280. _.set(WIKI.config, 'certs', {
  281. jwk: pem2jwk(certs.publicKey),
  282. public: certs.publicKey,
  283. private: certs.privateKey
  284. })
  285. await WIKI.configSvc.saveToDb([
  286. 'certs',
  287. 'sessionSecret'
  288. ])
  289. await WIKI.auth.activateStrategies()
  290. WIKI.logger.info('Regenerated certificates: [ COMPLETED ]')
  291. },
  292. /**
  293. * Reset Guest User
  294. */
  295. async resetGuestUser() {
  296. WIKI.logger.info('Resetting guest account...')
  297. const guestGroup = await WIKI.models.groups.query().where('id', 2).first()
  298. await WIKI.models.users.query().delete().where({
  299. providerKey: 'local',
  300. email: 'guest@example.com'
  301. }).orWhere('id', 2)
  302. const guestUser = await WIKI.models.users.query().insert({
  303. id: 2,
  304. provider: 'local',
  305. email: 'guest@example.com',
  306. name: 'Guest',
  307. password: '',
  308. locale: 'en',
  309. defaultEditor: 'markdown',
  310. tfaIsActive: false,
  311. isSystem: true,
  312. isActive: true,
  313. isVerified: true
  314. })
  315. await guestUser.$relatedQuery('groups').relate(guestGroup.id)
  316. WIKI.logger.info('Guest user has been reset: [ COMPLETED ]')
  317. }
  318. }