authentication.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const Model = require('objection').Model
  2. const autoload = require('auto-load')
  3. const path = require('path')
  4. const _ = require('lodash')
  5. /* global WIKI */
  6. /**
  7. * Authentication model
  8. */
  9. module.exports = class Authentication extends Model {
  10. static get tableName() { return 'authentication' }
  11. static get jsonSchema () {
  12. return {
  13. type: 'object',
  14. required: ['key', 'title', 'isEnabled', 'useForm'],
  15. properties: {
  16. id: {type: 'integer'},
  17. key: {type: 'string'},
  18. title: {type: 'string'},
  19. isEnabled: {type: 'boolean'},
  20. useForm: {type: 'boolean'},
  21. config: {type: 'object'}
  22. }
  23. }
  24. }
  25. static async getEnabledStrategies() {
  26. return WIKI.db.authentication.query().where({ isEnabled: true })
  27. }
  28. static async refreshStrategiesFromDisk() {
  29. try {
  30. const dbStrategies = await WIKI.db.authentication.query()
  31. const diskStrategies = autoload(path.join(WIKI.SERVERPATH, 'modules/authentication'))
  32. let newStrategies = []
  33. _.forOwn(diskStrategies, (strategy, strategyKey) => {
  34. if (!_.some(dbStrategies, ['key', strategy.key])) {
  35. newStrategies.push({
  36. key: strategy.key,
  37. title: strategy.title,
  38. isEnabled: false,
  39. useForm: strategy.useForm,
  40. config: _.reduce(strategy.props, (result, value, key) => {
  41. _.set(result, value, '')
  42. return result
  43. }, {})
  44. })
  45. }
  46. })
  47. if (newStrategies.length > 0) {
  48. await WIKI.db.authentication.query().insert(newStrategies)
  49. WIKI.logger.info(`Loaded ${newStrategies.length} new authentication strategies: [ OK ]`)
  50. } else {
  51. WIKI.logger.info(`No new authentication strategies found: [ SKIPPED ]`)
  52. }
  53. } catch (err) {
  54. WIKI.logger.error(`Failed to scan or load new authentication providers: [ FAILED ]`)
  55. WIKI.logger.error(err)
  56. }
  57. }
  58. }