authentication.js 8.2 KB

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