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.

140 lines
4.4 KiB

  1. const Model = require('objection').Model
  2. const fs = require('fs-extra')
  3. const path = require('path')
  4. const _ = require('lodash')
  5. const yaml = require('js-yaml')
  6. const commonHelper = require('../helpers/common')
  7. /* global WIKI */
  8. /**
  9. * Authentication model
  10. */
  11. module.exports = class Authentication extends Model {
  12. static get tableName() { return 'authentication' }
  13. static get idColumn() { return 'key' }
  14. static get jsonSchema () {
  15. return {
  16. type: 'object',
  17. required: ['key', 'isEnabled'],
  18. properties: {
  19. key: {type: 'string'},
  20. isEnabled: {type: 'boolean'},
  21. selfRegistration: {type: 'boolean'}
  22. }
  23. }
  24. }
  25. static get jsonAttributes() {
  26. return ['config', 'domainWhitelist', 'autoEnrollGroups']
  27. }
  28. static async getStrategy(key) {
  29. return WIKI.models.authentication.query().findOne({ key })
  30. }
  31. static async getStrategies(isEnabled) {
  32. const strategies = await WIKI.models.authentication.query().where(_.isBoolean(isEnabled) ? { isEnabled } : {})
  33. return _.sortBy(strategies.map(str => ({
  34. ...str,
  35. domainWhitelist: _.get(str.domainWhitelist, 'v', []),
  36. autoEnrollGroups: _.get(str.autoEnrollGroups, 'v', [])
  37. })), ['key'])
  38. }
  39. static async getStrategiesForLegacyClient() {
  40. const strategies = await WIKI.models.authentication.query().select('key', 'selfRegistration').where({ isEnabled: true })
  41. let formStrategies = []
  42. let socialStrategies = []
  43. for (let stg of strategies) {
  44. const stgInfo = _.find(WIKI.data.authentication, ['key', stg.key]) || {}
  45. if (stgInfo.useForm) {
  46. formStrategies.push({
  47. key: stg.key,
  48. title: stgInfo.title
  49. })
  50. } else {
  51. socialStrategies.push({
  52. ...stgInfo,
  53. ...stg,
  54. icon: await fs.readFile(path.join(WIKI.ROOTPATH, `assets/svg/auth-icon-${stg.key}.svg`), 'utf8').catch(err => {
  55. if (err.code === 'ENOENT') {
  56. return null
  57. }
  58. throw err
  59. })
  60. })
  61. }
  62. }
  63. return {
  64. formStrategies,
  65. socialStrategies
  66. }
  67. }
  68. static async refreshStrategiesFromDisk() {
  69. let trx
  70. try {
  71. const dbStrategies = await WIKI.models.authentication.query()
  72. // -> Fetch definitions from disk
  73. const authDirs = await fs.readdir(path.join(WIKI.SERVERPATH, 'modules/authentication'))
  74. let diskStrategies = []
  75. for (let dir of authDirs) {
  76. const def = await fs.readFile(path.join(WIKI.SERVERPATH, 'modules/authentication', dir, 'definition.yml'), 'utf8')
  77. diskStrategies.push(yaml.safeLoad(def))
  78. }
  79. WIKI.data.authentication = diskStrategies.map(strategy => ({
  80. ...strategy,
  81. props: commonHelper.parseModuleProps(strategy.props)
  82. }))
  83. let newStrategies = []
  84. for (let strategy of WIKI.data.authentication) {
  85. if (!_.some(dbStrategies, ['key', strategy.key])) {
  86. newStrategies.push({
  87. key: strategy.key,
  88. isEnabled: false,
  89. config: _.transform(strategy.props, (result, value, key) => {
  90. _.set(result, key, value.default)
  91. return result
  92. }, {}),
  93. selfRegistration: false,
  94. domainWhitelist: { v: [] },
  95. autoEnrollGroups: { v: [] }
  96. })
  97. } else {
  98. const strategyConfig = _.get(_.find(dbStrategies, ['key', strategy.key]), 'config', {})
  99. await WIKI.models.authentication.query().patch({
  100. config: _.transform(strategy.props, (result, value, key) => {
  101. if (!_.has(result, key)) {
  102. _.set(result, key, value.default)
  103. }
  104. return result
  105. }, strategyConfig)
  106. }).where('key', strategy.key)
  107. }
  108. }
  109. if (newStrategies.length > 0) {
  110. trx = await WIKI.models.Objection.transaction.start(WIKI.models.knex)
  111. for (let strategy of newStrategies) {
  112. await WIKI.models.authentication.query(trx).insert(strategy)
  113. }
  114. await trx.commit()
  115. WIKI.logger.info(`Loaded ${newStrategies.length} new authentication strategies: [ OK ]`)
  116. } else {
  117. WIKI.logger.info(`No new authentication strategies found: [ SKIPPED ]`)
  118. }
  119. } catch (err) {
  120. WIKI.logger.error(`Failed to scan or load new authentication providers: [ FAILED ]`)
  121. WIKI.logger.error(err)
  122. if (trx) {
  123. trx.rollback()
  124. }
  125. }
  126. }
  127. }