users.mjs 26 KB

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