authentication.js 3.49 KB
Newer Older
1
const Model = require('objection').Model
2
const fs = require('fs-extra')
3 4
const path = require('path')
const _ = require('lodash')
5
const yaml = require('js-yaml')
6
const commonHelper = require('../helpers/common')
7 8 9 10 11 12 13 14

/* global WIKI */

/**
 * Authentication model
 */
module.exports = class Authentication extends Model {
  static get tableName() { return 'authentication' }
15
  static get idColumn() { return 'key' }
16 17 18 19

  static get jsonSchema () {
    return {
      type: 'object',
20
      required: ['key', 'isEnabled'],
21 22 23 24

      properties: {
        key: {type: 'string'},
        isEnabled: {type: 'boolean'},
25
        selfRegistration: {type: 'boolean'}
26 27 28 29
      }
    }
  }

30 31 32 33
  static get jsonAttributes() {
    return ['config', 'domainWhitelist', 'autoEnrollGroups']
  }

34 35 36 37
  static async getStrategy(key) {
    return WIKI.models.authentication.query().findOne({ key })
  }

38 39 40
  static async getStrategies(isEnabled) {
    const strategies = await WIKI.models.authentication.query().where(_.isBoolean(isEnabled) ? { isEnabled } : {})
    return _.sortBy(strategies.map(str => ({
41 42 43
      ...str,
      domainWhitelist: _.get(str.domainWhitelist, 'v', []),
      autoEnrollGroups: _.get(str.autoEnrollGroups, 'v', [])
44
    })), ['key'])
45 46 47
  }

  static async refreshStrategiesFromDisk() {
48
    let trx
49
    try {
50
      const dbStrategies = await WIKI.models.authentication.query()
51 52 53 54 55 56 57 58

      // -> Fetch definitions from disk
      const authDirs = await fs.readdir(path.join(WIKI.SERVERPATH, 'modules/authentication'))
      let diskStrategies = []
      for (let dir of authDirs) {
        const def = await fs.readFile(path.join(WIKI.SERVERPATH, 'modules/authentication', dir, 'definition.yml'), 'utf8')
        diskStrategies.push(yaml.safeLoad(def))
      }
59 60 61 62
      WIKI.data.authentication = diskStrategies.map(strategy => ({
        ...strategy,
        props: commonHelper.parseModuleProps(strategy.props)
      }))
63

64
      let newStrategies = []
65
      for (let strategy of WIKI.data.authentication) {
66 67 68 69
        if (!_.some(dbStrategies, ['key', strategy.key])) {
          newStrategies.push({
            key: strategy.key,
            isEnabled: false,
70
            config: _.transform(strategy.props, (result, value, key) => {
71
              _.set(result, key, value.default)
72
              return result
73 74 75 76
            }, {}),
            selfRegistration: false,
            domainWhitelist: { v: [] },
            autoEnrollGroups: { v: [] }
77
          })
78 79 80 81 82 83 84 85 86 87
        } else {
          const strategyConfig = _.get(_.find(dbStrategies, ['key', strategy.key]), 'config', {})
          await WIKI.models.authentication.query().patch({
            config: _.transform(strategy.props, (result, value, key) => {
              if (!_.has(result, key)) {
                _.set(result, key, value.default)
              }
              return result
            }, strategyConfig)
          }).where('key', strategy.key)
88
        }
89
      }
90
      if (newStrategies.length > 0) {
91 92 93 94 95
        trx = await WIKI.models.Objection.transaction.start(WIKI.models.knex)
        for (let strategy of newStrategies) {
          await WIKI.models.authentication.query(trx).insert(strategy)
        }
        await trx.commit()
96 97 98 99 100 101 102
        WIKI.logger.info(`Loaded ${newStrategies.length} new authentication strategies: [ OK ]`)
      } else {
        WIKI.logger.info(`No new authentication strategies found: [ SKIPPED ]`)
      }
    } catch (err) {
      WIKI.logger.error(`Failed to scan or load new authentication providers: [ FAILED ]`)
      WIKI.logger.error(err)
103 104 105
      if (trx) {
        trx.rollback()
      }
106 107 108
    }
  }
}