users.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867
  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. /**
  239. * Login a user
  240. */
  241. static async login (opts, context) {
  242. if (_.has(WIKI.auth.strategies, opts.strategy)) {
  243. const selStrategy = _.get(WIKI.auth.strategies, opts.strategy)
  244. const strInfo = _.find(WIKI.data.authentication, ['key', selStrategy.strategyKey])
  245. // Inject form user/pass
  246. if (strInfo.useForm) {
  247. _.set(context.req, 'body.email', opts.username)
  248. _.set(context.req, 'body.password', opts.password)
  249. }
  250. // Authenticate
  251. return new Promise((resolve, reject) => {
  252. WIKI.auth.passport.authenticate(selStrategy.strategyKey, {
  253. session: !strInfo.useForm,
  254. scope: strInfo.scopes ? strInfo.scopes : null
  255. }, async (err, user, info) => {
  256. if (err) { return reject(err) }
  257. if (!user) { return reject(new WIKI.Error.AuthLoginFailed()) }
  258. try {
  259. const resp = await WIKI.models.users.afterLoginChecks(user, context, {
  260. skipTFA: !strInfo.useForm,
  261. skipChangePwd: !strInfo.useForm
  262. })
  263. resolve(resp)
  264. } catch (err) {
  265. reject(err)
  266. }
  267. })(context.req, context.res, () => {})
  268. })
  269. } else {
  270. throw new WIKI.Error.AuthProviderInvalid()
  271. }
  272. }
  273. /**
  274. * Perform post-login checks
  275. */
  276. static async afterLoginChecks (user, context, { skipTFA, skipChangePwd } = { skipTFA: false, skipChangePwd: false }) {
  277. // Get redirect target
  278. user.groups = await user.$relatedQuery('groups').select('groups.id', 'permissions', 'redirectOnLogin')
  279. let redirect = '/'
  280. if (user.groups && user.groups.length > 0) {
  281. redirect = user.groups[0].redirectOnLogin
  282. }
  283. // Is 2FA required?
  284. if (!skipTFA) {
  285. if (user.tfaIsActive && user.tfaSecret) {
  286. try {
  287. const tfaToken = await WIKI.models.userKeys.generateToken({
  288. kind: 'tfa',
  289. userId: user.id
  290. })
  291. return {
  292. mustProvideTFA: true,
  293. continuationToken: tfaToken,
  294. redirect
  295. }
  296. } catch (errc) {
  297. WIKI.logger.warn(errc)
  298. throw new WIKI.Error.AuthGenericError()
  299. }
  300. } else if (WIKI.config.auth.enforce2FA || (user.tfaIsActive && !user.tfaSecret)) {
  301. try {
  302. const tfaQRImage = await user.generateTFA()
  303. const tfaToken = await WIKI.models.userKeys.generateToken({
  304. kind: 'tfaSetup',
  305. userId: user.id
  306. })
  307. return {
  308. mustSetupTFA: true,
  309. continuationToken: tfaToken,
  310. tfaQRImage,
  311. redirect
  312. }
  313. } catch (errc) {
  314. WIKI.logger.warn(errc)
  315. throw new WIKI.Error.AuthGenericError()
  316. }
  317. }
  318. }
  319. // Must Change Password?
  320. if (!skipChangePwd && user.mustChangePwd) {
  321. try {
  322. const pwdChangeToken = await WIKI.models.userKeys.generateToken({
  323. kind: 'changePwd',
  324. userId: user.id
  325. })
  326. return {
  327. mustChangePwd: true,
  328. continuationToken: pwdChangeToken,
  329. redirect
  330. }
  331. } catch (errc) {
  332. WIKI.logger.warn(errc)
  333. throw new WIKI.Error.AuthGenericError()
  334. }
  335. }
  336. return new Promise((resolve, reject) => {
  337. context.req.login(user, { session: false }, async errc => {
  338. if (errc) { return reject(errc) }
  339. const jwtToken = await WIKI.models.users.refreshToken(user)
  340. resolve({ jwt: jwtToken.token, redirect })
  341. })
  342. })
  343. }
  344. /**
  345. * Generate a new token for a user
  346. */
  347. static async refreshToken(user) {
  348. if (_.isSafeInteger(user)) {
  349. user = await WIKI.models.users.query().findById(user).withGraphFetched('groups').modifyGraph('groups', builder => {
  350. builder.select('groups.id', 'permissions')
  351. })
  352. if (!user) {
  353. WIKI.logger.warn(`Failed to refresh token for user ${user}: Not found.`)
  354. throw new WIKI.Error.AuthGenericError()
  355. }
  356. if (!user.isActive) {
  357. WIKI.logger.warn(`Failed to refresh token for user ${user}: Inactive.`)
  358. throw new WIKI.Error.AuthAccountBanned()
  359. }
  360. } else if (_.isNil(user.groups)) {
  361. user.groups = await user.$relatedQuery('groups').select('groups.id', 'permissions')
  362. }
  363. // Update Last Login Date
  364. // -> Bypass Objection.js to avoid updating the updatedAt field
  365. await WIKI.models.knex('users').where('id', user.id).update({ lastLoginAt: new Date().toISOString() })
  366. return {
  367. token: jwt.sign({
  368. id: user.id,
  369. email: user.email,
  370. name: user.name,
  371. av: user.pictureUrl,
  372. tz: user.timezone,
  373. lc: user.localeCode,
  374. df: user.dateFormat,
  375. ap: user.appearance,
  376. // defaultEditor: user.defaultEditor,
  377. permissions: user.getGlobalPermissions(),
  378. groups: user.getGroups()
  379. }, {
  380. key: WIKI.config.certs.private,
  381. passphrase: WIKI.config.sessionSecret
  382. }, {
  383. algorithm: 'RS256',
  384. expiresIn: WIKI.config.auth.tokenExpiration,
  385. audience: WIKI.config.auth.audience,
  386. issuer: 'urn:wiki.js'
  387. }),
  388. user
  389. }
  390. }
  391. /**
  392. * Verify a TFA login
  393. */
  394. static async loginTFA ({ securityCode, continuationToken, setup }, context) {
  395. if (securityCode.length === 6 && continuationToken.length > 1) {
  396. const user = await WIKI.models.userKeys.validateToken({
  397. kind: setup ? 'tfaSetup' : 'tfa',
  398. token: continuationToken,
  399. skipDelete: setup
  400. })
  401. if (user) {
  402. if (user.verifyTFA(securityCode)) {
  403. if (setup) {
  404. await user.enableTFA()
  405. }
  406. return WIKI.models.users.afterLoginChecks(user, context, { skipTFA: true })
  407. } else {
  408. throw new WIKI.Error.AuthTFAFailed()
  409. }
  410. }
  411. }
  412. throw new WIKI.Error.AuthTFAInvalid()
  413. }
  414. /**
  415. * Change Password from a Mandatory Password Change after Login
  416. */
  417. static async loginChangePassword ({ continuationToken, newPassword }, context) {
  418. if (!newPassword || newPassword.length < 6) {
  419. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  420. }
  421. const usr = await WIKI.models.userKeys.validateToken({
  422. kind: 'changePwd',
  423. token: continuationToken
  424. })
  425. if (usr) {
  426. await WIKI.models.users.query().patch({
  427. password: newPassword,
  428. mustChangePwd: false
  429. }).findById(usr.id)
  430. return new Promise((resolve, reject) => {
  431. context.req.logIn(usr, { session: false }, async err => {
  432. if (err) { return reject(err) }
  433. const jwtToken = await WIKI.models.users.refreshToken(usr)
  434. resolve({ jwt: jwtToken.token })
  435. })
  436. })
  437. } else {
  438. throw new WIKI.Error.UserNotFound()
  439. }
  440. }
  441. /**
  442. * Send a password reset request
  443. */
  444. static async loginForgotPassword ({ email }, context) {
  445. const usr = await WIKI.models.users.query().where({
  446. email,
  447. providerKey: 'local'
  448. }).first()
  449. if (!usr) {
  450. WIKI.logger.debug(`Password reset attempt on nonexistant local account ${email}: [DISCARDED]`)
  451. return
  452. }
  453. const resetToken = await WIKI.models.userKeys.generateToken({
  454. userId: usr.id,
  455. kind: 'resetPwd'
  456. })
  457. await WIKI.mail.send({
  458. template: 'accountResetPwd',
  459. to: email,
  460. subject: `Password Reset Request`,
  461. data: {
  462. preheadertext: `A password reset was requested for ${WIKI.config.title}`,
  463. title: `A password reset was requested for ${WIKI.config.title}`,
  464. content: `Click the button below to reset your password. If you didn't request this password reset, simply discard this email.`,
  465. buttonLink: `${WIKI.config.host}/login-reset/${resetToken}`,
  466. buttonText: 'Reset Password'
  467. },
  468. text: `A password reset was requested for wiki ${WIKI.config.title}. Open the following link to proceed: ${WIKI.config.host}/login-reset/${resetToken}`
  469. })
  470. }
  471. /**
  472. * Create a new user
  473. *
  474. * @param {Object} param0 User Fields
  475. */
  476. static async createNewUser ({ providerKey, email, passwordRaw, name, groups, mustChangePassword, sendWelcomeEmail }) {
  477. // Input sanitization
  478. email = _.toLower(email)
  479. // Input validation
  480. let validation = null
  481. if (providerKey === 'local') {
  482. validation = validate({
  483. email,
  484. passwordRaw,
  485. name
  486. }, {
  487. email: {
  488. email: true,
  489. length: {
  490. maximum: 255
  491. }
  492. },
  493. passwordRaw: {
  494. presence: {
  495. allowEmpty: false
  496. },
  497. length: {
  498. minimum: 6
  499. }
  500. },
  501. name: {
  502. presence: {
  503. allowEmpty: false
  504. },
  505. length: {
  506. minimum: 2,
  507. maximum: 255
  508. }
  509. }
  510. }, { format: 'flat' })
  511. } else {
  512. validation = validate({
  513. email,
  514. name
  515. }, {
  516. email: {
  517. email: true,
  518. length: {
  519. maximum: 255
  520. }
  521. },
  522. name: {
  523. presence: {
  524. allowEmpty: false
  525. },
  526. length: {
  527. minimum: 2,
  528. maximum: 255
  529. }
  530. }
  531. }, { format: 'flat' })
  532. }
  533. if (validation && validation.length > 0) {
  534. throw new WIKI.Error.InputInvalid(validation[0])
  535. }
  536. // Check if email already exists
  537. const usr = await WIKI.models.users.query().findOne({ email, providerKey })
  538. if (!usr) {
  539. // Create the account
  540. let newUsrData = {
  541. providerKey,
  542. email,
  543. name,
  544. locale: 'en',
  545. defaultEditor: 'markdown',
  546. tfaIsActive: false,
  547. isSystem: false,
  548. isActive: true,
  549. isVerified: true,
  550. mustChangePwd: false
  551. }
  552. if (providerKey === `local`) {
  553. newUsrData.password = passwordRaw
  554. newUsrData.mustChangePwd = (mustChangePassword === true)
  555. }
  556. const newUsr = await WIKI.models.users.query().insert(newUsrData)
  557. // Assign to group(s)
  558. if (groups.length > 0) {
  559. await newUsr.$relatedQuery('groups').relate(groups)
  560. }
  561. if (sendWelcomeEmail) {
  562. // Send welcome email
  563. await WIKI.mail.send({
  564. template: 'accountWelcome',
  565. to: email,
  566. subject: `Welcome to the wiki ${WIKI.config.title}`,
  567. data: {
  568. preheadertext: `You've been invited to the wiki ${WIKI.config.title}`,
  569. title: `You've been invited to the wiki ${WIKI.config.title}`,
  570. content: `Click the button below to access the wiki.`,
  571. buttonLink: `${WIKI.config.host}/login`,
  572. buttonText: 'Login'
  573. },
  574. text: `You've been invited to the wiki ${WIKI.config.title}: ${WIKI.config.host}/login`
  575. })
  576. }
  577. } else {
  578. throw new WIKI.Error.AuthAccountAlreadyExists()
  579. }
  580. }
  581. /**
  582. * Update an existing user
  583. *
  584. * @param {Object} param0 User ID and fields to update
  585. */
  586. static async updateUser ({ id, email, name, newPassword, groups, location, jobTitle, timezone, dateFormat, appearance }) {
  587. const usr = await WIKI.models.users.query().findById(id)
  588. if (usr) {
  589. let usrData = {}
  590. if (!_.isEmpty(email) && email !== usr.email) {
  591. const dupUsr = await WIKI.models.users.query().select('id').where({
  592. email,
  593. providerKey: usr.providerKey
  594. }).first()
  595. if (dupUsr) {
  596. throw new WIKI.Error.AuthAccountAlreadyExists()
  597. }
  598. usrData.email = email
  599. }
  600. if (!_.isEmpty(name) && name !== usr.name) {
  601. usrData.name = _.trim(name)
  602. }
  603. if (!_.isEmpty(newPassword)) {
  604. if (newPassword.length < 6) {
  605. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  606. }
  607. usrData.password = newPassword
  608. }
  609. if (_.isArray(groups)) {
  610. const usrGroupsRaw = await usr.$relatedQuery('groups')
  611. const usrGroups = _.map(usrGroupsRaw, 'id')
  612. // Relate added groups
  613. const addUsrGroups = _.difference(groups, usrGroups)
  614. for (const grp of addUsrGroups) {
  615. await usr.$relatedQuery('groups').relate(grp)
  616. }
  617. // Unrelate removed groups
  618. const remUsrGroups = _.difference(usrGroups, groups)
  619. for (const grp of remUsrGroups) {
  620. await usr.$relatedQuery('groups').unrelate().where('groupId', grp)
  621. }
  622. }
  623. if (!_.isEmpty(location) && location !== usr.location) {
  624. usrData.location = _.trim(location)
  625. }
  626. if (!_.isEmpty(jobTitle) && jobTitle !== usr.jobTitle) {
  627. usrData.jobTitle = _.trim(jobTitle)
  628. }
  629. if (!_.isEmpty(timezone) && timezone !== usr.timezone) {
  630. usrData.timezone = timezone
  631. }
  632. if (!_.isNil(dateFormat) && dateFormat !== usr.dateFormat) {
  633. usrData.dateFormat = dateFormat
  634. }
  635. if (!_.isNil(appearance) && appearance !== usr.appearance) {
  636. usrData.appearance = appearance
  637. }
  638. await WIKI.models.users.query().patch(usrData).findById(id)
  639. } else {
  640. throw new WIKI.Error.UserNotFound()
  641. }
  642. }
  643. /**
  644. * Delete a User
  645. *
  646. * @param {*} id User ID
  647. */
  648. static async deleteUser (id, replaceId) {
  649. const usr = await WIKI.models.users.query().findById(id)
  650. if (usr) {
  651. await WIKI.models.assets.query().patch({ authorId: replaceId }).where('authorId', id)
  652. await WIKI.models.comments.query().patch({ authorId: replaceId }).where('authorId', id)
  653. await WIKI.models.pageHistory.query().patch({ authorId: replaceId }).where('authorId', id)
  654. await WIKI.models.pages.query().patch({ authorId: replaceId }).where('authorId', id)
  655. await WIKI.models.pages.query().patch({ creatorId: replaceId }).where('creatorId', id)
  656. await WIKI.models.userKeys.query().delete().where('userId', id)
  657. await WIKI.models.users.query().deleteById(id)
  658. } else {
  659. throw new WIKI.Error.UserNotFound()
  660. }
  661. }
  662. /**
  663. * Register a new user (client-side registration)
  664. *
  665. * @param {Object} param0 User fields
  666. * @param {Object} context GraphQL Context
  667. */
  668. static async register ({ email, password, name, verify = false, bypassChecks = false }, context) {
  669. const localStrg = await WIKI.models.authentication.getStrategy('local')
  670. // Check if self-registration is enabled
  671. if (localStrg.selfRegistration || bypassChecks) {
  672. // Input sanitization
  673. email = _.toLower(email)
  674. // Input validation
  675. const validation = validate({
  676. email,
  677. password,
  678. name
  679. }, {
  680. email: {
  681. email: true,
  682. length: {
  683. maximum: 255
  684. }
  685. },
  686. password: {
  687. presence: {
  688. allowEmpty: false
  689. },
  690. length: {
  691. minimum: 6
  692. }
  693. },
  694. name: {
  695. presence: {
  696. allowEmpty: false
  697. },
  698. length: {
  699. minimum: 2,
  700. maximum: 255
  701. }
  702. }
  703. }, { format: 'flat' })
  704. if (validation && validation.length > 0) {
  705. throw new WIKI.Error.InputInvalid(validation[0])
  706. }
  707. // Check if email domain is whitelisted
  708. if (_.get(localStrg, 'domainWhitelist.v', []).length > 0 && !bypassChecks) {
  709. const emailDomain = _.last(email.split('@'))
  710. if (!_.includes(localStrg.domainWhitelist.v, emailDomain)) {
  711. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  712. }
  713. }
  714. // Check if email already exists
  715. const usr = await WIKI.models.users.query().findOne({ email, providerKey: 'local' })
  716. if (!usr) {
  717. // Create the account
  718. const newUsr = await WIKI.models.users.query().insert({
  719. provider: 'local',
  720. email,
  721. name,
  722. password,
  723. locale: 'en',
  724. defaultEditor: 'markdown',
  725. tfaIsActive: false,
  726. isSystem: false,
  727. isActive: true,
  728. isVerified: false
  729. })
  730. // Assign to group(s)
  731. if (_.get(localStrg, 'autoEnrollGroups.v', []).length > 0) {
  732. await newUsr.$relatedQuery('groups').relate(localStrg.autoEnrollGroups.v)
  733. }
  734. if (verify) {
  735. // Create verification token
  736. const verificationToken = await WIKI.models.userKeys.generateToken({
  737. kind: 'verify',
  738. userId: newUsr.id
  739. })
  740. // Send verification email
  741. await WIKI.mail.send({
  742. template: 'accountVerify',
  743. to: email,
  744. subject: 'Verify your account',
  745. data: {
  746. preheadertext: 'Verify your account in order to gain access to the wiki.',
  747. title: 'Verify your account',
  748. content: 'Click the button below in order to verify your account and gain access to the wiki.',
  749. buttonLink: `${WIKI.config.host}/verify/${verificationToken}`,
  750. buttonText: 'Verify'
  751. },
  752. 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}`
  753. })
  754. }
  755. return true
  756. } else {
  757. throw new WIKI.Error.AuthAccountAlreadyExists()
  758. }
  759. } else {
  760. throw new WIKI.Error.AuthRegistrationDisabled()
  761. }
  762. }
  763. /**
  764. * Logout the current user
  765. */
  766. static async logout (context) {
  767. if (!context.req.user || context.req.user.id === 2) {
  768. return '/'
  769. }
  770. const usr = await WIKI.models.users.query().findById(context.req.user.id).select('providerKey')
  771. const provider = _.find(WIKI.auth.strategies, ['key', usr.providerKey])
  772. return provider.logout ? provider.logout(provider.config) : '/'
  773. }
  774. static async getGuestUser () {
  775. const user = await WIKI.models.users.query().findById(2).withGraphJoined('groups').modifyGraph('groups', builder => {
  776. builder.select('groups.id', 'permissions')
  777. })
  778. if (!user) {
  779. WIKI.logger.error('CRITICAL ERROR: Guest user is missing!')
  780. process.exit(1)
  781. }
  782. user.permissions = user.getGlobalPermissions()
  783. return user
  784. }
  785. static async getRootUser () {
  786. let user = await WIKI.models.users.query().findById(1)
  787. if (!user) {
  788. WIKI.logger.error('CRITICAL ERROR: Root Administrator user is missing!')
  789. process.exit(1)
  790. }
  791. user.permissions = ['manage:system']
  792. return user
  793. }
  794. }