authentication.js 7.9 KB

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