users.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746
  1. /* global WIKI */
  2. const bcrypt = require('bcryptjs-then')
  3. const _ = require('lodash')
  4. const tfa = require('node-2fa')
  5. const jwt = require('jsonwebtoken')
  6. const Model = require('objection').Model
  7. const validate = require('validate.js')
  8. const bcryptRegexp = /^\$2[ayb]\$[0-9]{2}\$[A-Za-z0-9./]{53}$/
  9. /**
  10. * Users model
  11. */
  12. module.exports = class User extends Model {
  13. static get tableName() { return 'users' }
  14. static get jsonSchema () {
  15. return {
  16. type: 'object',
  17. required: ['email'],
  18. properties: {
  19. id: {type: 'integer'},
  20. email: {type: 'string', format: 'email'},
  21. name: {type: 'string', minLength: 1, maxLength: 255},
  22. providerId: {type: 'string'},
  23. password: {type: 'string'},
  24. tfaIsActive: {type: 'boolean', default: false},
  25. tfaSecret: {type: 'string'},
  26. jobTitle: {type: 'string'},
  27. location: {type: 'string'},
  28. pictureUrl: {type: 'string'},
  29. isSystem: {type: 'boolean'},
  30. isActive: {type: 'boolean'},
  31. isVerified: {type: 'boolean'},
  32. createdAt: {type: 'string'},
  33. updatedAt: {type: 'string'}
  34. }
  35. }
  36. }
  37. static get relationMappings() {
  38. return {
  39. groups: {
  40. relation: Model.ManyToManyRelation,
  41. modelClass: require('./groups'),
  42. join: {
  43. from: 'users.id',
  44. through: {
  45. from: 'userGroups.userId',
  46. to: 'userGroups.groupId'
  47. },
  48. to: 'groups.id'
  49. }
  50. },
  51. provider: {
  52. relation: Model.BelongsToOneRelation,
  53. modelClass: require('./authentication'),
  54. join: {
  55. from: 'users.providerKey',
  56. to: 'authentication.key'
  57. }
  58. },
  59. defaultEditor: {
  60. relation: Model.BelongsToOneRelation,
  61. modelClass: require('./editors'),
  62. join: {
  63. from: 'users.editorKey',
  64. to: 'editors.key'
  65. }
  66. },
  67. locale: {
  68. relation: Model.BelongsToOneRelation,
  69. modelClass: require('./locales'),
  70. join: {
  71. from: 'users.localeCode',
  72. to: 'locales.code'
  73. }
  74. }
  75. }
  76. }
  77. async $beforeUpdate(opt, context) {
  78. await super.$beforeUpdate(opt, context)
  79. this.updatedAt = new Date().toISOString()
  80. if (!(opt.patch && this.password === undefined)) {
  81. await this.generateHash()
  82. }
  83. }
  84. async $beforeInsert(context) {
  85. await super.$beforeInsert(context)
  86. this.createdAt = new Date().toISOString()
  87. this.updatedAt = new Date().toISOString()
  88. await this.generateHash()
  89. }
  90. // ------------------------------------------------
  91. // Instance Methods
  92. // ------------------------------------------------
  93. async generateHash() {
  94. if (this.password) {
  95. if (bcryptRegexp.test(this.password)) { return }
  96. this.password = await bcrypt.hash(this.password, 12)
  97. }
  98. }
  99. async verifyPassword(pwd) {
  100. if (await bcrypt.compare(pwd, this.password) === true) {
  101. return true
  102. } else {
  103. throw new WIKI.Error.AuthLoginFailed()
  104. }
  105. }
  106. async enableTFA() {
  107. let tfaInfo = tfa.generateSecret({
  108. name: WIKI.config.site.title
  109. })
  110. return this.$query.patch({
  111. tfaIsActive: true,
  112. tfaSecret: tfaInfo.secret
  113. })
  114. }
  115. async disableTFA() {
  116. return this.$query.patch({
  117. tfaIsActive: false,
  118. tfaSecret: ''
  119. })
  120. }
  121. async verifyTFA(code) {
  122. let result = tfa.verifyToken(this.tfaSecret, code)
  123. return (result && _.has(result, 'delta') && result.delta === 0)
  124. }
  125. getGlobalPermissions() {
  126. return _.uniq(_.flatten(_.map(this.groups, 'permissions')))
  127. }
  128. getGroups() {
  129. return _.uniq(_.map(this.groups, 'id'))
  130. }
  131. // ------------------------------------------------
  132. // Model Methods
  133. // ------------------------------------------------
  134. static async processProfile({ profile, providerKey }) {
  135. const provider = _.get(WIKI.auth.strategies, providerKey, {})
  136. provider.info = _.find(WIKI.data.authentication, ['key', providerKey])
  137. // Find existing user
  138. let user = await WIKI.models.users.query().findOne({
  139. providerId: _.toString(profile.id),
  140. providerKey
  141. })
  142. // Parse email
  143. let primaryEmail = ''
  144. if (_.isArray(profile.emails)) {
  145. const e = _.find(profile.emails, ['primary', true])
  146. primaryEmail = (e) ? e.value : _.first(profile.emails).value
  147. } else if (_.isString(profile.email) && profile.email.length > 5) {
  148. primaryEmail = profile.email
  149. } else if (_.isString(profile.mail) && profile.mail.length > 5) {
  150. primaryEmail = profile.mail
  151. } else if (profile.user && profile.user.email && profile.user.email.length > 5) {
  152. primaryEmail = profile.user.email
  153. } else {
  154. throw new Error('Missing or invalid email address from profile.')
  155. }
  156. primaryEmail = _.toLower(primaryEmail)
  157. // Find pending social user
  158. if (!user) {
  159. user = await WIKI.models.users.query().findOne({
  160. email: primaryEmail,
  161. providerId: null,
  162. providerKey
  163. })
  164. if (user) {
  165. user = await user.$query().patchAndFetch({
  166. providerId: _.toString(profile.id)
  167. })
  168. }
  169. }
  170. // Parse display name
  171. let displayName = ''
  172. if (_.isString(profile.displayName) && profile.displayName.length > 0) {
  173. displayName = profile.displayName
  174. } else if (_.isString(profile.name) && profile.name.length > 0) {
  175. displayName = profile.name
  176. } else {
  177. displayName = primaryEmail.split('@')[0]
  178. }
  179. // Parse picture URL
  180. let pictureUrl = _.truncate(_.get(profile, 'picture', _.get(user, 'pictureUrl', null)), {
  181. length: 255,
  182. omission: ''
  183. })
  184. // Update existing user
  185. if (user) {
  186. if (!user.isActive) {
  187. throw new WIKI.Error.AuthAccountBanned()
  188. }
  189. if (user.isSystem) {
  190. throw new Error('This is a system reserved account and cannot be used.')
  191. }
  192. user = await user.$query().patchAndFetch({
  193. email: primaryEmail,
  194. name: displayName,
  195. pictureUrl: pictureUrl
  196. })
  197. return user
  198. }
  199. // Self-registration
  200. if (provider.selfRegistration) {
  201. // Check if email domain is whitelisted
  202. if (_.get(provider, 'domainWhitelist', []).length > 0) {
  203. const emailDomain = _.last(primaryEmail.split('@'))
  204. if (!_.includes(provider.domainWhitelist, emailDomain)) {
  205. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  206. }
  207. }
  208. // Create account
  209. user = await WIKI.models.users.query().insertAndFetch({
  210. providerKey: providerKey,
  211. providerId: _.toString(profile.id),
  212. email: primaryEmail,
  213. name: displayName,
  214. pictureUrl: pictureUrl,
  215. localeCode: WIKI.config.lang.code,
  216. defaultEditor: 'markdown',
  217. tfaIsActive: false,
  218. isSystem: false,
  219. isActive: true,
  220. isVerified: true
  221. })
  222. // Assign to group(s)
  223. if (provider.autoEnrollGroups.length > 0) {
  224. await user.$relatedQuery('groups').relate(provider.autoEnrollGroups)
  225. }
  226. return user
  227. }
  228. throw new Error('You are not authorized to login.')
  229. }
  230. static async login (opts, context) {
  231. if (_.has(WIKI.auth.strategies, opts.strategy)) {
  232. const strInfo = _.find(WIKI.data.authentication, ['key', opts.strategy])
  233. // Inject form user/pass
  234. if (strInfo.useForm) {
  235. _.set(context.req, 'body.email', opts.username)
  236. _.set(context.req, 'body.password', opts.password)
  237. }
  238. // Authenticate
  239. return new Promise((resolve, reject) => {
  240. WIKI.auth.passport.authenticate(opts.strategy, {
  241. session: !strInfo.useForm,
  242. scope: strInfo.scopes ? strInfo.scopes : null
  243. }, async (err, user, info) => {
  244. if (err) { return reject(err) }
  245. if (!user) { return reject(new WIKI.Error.AuthLoginFailed()) }
  246. // Must Change Password?
  247. if (user.mustChangePwd) {
  248. try {
  249. const pwdChangeToken = await WIKI.models.userKeys.generateToken({
  250. kind: 'changePwd',
  251. userId: user.id
  252. })
  253. return resolve({
  254. mustChangePwd: true,
  255. continuationToken: pwdChangeToken
  256. })
  257. } catch (errc) {
  258. WIKI.logger.warn(errc)
  259. return reject(new WIKI.Error.AuthGenericError())
  260. }
  261. }
  262. // Is 2FA required?
  263. if (user.tfaIsActive) {
  264. try {
  265. const tfaToken = await WIKI.models.userKeys.generateToken({
  266. kind: 'tfa',
  267. userId: user.id
  268. })
  269. return resolve({
  270. tfaRequired: true,
  271. continuationToken: tfaToken
  272. })
  273. } catch (errc) {
  274. WIKI.logger.warn(errc)
  275. return reject(new WIKI.Error.AuthGenericError())
  276. }
  277. }
  278. context.req.logIn(user, { session: !strInfo.useForm }, async errc => {
  279. if (errc) { return reject(errc) }
  280. const jwtToken = await WIKI.models.users.refreshToken(user)
  281. resolve({ jwt: jwtToken.token })
  282. })
  283. })(context.req, context.res, () => {})
  284. })
  285. } else {
  286. throw new WIKI.Error.AuthProviderInvalid()
  287. }
  288. }
  289. static async refreshToken(user) {
  290. if (_.isSafeInteger(user)) {
  291. user = await WIKI.models.users.query().findById(user).withGraphFetched('groups').modifyGraph('groups', builder => {
  292. builder.select('groups.id', 'permissions')
  293. })
  294. if (!user) {
  295. WIKI.logger.warn(`Failed to refresh token for user ${user}: Not found.`)
  296. throw new WIKI.Error.AuthGenericError()
  297. }
  298. } else if (_.isNil(user.groups)) {
  299. user.groups = await user.$relatedQuery('groups').select('groups.id', 'permissions')
  300. }
  301. // Update Last Login Date
  302. // -> Bypass Objection.js to avoid updating the updatedAt field
  303. await WIKI.models.knex('users').where('id', user.id).update({ lastLoginAt: new Date().toISOString() })
  304. return {
  305. token: jwt.sign({
  306. id: user.id,
  307. email: user.email,
  308. name: user.name,
  309. pictureUrl: user.pictureUrl,
  310. timezone: user.timezone,
  311. localeCode: user.localeCode,
  312. defaultEditor: user.defaultEditor,
  313. permissions: user.getGlobalPermissions(),
  314. groups: user.getGroups()
  315. }, {
  316. key: WIKI.config.certs.private,
  317. passphrase: WIKI.config.sessionSecret
  318. }, {
  319. algorithm: 'RS256',
  320. expiresIn: WIKI.config.auth.tokenExpiration,
  321. audience: WIKI.config.auth.audience,
  322. issuer: 'urn:wiki.js'
  323. }),
  324. user
  325. }
  326. }
  327. static async loginTFA (opts, context) {
  328. if (opts.securityCode.length === 6 && opts.loginToken.length === 64) {
  329. let result = await WIKI.redis.get(`tfa:${opts.loginToken}`)
  330. if (result) {
  331. let userId = _.toSafeInteger(result)
  332. if (userId && userId > 0) {
  333. let user = await WIKI.models.users.query().findById(userId)
  334. if (user && user.verifyTFA(opts.securityCode)) {
  335. return Promise.fromCallback(clb => {
  336. context.req.logIn(user, clb)
  337. }).return({
  338. succeeded: true,
  339. message: 'Login Successful'
  340. }).catch(err => {
  341. WIKI.logger.warn(err)
  342. throw new WIKI.Error.AuthGenericError()
  343. })
  344. } else {
  345. throw new WIKI.Error.AuthTFAFailed()
  346. }
  347. }
  348. }
  349. }
  350. throw new WIKI.Error.AuthTFAInvalid()
  351. }
  352. /**
  353. * Change Password from a Mandatory Password Change after Login
  354. */
  355. static async loginChangePassword ({ continuationToken, newPassword }, context) {
  356. if (!newPassword || newPassword.length < 6) {
  357. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  358. }
  359. const usr = await WIKI.models.userKeys.validateToken({
  360. kind: 'changePwd',
  361. token: continuationToken
  362. })
  363. if (usr) {
  364. await WIKI.models.users.query().patch({
  365. password: newPassword,
  366. mustChangePwd: false
  367. }).findById(usr.id)
  368. return new Promise((resolve, reject) => {
  369. context.req.logIn(usr, { session: false }, async err => {
  370. if (err) { return reject(err) }
  371. const jwtToken = await WIKI.models.users.refreshToken(usr)
  372. resolve({ jwt: jwtToken.token })
  373. })
  374. })
  375. } else {
  376. throw new WIKI.Error.UserNotFound()
  377. }
  378. }
  379. /**
  380. * Create a new user
  381. *
  382. * @param {Object} param0 User Fields
  383. */
  384. static async createNewUser ({ providerKey, email, passwordRaw, name, groups, mustChangePassword, sendWelcomeEmail }) {
  385. // Input sanitization
  386. email = _.toLower(email)
  387. // Input validation
  388. let validation = null
  389. if (providerKey === 'local') {
  390. validation = validate({
  391. email,
  392. passwordRaw,
  393. name
  394. }, {
  395. email: {
  396. email: true,
  397. length: {
  398. maximum: 255
  399. }
  400. },
  401. passwordRaw: {
  402. presence: {
  403. allowEmpty: false
  404. },
  405. length: {
  406. minimum: 6
  407. }
  408. },
  409. name: {
  410. presence: {
  411. allowEmpty: false
  412. },
  413. length: {
  414. minimum: 2,
  415. maximum: 255
  416. }
  417. }
  418. }, { format: 'flat' })
  419. } else {
  420. validation = validate({
  421. email,
  422. name
  423. }, {
  424. email: {
  425. email: true,
  426. length: {
  427. maximum: 255
  428. }
  429. },
  430. name: {
  431. presence: {
  432. allowEmpty: false
  433. },
  434. length: {
  435. minimum: 2,
  436. maximum: 255
  437. }
  438. }
  439. }, { format: 'flat' })
  440. }
  441. if (validation && validation.length > 0) {
  442. throw new WIKI.Error.InputInvalid(validation[0])
  443. }
  444. // Check if email already exists
  445. const usr = await WIKI.models.users.query().findOne({ email, providerKey })
  446. if (!usr) {
  447. // Create the account
  448. let newUsrData = {
  449. providerKey,
  450. email,
  451. name,
  452. locale: 'en',
  453. defaultEditor: 'markdown',
  454. tfaIsActive: false,
  455. isSystem: false,
  456. isActive: true,
  457. isVerified: true,
  458. mustChangePwd: false
  459. }
  460. if (providerKey === `local`) {
  461. newUsrData.password = passwordRaw
  462. newUsrData.mustChangePwd = (mustChangePassword === true)
  463. }
  464. const newUsr = await WIKI.models.users.query().insert(newUsrData)
  465. // Assign to group(s)
  466. if (groups.length > 0) {
  467. await newUsr.$relatedQuery('groups').relate(groups)
  468. }
  469. if (sendWelcomeEmail) {
  470. // Send welcome email
  471. await WIKI.mail.send({
  472. template: 'accountWelcome',
  473. to: email,
  474. subject: `Welcome to the wiki ${WIKI.config.title}`,
  475. data: {
  476. preheadertext: `You've been invited to the wiki ${WIKI.config.title}`,
  477. title: `You've been invited to the wiki ${WIKI.config.title}`,
  478. content: `Click the button below to access the wiki.`,
  479. buttonLink: `${WIKI.config.host}/login`,
  480. buttonText: 'Login'
  481. },
  482. text: `You've been invited to the wiki ${WIKI.config.title}: ${WIKI.config.host}/login`
  483. })
  484. }
  485. } else {
  486. throw new WIKI.Error.AuthAccountAlreadyExists()
  487. }
  488. }
  489. /**
  490. * Update an existing user
  491. *
  492. * @param {Object} param0 User ID and fields to update
  493. */
  494. static async updateUser ({ id, email, name, newPassword, groups, location, jobTitle, timezone }) {
  495. const usr = await WIKI.models.users.query().findById(id)
  496. if (usr) {
  497. let usrData = {}
  498. if (!_.isEmpty(email) && email !== usr.email) {
  499. const dupUsr = await WIKI.models.users.query().select('id').where({
  500. email,
  501. providerKey: usr.providerKey
  502. }).first()
  503. if (dupUsr) {
  504. throw new WIKI.Error.AuthAccountAlreadyExists()
  505. }
  506. usrData.email = email
  507. }
  508. if (!_.isEmpty(name) && name !== usr.name) {
  509. usrData.name = _.trim(name)
  510. }
  511. if (!_.isEmpty(newPassword)) {
  512. if (newPassword.length < 6) {
  513. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  514. }
  515. usrData.password = newPassword
  516. }
  517. if (_.isArray(groups)) {
  518. const usrGroupsRaw = await usr.$relatedQuery('groups')
  519. const usrGroups = _.map(usrGroupsRaw, 'id')
  520. // Relate added groups
  521. const addUsrGroups = _.difference(groups, usrGroups)
  522. for (const grp of addUsrGroups) {
  523. await usr.$relatedQuery('groups').relate(grp)
  524. }
  525. // Unrelate removed groups
  526. const remUsrGroups = _.difference(usrGroups, groups)
  527. for (const grp of remUsrGroups) {
  528. await usr.$relatedQuery('groups').unrelate().where('groupId', grp)
  529. }
  530. }
  531. if (!_.isEmpty(location) && location !== usr.location) {
  532. usrData.location = _.trim(location)
  533. }
  534. if (!_.isEmpty(jobTitle) && jobTitle !== usr.jobTitle) {
  535. usrData.jobTitle = _.trim(jobTitle)
  536. }
  537. if (!_.isEmpty(timezone) && timezone !== usr.timezone) {
  538. usrData.timezone = timezone
  539. }
  540. await WIKI.models.users.query().patch(usrData).findById(id)
  541. } else {
  542. throw new WIKI.Error.UserNotFound()
  543. }
  544. }
  545. /**
  546. * Delete a User
  547. *
  548. * @param {*} id User ID
  549. */
  550. static async deleteUser (id) {
  551. const usr = await WIKI.models.users.query().findById(id)
  552. if (usr) {
  553. await WIKI.models.userKeys.query().delete().where('userId', id)
  554. await WIKI.models.users.query().deleteById(id)
  555. } else {
  556. throw new WIKI.Error.UserNotFound()
  557. }
  558. }
  559. /**
  560. * Register a new user (client-side registration)
  561. *
  562. * @param {Object} param0 User fields
  563. * @param {Object} context GraphQL Context
  564. */
  565. static async register ({ email, password, name, verify = false, bypassChecks = false }, context) {
  566. const localStrg = await WIKI.models.authentication.getStrategy('local')
  567. // Check if self-registration is enabled
  568. if (localStrg.selfRegistration || bypassChecks) {
  569. // Input sanitization
  570. email = _.toLower(email)
  571. // Input validation
  572. const validation = validate({
  573. email,
  574. password,
  575. name
  576. }, {
  577. email: {
  578. email: true,
  579. length: {
  580. maximum: 255
  581. }
  582. },
  583. password: {
  584. presence: {
  585. allowEmpty: false
  586. },
  587. length: {
  588. minimum: 6
  589. }
  590. },
  591. name: {
  592. presence: {
  593. allowEmpty: false
  594. },
  595. length: {
  596. minimum: 2,
  597. maximum: 255
  598. }
  599. }
  600. }, { format: 'flat' })
  601. if (validation && validation.length > 0) {
  602. throw new WIKI.Error.InputInvalid(validation[0])
  603. }
  604. // Check if email domain is whitelisted
  605. if (_.get(localStrg, 'domainWhitelist.v', []).length > 0 && !bypassChecks) {
  606. const emailDomain = _.last(email.split('@'))
  607. if (!_.includes(localStrg.domainWhitelist.v, emailDomain)) {
  608. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  609. }
  610. }
  611. // Check if email already exists
  612. const usr = await WIKI.models.users.query().findOne({ email, providerKey: 'local' })
  613. if (!usr) {
  614. // Create the account
  615. const newUsr = await WIKI.models.users.query().insert({
  616. provider: 'local',
  617. email,
  618. name,
  619. password,
  620. locale: 'en',
  621. defaultEditor: 'markdown',
  622. tfaIsActive: false,
  623. isSystem: false,
  624. isActive: true,
  625. isVerified: false
  626. })
  627. // Assign to group(s)
  628. if (_.get(localStrg, 'autoEnrollGroups.v', []).length > 0) {
  629. await newUsr.$relatedQuery('groups').relate(localStrg.autoEnrollGroups.v)
  630. }
  631. if (verify) {
  632. // Create verification token
  633. const verificationToken = await WIKI.models.userKeys.generateToken({
  634. kind: 'verify',
  635. userId: newUsr.id
  636. })
  637. // Send verification email
  638. await WIKI.mail.send({
  639. template: 'accountVerify',
  640. to: email,
  641. subject: 'Verify your account',
  642. data: {
  643. preheadertext: 'Verify your account in order to gain access to the wiki.',
  644. title: 'Verify your account',
  645. content: 'Click the button below in order to verify your account and gain access to the wiki.',
  646. buttonLink: `${WIKI.config.host}/verify/${verificationToken}`,
  647. buttonText: 'Verify'
  648. },
  649. text: `You must open the following link in your browser to verify your account and gain access to the wiki: ${WIKI.config.host}/verify/${verificationToken}`
  650. })
  651. }
  652. return true
  653. } else {
  654. throw new WIKI.Error.AuthAccountAlreadyExists()
  655. }
  656. } else {
  657. throw new WIKI.Error.AuthRegistrationDisabled()
  658. }
  659. }
  660. static async getGuestUser () {
  661. const user = await WIKI.models.users.query().findById(2).withGraphJoined('groups').modifyGraph('groups', builder => {
  662. builder.select('groups.id', 'permissions')
  663. })
  664. if (!user) {
  665. WIKI.logger.error('CRITICAL ERROR: Guest user is missing!')
  666. process.exit(1)
  667. }
  668. user.permissions = user.getGlobalPermissions()
  669. return user
  670. }
  671. static async getRootUser () {
  672. let user = await WIKI.models.users.query().findById(1)
  673. if (!user) {
  674. WIKI.logger.error('CRITICAL ERROR: Root Administrator user is missing!')
  675. process.exit(1)
  676. }
  677. user.permissions = ['manage:system']
  678. return user
  679. }
  680. }