users.js 25 KB

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