auth.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  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. try {
  70. const strategy = require(`../modules/authentication/${stg.key}/authentication.js`)
  71. stg.config.callbackURL = `${WIKI.config.host}/login/${stg.key}/callback`
  72. strategy.init(passport, stg.config)
  73. strategy.config = stg.config
  74. WIKI.auth.strategies[stg.key] = {
  75. ...strategy,
  76. ...stg
  77. }
  78. WIKI.logger.info(`Authentication Strategy ${stg.key}: [ OK ]`)
  79. } catch (err) {
  80. WIKI.logger.error(`Authentication Strategy ${stg.key}: [ FAILED ]`)
  81. WIKI.logger.error(err)
  82. }
  83. }
  84. } catch (err) {
  85. WIKI.logger.error(`Failed to initialize Authentication Strategies: [ ERROR ]`)
  86. WIKI.logger.error(err)
  87. }
  88. },
  89. /**
  90. * Authenticate current request
  91. *
  92. * @param {Express Request} req
  93. * @param {Express Response} res
  94. * @param {Express Next Callback} next
  95. */
  96. authenticate(req, res, next) {
  97. WIKI.auth.passport.authenticate('jwt', {session: false}, async (err, user, info) => {
  98. if (err) { return next() }
  99. // Expired but still valid within N days, just renew
  100. if (info instanceof Error && info.name === 'TokenExpiredError' && moment().subtract(14, 'days').isBefore(info.expiredAt)) {
  101. const jwtPayload = jwt.decode(securityHelper.extractJWT(req))
  102. try {
  103. const newToken = await WIKI.models.users.refreshToken(jwtPayload.id)
  104. user = newToken.user
  105. user.permissions = user.getGlobalPermissions()
  106. req.user = user
  107. // Try headers, otherwise cookies for response
  108. if (req.get('content-type') === 'application/json') {
  109. res.set('new-jwt', newToken.token)
  110. } else {
  111. res.cookie('jwt', newToken.token, { expires: moment().add(365, 'days').toDate() })
  112. }
  113. } catch (errc) {
  114. WIKI.logger.warn(errc)
  115. return next()
  116. }
  117. }
  118. // JWT is NOT valid, set as guest
  119. if (!user) {
  120. if (WIKI.auth.guest.cacheExpiration.isSameOrBefore(moment.utc())) {
  121. WIKI.auth.guest = await WIKI.models.users.getGuestUser()
  122. WIKI.auth.guest.cacheExpiration = moment.utc().add(1, 'm')
  123. }
  124. req.user = WIKI.auth.guest
  125. return next()
  126. }
  127. // Process API tokens
  128. if (_.has(user, 'api')) {
  129. if (!WIKI.config.api.isEnabled) {
  130. return next(new Error('API is disabled. You must enable it from the Administration Area first.'))
  131. } else if (_.includes(WIKI.auth.validApiKeys, user.api)) {
  132. req.user = {
  133. id: 1,
  134. email: 'api@localhost',
  135. name: 'API',
  136. pictureUrl: null,
  137. timezone: 'America/New_York',
  138. localeCode: 'en',
  139. permissions: _.get(WIKI.auth.groups, `${user.grp}.permissions`, []),
  140. groups: [user.grp],
  141. getGlobalPermissions () {
  142. return req.user.permissions
  143. },
  144. getGroups () {
  145. return req.user.groups
  146. }
  147. }
  148. return next()
  149. } else {
  150. return next(new Error('API Key is invalid or was revoked.'))
  151. }
  152. }
  153. // JWT is valid
  154. req.logIn(user, { session: false }, (errc) => {
  155. if (errc) { return next(errc) }
  156. next()
  157. })
  158. })(req, res, next)
  159. },
  160. /**
  161. * Check if user has access to resource
  162. *
  163. * @param {User} user
  164. * @param {Array<String>} permissions
  165. * @param {String|Boolean} path
  166. */
  167. checkAccess(user, permissions = [], page = false) {
  168. const userPermissions = user.permissions ? user.permissions : user.getGlobalPermissions()
  169. // System Admin
  170. if (_.includes(userPermissions, 'manage:system')) {
  171. return true
  172. }
  173. // Check Global Permissions
  174. if (_.intersection(userPermissions, permissions).length < 1) {
  175. return false
  176. }
  177. // Check Page Rules
  178. if (page && user.groups) {
  179. let checkState = {
  180. deny: false,
  181. match: false,
  182. specificity: ''
  183. }
  184. user.groups.forEach(grp => {
  185. const grpId = _.isObject(grp) ? _.get(grp, 'id', 0) : grp
  186. _.get(WIKI.auth.groups, `${grpId}.pageRules`, []).forEach(rule => {
  187. if (_.intersection(rule.roles, permissions).length > 0) {
  188. switch (rule.match) {
  189. case 'START':
  190. if (_.startsWith(`/${page.path}`, `/${rule.path}`)) {
  191. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['END', 'REGEX', 'EXACT', 'TAG'] })
  192. }
  193. break
  194. case 'END':
  195. if (_.endsWith(page.path, rule.path)) {
  196. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['REGEX', 'EXACT', 'TAG'] })
  197. }
  198. break
  199. case 'REGEX':
  200. const reg = new RegExp(rule.path)
  201. if (reg.test(page.path)) {
  202. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['EXACT', 'TAG'] })
  203. }
  204. break
  205. case 'TAG':
  206. _.get(page, 'tags', []).forEach(tag => {
  207. if (tag.tag === rule.path) {
  208. checkState = this._applyPageRuleSpecificity({
  209. rule,
  210. checkState,
  211. higherPriority: ['EXACT']
  212. })
  213. }
  214. })
  215. break
  216. case 'EXACT':
  217. if (`/${page.path}` === `/${rule.path}`) {
  218. checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: [] })
  219. }
  220. break
  221. }
  222. }
  223. })
  224. })
  225. return (checkState.match && !checkState.deny)
  226. }
  227. return false
  228. },
  229. /**
  230. * Check and apply Page Rule specificity
  231. *
  232. * @access private
  233. */
  234. _applyPageRuleSpecificity ({ rule, checkState, higherPriority = [] }) {
  235. if (rule.path.length === checkState.specificity.length) {
  236. // Do not override higher priority rules
  237. if (_.includes(higherPriority, checkState.match)) {
  238. return checkState
  239. }
  240. // Do not override a previous DENY rule with same match
  241. if (rule.match === checkState.match && checkState.deny && !rule.deny) {
  242. return checkState
  243. }
  244. } else if (rule.path.length < checkState.specificity.length) {
  245. // Do not override higher specificity rules
  246. return checkState
  247. }
  248. return {
  249. deny: rule.deny,
  250. match: rule.match,
  251. specificity: rule.path
  252. }
  253. },
  254. /**
  255. * Reload Groups from DB
  256. */
  257. async reloadGroups () {
  258. const groupsArray = await WIKI.models.groups.query()
  259. this.groups = _.keyBy(groupsArray, 'id')
  260. WIKI.auth.guest.cacheExpiration = moment.utc().subtract(1, 'd')
  261. },
  262. /**
  263. * Reload valid API Keys from DB
  264. */
  265. async reloadApiKeys () {
  266. const keys = await WIKI.models.apiKeys.query().select('id').where('isRevoked', false).andWhere('expiration', '>', moment.utc().toISOString())
  267. this.validApiKeys = _.map(keys, 'id')
  268. },
  269. /**
  270. * Generate New Authentication Public / Private Key Certificates
  271. */
  272. async regenerateCertificates () {
  273. WIKI.logger.info('Regenerating certificates...')
  274. _.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
  275. const certs = crypto.generateKeyPairSync('rsa', {
  276. modulusLength: 2048,
  277. publicKeyEncoding: {
  278. type: 'pkcs1',
  279. format: 'pem'
  280. },
  281. privateKeyEncoding: {
  282. type: 'pkcs1',
  283. format: 'pem',
  284. cipher: 'aes-256-cbc',
  285. passphrase: WIKI.config.sessionSecret
  286. }
  287. })
  288. _.set(WIKI.config, 'certs', {
  289. jwk: pem2jwk(certs.publicKey),
  290. public: certs.publicKey,
  291. private: certs.privateKey
  292. })
  293. await WIKI.configSvc.saveToDb([
  294. 'certs',
  295. 'sessionSecret'
  296. ])
  297. await WIKI.auth.activateStrategies()
  298. WIKI.events.outbound.emit('reloadAuthStrategies')
  299. WIKI.logger.info('Regenerated certificates: [ COMPLETED ]')
  300. },
  301. /**
  302. * Reset Guest User
  303. */
  304. async resetGuestUser() {
  305. WIKI.logger.info('Resetting guest account...')
  306. const guestGroup = await WIKI.models.groups.query().where('id', 2).first()
  307. await WIKI.models.users.query().delete().where({
  308. providerKey: 'local',
  309. email: 'guest@example.com'
  310. }).orWhere('id', 2)
  311. const guestUser = await WIKI.models.users.query().insert({
  312. id: 2,
  313. provider: 'local',
  314. email: 'guest@example.com',
  315. name: 'Guest',
  316. password: '',
  317. locale: 'en',
  318. defaultEditor: 'markdown',
  319. tfaIsActive: false,
  320. isSystem: true,
  321. isActive: true,
  322. isVerified: true
  323. })
  324. await guestUser.$relatedQuery('groups').relate(guestGroup.id)
  325. WIKI.logger.info('Guest user has been reset: [ COMPLETED ]')
  326. },
  327. /**
  328. * Subscribe to HA propagation events
  329. */
  330. subscribeToEvents() {
  331. WIKI.events.inbound.on('reloadGroups', () => {
  332. WIKI.auth.reloadGroups()
  333. })
  334. WIKI.events.inbound.on('reloadApiKeys', () => {
  335. WIKI.auth.reloadApiKeys()
  336. })
  337. WIKI.events.inbound.on('reloadAuthStrategies', () => {
  338. WIKI.auth.activateStrategies()
  339. })
  340. }
  341. }