2017-09-11 03:00:03 +00:00
|
|
|
const passport = require('passport')
|
2018-10-08 04:17:31 +00:00
|
|
|
const passportJWT = require('passport-jwt')
|
2018-05-28 18:46:55 +00:00
|
|
|
const _ = require('lodash')
|
2019-01-07 03:03:34 +00:00
|
|
|
const jwt = require('jsonwebtoken')
|
|
|
|
const moment = require('moment')
|
2019-06-30 19:18:26 +00:00
|
|
|
const Promise = require('bluebird')
|
|
|
|
const crypto = Promise.promisifyAll(require('crypto'))
|
|
|
|
const pem2jwk = require('pem-jwk').pem2jwk
|
2018-08-04 21:27:55 +00:00
|
|
|
|
2018-10-08 04:17:31 +00:00
|
|
|
const securityHelper = require('../helpers/security')
|
2018-05-28 18:46:55 +00:00
|
|
|
|
|
|
|
/* global WIKI */
|
2017-04-02 23:56:47 +00:00
|
|
|
|
2017-08-03 03:47:11 +00:00
|
|
|
module.exports = {
|
2017-09-11 03:00:03 +00:00
|
|
|
strategies: {},
|
2019-01-07 03:03:34 +00:00
|
|
|
guest: {
|
|
|
|
cacheExpiration: moment.utc().subtract(1, 'd')
|
|
|
|
},
|
2019-01-12 23:33:30 +00:00
|
|
|
groups: {},
|
2019-01-07 03:03:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Initialize the authentication module
|
|
|
|
*/
|
2017-09-11 03:00:03 +00:00
|
|
|
init() {
|
|
|
|
this.passport = passport
|
|
|
|
|
2019-01-12 23:33:30 +00:00
|
|
|
passport.serializeUser((user, done) => {
|
2018-01-10 01:41:53 +00:00
|
|
|
done(null, user.id)
|
2017-08-03 03:47:11 +00:00
|
|
|
})
|
2017-04-02 23:56:47 +00:00
|
|
|
|
2019-01-12 23:33:30 +00:00
|
|
|
passport.deserializeUser(async (id, done) => {
|
|
|
|
try {
|
2020-01-25 00:20:53 +00:00
|
|
|
const user = await WIKI.models.users.query().findById(id).withGraphFetched('groups').modifyGraph('groups', builder => {
|
2019-01-12 23:33:30 +00:00
|
|
|
builder.select('groups.id', 'permissions')
|
|
|
|
})
|
2018-10-08 04:17:31 +00:00
|
|
|
if (user) {
|
|
|
|
done(null, user)
|
|
|
|
} else {
|
|
|
|
done(new Error(WIKI.lang.t('auth:errors:usernotfound')), null)
|
|
|
|
}
|
2019-01-12 23:33:30 +00:00
|
|
|
} catch (err) {
|
2018-10-08 04:17:31 +00:00
|
|
|
done(err, null)
|
2019-01-12 23:33:30 +00:00
|
|
|
}
|
2017-04-02 23:56:47 +00:00
|
|
|
})
|
|
|
|
|
2019-01-12 23:33:30 +00:00
|
|
|
this.reloadGroups()
|
|
|
|
|
2017-09-11 03:00:03 +00:00
|
|
|
return this
|
2018-05-28 18:46:55 +00:00
|
|
|
},
|
2019-01-07 03:03:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Load authentication strategies
|
|
|
|
*/
|
2018-05-28 18:46:55 +00:00
|
|
|
async activateStrategies() {
|
|
|
|
try {
|
|
|
|
// Unload any active strategies
|
2018-05-28 23:36:35 +00:00
|
|
|
WIKI.auth.strategies = {}
|
2018-05-28 18:46:55 +00:00
|
|
|
const currentStrategies = _.keys(passport._strategies)
|
|
|
|
_.pull(currentStrategies, 'session')
|
|
|
|
_.forEach(currentStrategies, stg => { passport.unuse(stg) })
|
|
|
|
|
2018-10-08 04:17:31 +00:00
|
|
|
// Load JWT
|
|
|
|
passport.use('jwt', new passportJWT.Strategy({
|
|
|
|
jwtFromRequest: securityHelper.extractJWT,
|
2018-12-03 02:42:43 +00:00
|
|
|
secretOrKey: WIKI.config.certs.public,
|
2019-01-07 03:03:34 +00:00
|
|
|
audience: WIKI.config.auth.audience,
|
2018-10-08 04:17:31 +00:00
|
|
|
issuer: 'urn:wiki.js'
|
|
|
|
}, (jwtPayload, cb) => {
|
|
|
|
cb(null, jwtPayload)
|
|
|
|
}))
|
|
|
|
|
2018-06-25 06:44:40 +00:00
|
|
|
// Load enabled strategies
|
2018-07-30 02:23:33 +00:00
|
|
|
const enabledStrategies = await WIKI.models.authentication.getStrategies()
|
2018-05-28 18:46:55 +00:00
|
|
|
for (let idx in enabledStrategies) {
|
|
|
|
const stg = enabledStrategies[idx]
|
2018-06-25 06:44:40 +00:00
|
|
|
if (!stg.isEnabled) { continue }
|
|
|
|
|
2018-07-08 15:16:45 +00:00
|
|
|
const strategy = require(`../modules/authentication/${stg.key}/authentication.js`)
|
2018-06-25 06:44:40 +00:00
|
|
|
|
2019-01-07 03:03:34 +00:00
|
|
|
stg.config.callbackURL = `${WIKI.config.host}/login/${stg.key}/callback`
|
2018-05-28 18:46:55 +00:00
|
|
|
strategy.init(passport, stg.config)
|
2019-04-22 01:43:33 +00:00
|
|
|
strategy.config = stg.config
|
2018-05-28 18:46:55 +00:00
|
|
|
|
2019-04-22 01:43:33 +00:00
|
|
|
WIKI.auth.strategies[stg.key] = {
|
|
|
|
...strategy,
|
|
|
|
...stg
|
2019-03-19 18:46:10 +00:00
|
|
|
}
|
2018-10-13 03:14:11 +00:00
|
|
|
WIKI.logger.info(`Authentication Strategy ${stg.key}: [ OK ]`)
|
2018-05-28 18:46:55 +00:00
|
|
|
}
|
|
|
|
} catch (err) {
|
|
|
|
WIKI.logger.error(`Authentication Strategy: [ FAILED ]`)
|
|
|
|
WIKI.logger.error(err)
|
|
|
|
}
|
2019-01-07 03:03:34 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Authenticate current request
|
|
|
|
*
|
|
|
|
* @param {Express Request} req
|
|
|
|
* @param {Express Response} res
|
|
|
|
* @param {Express Next Callback} next
|
|
|
|
*/
|
|
|
|
authenticate(req, res, next) {
|
|
|
|
WIKI.auth.passport.authenticate('jwt', {session: false}, async (err, user, info) => {
|
|
|
|
if (err) { return next() }
|
|
|
|
|
|
|
|
// Expired but still valid within N days, just renew
|
|
|
|
if (info instanceof Error && info.name === 'TokenExpiredError' && moment().subtract(14, 'days').isBefore(info.expiredAt)) {
|
|
|
|
const jwtPayload = jwt.decode(securityHelper.extractJWT(req))
|
|
|
|
try {
|
|
|
|
const newToken = await WIKI.models.users.refreshToken(jwtPayload.id)
|
|
|
|
user = newToken.user
|
2019-04-19 22:29:43 +00:00
|
|
|
user.permissions = user.getGlobalPermissions()
|
2019-01-25 22:19:52 +00:00
|
|
|
req.user = user
|
2019-01-07 03:03:34 +00:00
|
|
|
|
|
|
|
// Try headers, otherwise cookies for response
|
|
|
|
if (req.get('content-type') === 'application/json') {
|
|
|
|
res.set('new-jwt', newToken.token)
|
|
|
|
} else {
|
|
|
|
res.cookie('jwt', newToken.token, { expires: moment().add(365, 'days').toDate() })
|
|
|
|
}
|
2019-09-08 16:39:05 +00:00
|
|
|
} catch (errc) {
|
|
|
|
WIKI.logger.warn(errc)
|
2019-01-07 03:03:34 +00:00
|
|
|
return next()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// JWT is NOT valid, set as guest
|
|
|
|
if (!user) {
|
2019-03-17 02:41:48 +00:00
|
|
|
if (WIKI.auth.guest.cacheExpiration.isSameOrBefore(moment.utc())) {
|
2019-01-07 03:03:34 +00:00
|
|
|
WIKI.auth.guest = await WIKI.models.users.getGuestUser()
|
|
|
|
WIKI.auth.guest.cacheExpiration = moment.utc().add(1, 'm')
|
|
|
|
}
|
|
|
|
req.user = WIKI.auth.guest
|
|
|
|
return next()
|
|
|
|
}
|
|
|
|
|
|
|
|
// JWT is valid
|
2019-09-08 16:39:05 +00:00
|
|
|
req.logIn(user, { session: false }, (errc) => {
|
|
|
|
if (errc) { return next(errc) }
|
2019-01-07 03:03:34 +00:00
|
|
|
next()
|
|
|
|
})
|
|
|
|
})(req, res, next)
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Check if user has access to resource
|
|
|
|
*
|
|
|
|
* @param {User} user
|
|
|
|
* @param {Array<String>} permissions
|
|
|
|
* @param {String|Boolean} path
|
|
|
|
*/
|
2019-01-12 23:33:30 +00:00
|
|
|
checkAccess(user, permissions = [], page = false) {
|
2019-01-25 22:19:52 +00:00
|
|
|
const userPermissions = user.permissions ? user.permissions : user.getGlobalPermissions()
|
|
|
|
|
2019-01-07 03:03:34 +00:00
|
|
|
// System Admin
|
2019-01-25 22:19:52 +00:00
|
|
|
if (_.includes(userPermissions, 'manage:system')) {
|
2019-01-07 03:03:34 +00:00
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check Global Permissions
|
2019-01-12 23:33:30 +00:00
|
|
|
if (_.intersection(userPermissions, permissions).length < 1) {
|
2019-01-07 03:03:34 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check Page Rules
|
2019-10-13 23:59:50 +00:00
|
|
|
if (page && user.groups) {
|
2019-01-12 23:33:30 +00:00
|
|
|
let checkState = {
|
|
|
|
deny: false,
|
|
|
|
match: false,
|
|
|
|
specificity: ''
|
|
|
|
}
|
|
|
|
user.groups.forEach(grp => {
|
|
|
|
const grpId = _.isObject(grp) ? _.get(grp, 'id', 0) : grp
|
|
|
|
_.get(WIKI.auth.groups, `${grpId}.pageRules`, []).forEach(rule => {
|
2020-02-07 19:26:13 +00:00
|
|
|
if(_.intersection(rule.roles, permissions).length > 0) {
|
|
|
|
switch (rule.match) {
|
|
|
|
case 'START':
|
|
|
|
if (_.startsWith(`/${page.path}`, `/${rule.path}`)) {
|
|
|
|
checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['END', 'REGEX', 'EXACT', 'TAG'] })
|
2020-01-31 21:57:35 +00:00
|
|
|
}
|
2020-02-07 19:26:13 +00:00
|
|
|
break
|
|
|
|
case 'END':
|
|
|
|
if (_.endsWith(page.path, rule.path)) {
|
|
|
|
checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['REGEX', 'EXACT', 'TAG'] })
|
|
|
|
}
|
|
|
|
break
|
|
|
|
case 'REGEX':
|
|
|
|
const reg = new RegExp(rule.path)
|
|
|
|
if (reg.test(page.path)) {
|
|
|
|
checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: ['EXACT', 'TAG'] })
|
|
|
|
}
|
|
|
|
break
|
|
|
|
case 'TAG':
|
|
|
|
_.get(page, 'tags', []).forEach(tag => {
|
|
|
|
if (tag.tag === rule.path) {
|
|
|
|
checkState = this._applyPageRuleSpecificity({
|
|
|
|
rule,
|
|
|
|
checkState,
|
|
|
|
higherPriority: ['EXACT']
|
|
|
|
})
|
|
|
|
}
|
|
|
|
})
|
|
|
|
break
|
|
|
|
case 'EXACT':
|
|
|
|
if (`/${page.path}` === `/${rule.path}`) {
|
|
|
|
checkState = this._applyPageRuleSpecificity({ rule, checkState, higherPriority: [] })
|
|
|
|
}
|
|
|
|
break
|
|
|
|
}
|
2019-01-12 23:33:30 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
return (checkState.match && !checkState.deny)
|
|
|
|
}
|
|
|
|
|
2019-01-07 03:03:34 +00:00
|
|
|
return false
|
2019-01-12 23:33:30 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Check and apply Page Rule specificity
|
|
|
|
*
|
|
|
|
* @access private
|
|
|
|
*/
|
|
|
|
_applyPageRuleSpecificity ({ rule, checkState, higherPriority = [] }) {
|
|
|
|
if (rule.path.length === checkState.specificity.length) {
|
|
|
|
// Do not override higher priority rules
|
|
|
|
if (_.includes(higherPriority, checkState.match)) {
|
|
|
|
return checkState
|
|
|
|
}
|
|
|
|
// Do not override a previous DENY rule with same match
|
|
|
|
if (rule.match === checkState.match && checkState.deny && !rule.deny) {
|
|
|
|
return checkState
|
|
|
|
}
|
|
|
|
} else if (rule.path.length < checkState.specificity.length) {
|
|
|
|
// Do not override higher specificity rules
|
|
|
|
return checkState
|
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
deny: rule.deny,
|
|
|
|
match: rule.match,
|
|
|
|
specificity: rule.path
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Reload Groups from DB
|
|
|
|
*/
|
|
|
|
async reloadGroups() {
|
|
|
|
const groupsArray = await WIKI.models.groups.query()
|
|
|
|
this.groups = _.keyBy(groupsArray, 'id')
|
2019-06-30 19:18:26 +00:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Generate New Authentication Public / Private Key Certificates
|
|
|
|
*/
|
|
|
|
async regenerateCertificates() {
|
|
|
|
WIKI.logger.info('Regenerating certificates...')
|
|
|
|
|
|
|
|
_.set(WIKI.config, 'sessionSecret', (await crypto.randomBytesAsync(32)).toString('hex'))
|
|
|
|
const certs = crypto.generateKeyPairSync('rsa', {
|
|
|
|
modulusLength: 2048,
|
|
|
|
publicKeyEncoding: {
|
|
|
|
type: 'pkcs1',
|
|
|
|
format: 'pem'
|
|
|
|
},
|
|
|
|
privateKeyEncoding: {
|
|
|
|
type: 'pkcs1',
|
|
|
|
format: 'pem',
|
|
|
|
cipher: 'aes-256-cbc',
|
|
|
|
passphrase: WIKI.config.sessionSecret
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
_.set(WIKI.config, 'certs', {
|
|
|
|
jwk: pem2jwk(certs.publicKey),
|
|
|
|
public: certs.publicKey,
|
|
|
|
private: certs.privateKey
|
|
|
|
})
|
|
|
|
|
|
|
|
await WIKI.configSvc.saveToDb([
|
|
|
|
'certs',
|
|
|
|
'sessionSecret'
|
|
|
|
])
|
|
|
|
|
|
|
|
await WIKI.auth.activateStrategies()
|
|
|
|
|
|
|
|
WIKI.logger.info('Regenerated certificates: [ COMPLETED ]')
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Reset Guest User
|
|
|
|
*/
|
|
|
|
async resetGuestUser() {
|
|
|
|
WIKI.logger.info('Resetting guest account...')
|
|
|
|
const guestGroup = await WIKI.models.groups.query().where('id', 2).first()
|
|
|
|
|
|
|
|
await WIKI.models.users.query().delete().where({
|
|
|
|
providerKey: 'local',
|
|
|
|
email: 'guest@example.com'
|
|
|
|
}).orWhere('id', 2)
|
|
|
|
|
|
|
|
const guestUser = await WIKI.models.users.query().insert({
|
|
|
|
id: 2,
|
|
|
|
provider: 'local',
|
|
|
|
email: 'guest@example.com',
|
|
|
|
name: 'Guest',
|
|
|
|
password: '',
|
|
|
|
locale: 'en',
|
|
|
|
defaultEditor: 'markdown',
|
|
|
|
tfaIsActive: false,
|
|
|
|
isSystem: true,
|
|
|
|
isActive: true,
|
|
|
|
isVerified: true
|
|
|
|
})
|
|
|
|
await guestUser.$relatedQuery('groups').relate(guestGroup.id)
|
|
|
|
|
|
|
|
WIKI.logger.info('Guest user has been reset: [ COMPLETED ]')
|
2017-08-03 03:47:11 +00:00
|
|
|
}
|
2017-04-02 23:56:47 +00:00
|
|
|
}
|