authentication.mjs 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import _ from 'lodash-es'
  2. import { generateError, generateSuccess } from '../../helpers/graph.mjs'
  3. export default {
  4. Query: {
  5. /**
  6. * List of API Keys
  7. */
  8. async apiKeys (obj, args, context) {
  9. const keys = await WIKI.db.apiKeys.query().orderBy(['isRevoked', 'name'])
  10. return keys.map(k => ({
  11. id: k.id,
  12. name: k.name,
  13. keyShort: '...' + k.key.substring(k.key.length - 20),
  14. isRevoked: k.isRevoked,
  15. expiration: k.expiration,
  16. createdAt: k.createdAt,
  17. updatedAt: k.updatedAt
  18. }))
  19. },
  20. /**
  21. * Current API State
  22. */
  23. apiState () {
  24. return WIKI.config.api.isEnabled
  25. },
  26. /**
  27. * Fetch authentication strategies
  28. */
  29. async authStrategies () {
  30. return WIKI.data.authentication.map(stg => ({
  31. ...stg,
  32. isAvailable: stg.isAvailable === true
  33. }))
  34. },
  35. /**
  36. * Fetch active authentication strategies
  37. */
  38. async authActiveStrategies (obj, args, context) {
  39. return WIKI.db.authentication.getStrategies({ enabledOnly: args.enabledOnly })
  40. },
  41. /**
  42. * Fetch site authentication strategies
  43. */
  44. async authSiteStrategies (obj, args, context, info) {
  45. const site = await WIKI.db.sites.query().findById(args.siteId)
  46. const activeStrategies = await WIKI.db.authentication.getStrategies({ enabledOnly: true })
  47. return activeStrategies.map(str => {
  48. const siteAuth = _.find(site.config.authStrategies, ['id', str.id]) || {}
  49. return {
  50. id: str.id,
  51. activeStrategy: str,
  52. order: siteAuth.order ?? 0,
  53. isVisible: siteAuth.isVisible ?? false
  54. }
  55. })
  56. }
  57. },
  58. Mutation: {
  59. /**
  60. * Create New API Key
  61. */
  62. async createApiKey (obj, args, context) {
  63. try {
  64. const key = await WIKI.db.apiKeys.createNewKey(args)
  65. await WIKI.auth.reloadApiKeys()
  66. WIKI.events.outbound.emit('reloadApiKeys')
  67. return {
  68. key,
  69. operation: generateSuccess('API Key created successfully')
  70. }
  71. } catch (err) {
  72. WIKI.logger.warn(err)
  73. return generateError(err)
  74. }
  75. },
  76. /**
  77. * Perform Login
  78. */
  79. async login (obj, args, context) {
  80. try {
  81. const authResult = await WIKI.db.users.login(args, context)
  82. return {
  83. ...authResult,
  84. operation: generateSuccess('Login success')
  85. }
  86. } catch (err) {
  87. // LDAP Debug Flag
  88. if (args.strategy === 'ldap' && WIKI.config.flags.ldapdebug) {
  89. WIKI.logger.warn('LDAP LOGIN ERROR (c1): ', err)
  90. }
  91. console.error(err)
  92. return generateError(err)
  93. }
  94. },
  95. /**
  96. * Perform 2FA Login
  97. */
  98. async loginTFA (obj, args, context) {
  99. try {
  100. const authResult = await WIKI.db.users.loginTFA(args, context)
  101. return {
  102. ...authResult,
  103. responseResult: generateSuccess('TFA success')
  104. }
  105. } catch (err) {
  106. return generateError(err)
  107. }
  108. },
  109. /**
  110. * Perform Password Change
  111. */
  112. async changePassword (obj, args, context) {
  113. try {
  114. const authResult = await WIKI.db.users.loginChangePassword(args, context)
  115. return {
  116. ...authResult,
  117. responseResult: generateSuccess('Password changed successfully')
  118. }
  119. } catch (err) {
  120. return generateError(err)
  121. }
  122. },
  123. /**
  124. * Perform Forget Password
  125. */
  126. async forgotPassword (obj, args, context) {
  127. try {
  128. await WIKI.db.users.loginForgotPassword(args, context)
  129. return {
  130. responseResult: generateSuccess('Password reset request processed.')
  131. }
  132. } catch (err) {
  133. return generateError(err)
  134. }
  135. },
  136. /**
  137. * Register a new account
  138. */
  139. async register (obj, args, context) {
  140. try {
  141. await WIKI.db.users.register({ ...args, verify: true }, context)
  142. return {
  143. responseResult: generateSuccess('Registration success')
  144. }
  145. } catch (err) {
  146. return generateError(err)
  147. }
  148. },
  149. /**
  150. * Set API state
  151. */
  152. async setApiState (obj, args, context) {
  153. try {
  154. WIKI.config.api.isEnabled = args.enabled
  155. await WIKI.configSvc.saveToDb(['api'])
  156. return {
  157. operation: generateSuccess('API State changed successfully')
  158. }
  159. } catch (err) {
  160. return generateError(err)
  161. }
  162. },
  163. /**
  164. * Revoke an API key
  165. */
  166. async revokeApiKey (obj, args, context) {
  167. try {
  168. await WIKI.db.apiKeys.query().findById(args.id).patch({
  169. isRevoked: true
  170. })
  171. await WIKI.auth.reloadApiKeys()
  172. WIKI.events.outbound.emit('reloadApiKeys')
  173. return {
  174. operation: generateSuccess('API Key revoked successfully')
  175. }
  176. } catch (err) {
  177. return generateError(err)
  178. }
  179. },
  180. /**
  181. * Update Authentication Strategies
  182. */
  183. async updateAuthStrategies (obj, args, context) {
  184. try {
  185. const previousStrategies = await WIKI.db.authentication.getStrategies()
  186. for (const str of args.strategies) {
  187. const newStr = {
  188. displayName: str.displayName,
  189. order: str.order,
  190. isEnabled: str.isEnabled,
  191. config: _.reduce(str.config, (result, value, key) => {
  192. _.set(result, `${value.key}`, _.get(JSON.parse(value.value), 'v', null))
  193. return result
  194. }, {}),
  195. selfRegistration: str.selfRegistration,
  196. domainWhitelist: { v: str.domainWhitelist },
  197. autoEnrollGroups: { v: str.autoEnrollGroups }
  198. }
  199. if (_.some(previousStrategies, ['key', str.key])) {
  200. await WIKI.db.authentication.query().patch({
  201. key: str.key,
  202. strategyKey: str.strategyKey,
  203. ...newStr
  204. }).where('key', str.key)
  205. } else {
  206. await WIKI.db.authentication.query().insert({
  207. key: str.key,
  208. strategyKey: str.strategyKey,
  209. ...newStr
  210. })
  211. }
  212. }
  213. for (const str of _.differenceBy(previousStrategies, args.strategies, 'key')) {
  214. const hasUsers = await WIKI.db.users.query().count('* as total').where({ providerKey: str.key }).first()
  215. if (_.toSafeInteger(hasUsers.total) > 0) {
  216. throw new Error(`Cannot delete ${str.displayName} as 1 or more users are still using it.`)
  217. } else {
  218. await WIKI.db.authentication.query().delete().where('key', str.key)
  219. }
  220. }
  221. await WIKI.auth.activateStrategies()
  222. WIKI.events.outbound.emit('reloadAuthStrategies')
  223. return {
  224. responseResult: generateSuccess('Strategies updated successfully')
  225. }
  226. } catch (err) {
  227. return generateError(err)
  228. }
  229. },
  230. /**
  231. * Generate New Authentication Public / Private Key Certificates
  232. */
  233. async regenerateCertificates (obj, args, context) {
  234. try {
  235. await WIKI.auth.regenerateCertificates()
  236. return {
  237. responseResult: generateSuccess('Certificates have been regenerated successfully.')
  238. }
  239. } catch (err) {
  240. return generateError(err)
  241. }
  242. },
  243. /**
  244. * Reset Guest User
  245. */
  246. async resetGuestUser (obj, args, context) {
  247. try {
  248. await WIKI.auth.resetGuestUser()
  249. return {
  250. responseResult: generateSuccess('Guest user has been reset successfully.')
  251. }
  252. } catch (err) {
  253. return generateError(err)
  254. }
  255. }
  256. },
  257. AuthenticationActiveStrategy: {
  258. strategy (obj, args, context) {
  259. return _.find(WIKI.data.authentication, ['key', obj.module])
  260. }
  261. }
  262. }