users.mjs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880
  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) {
  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. }, {
  367. key: WIKI.config.auth.certs.private,
  368. passphrase: WIKI.config.auth.secret
  369. }, {
  370. algorithm: 'RS256',
  371. expiresIn: WIKI.config.auth.tokenExpiration,
  372. audience: WIKI.config.auth.audience,
  373. issuer: 'urn:wiki.js'
  374. }),
  375. user
  376. }
  377. }
  378. /**
  379. * Verify a TFA login
  380. */
  381. static async loginTFA ({ securityCode, continuationToken, setup }, context) {
  382. if (securityCode.length === 6 && continuationToken.length > 1) {
  383. const user = await WIKI.db.userKeys.validateToken({
  384. kind: setup ? 'tfaSetup' : 'tfa',
  385. token: continuationToken,
  386. skipDelete: setup
  387. })
  388. if (user) {
  389. if (user.verifyTFA(securityCode)) {
  390. if (setup) {
  391. await user.enableTFA()
  392. }
  393. return WIKI.db.users.afterLoginChecks(user, context, { skipTFA: true })
  394. } else {
  395. throw new WIKI.Error.AuthTFAFailed()
  396. }
  397. }
  398. }
  399. throw new WIKI.Error.AuthTFAInvalid()
  400. }
  401. /**
  402. * Change Password from a Mandatory Password Change after Login
  403. */
  404. static async loginChangePassword ({ continuationToken, newPassword }, context) {
  405. if (!newPassword || newPassword.length < 6) {
  406. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  407. }
  408. const usr = await WIKI.db.userKeys.validateToken({
  409. kind: 'changePwd',
  410. token: continuationToken
  411. })
  412. if (usr) {
  413. await WIKI.db.users.query().patch({
  414. password: newPassword,
  415. mustChangePwd: false
  416. }).findById(usr.id)
  417. return new Promise((resolve, reject) => {
  418. context.req.logIn(usr, { session: false }, async err => {
  419. if (err) { return reject(err) }
  420. const jwtToken = await WIKI.db.users.refreshToken(usr)
  421. resolve({ jwt: jwtToken.token })
  422. })
  423. })
  424. } else {
  425. throw new WIKI.Error.UserNotFound()
  426. }
  427. }
  428. /**
  429. * Send a password reset request
  430. */
  431. static async loginForgotPassword ({ email }, context) {
  432. const usr = await WIKI.db.users.query().where({
  433. email,
  434. providerKey: 'local'
  435. }).first()
  436. if (!usr) {
  437. WIKI.logger.debug(`Password reset attempt on nonexistant local account ${email}: [DISCARDED]`)
  438. return
  439. }
  440. const resetToken = await WIKI.db.userKeys.generateToken({
  441. userId: usr.id,
  442. kind: 'resetPwd'
  443. })
  444. await WIKI.mail.send({
  445. template: 'accountResetPwd',
  446. to: email,
  447. subject: `Password Reset Request`,
  448. data: {
  449. preheadertext: `A password reset was requested for ${WIKI.config.title}`,
  450. title: `A password reset was requested for ${WIKI.config.title}`,
  451. content: `Click the button below to reset your password. If you didn't request this password reset, simply discard this email.`,
  452. buttonLink: `${WIKI.config.host}/login-reset/${resetToken}`,
  453. buttonText: 'Reset Password'
  454. },
  455. text: `A password reset was requested for wiki ${WIKI.config.title}. Open the following link to proceed: ${WIKI.config.host}/login-reset/${resetToken}`
  456. })
  457. }
  458. /**
  459. * Create a new user
  460. *
  461. * @param {Object} param0 User Fields
  462. */
  463. static async createNewUser ({ email, password, name, groups, mustChangePassword = false, sendWelcomeEmail = false }) {
  464. // Input sanitization
  465. email = email.toLowerCase().trim()
  466. // Input validation
  467. const validation = validate({
  468. email,
  469. password,
  470. name
  471. }, {
  472. email: {
  473. email: true,
  474. length: {
  475. maximum: 255
  476. }
  477. },
  478. password: {
  479. presence: {
  480. allowEmpty: false
  481. },
  482. length: {
  483. minimum: 6
  484. }
  485. },
  486. name: {
  487. presence: {
  488. allowEmpty: false
  489. },
  490. length: {
  491. minimum: 2,
  492. maximum: 255
  493. }
  494. }
  495. }, { format: 'flat' })
  496. if (validation && validation.length > 0) {
  497. throw new Error(`ERR_INVALID_INPUT: ${validation[0]}`)
  498. }
  499. // Check if email already exists
  500. const usr = await WIKI.db.users.query().findOne({ email })
  501. if (usr) {
  502. throw new Error('ERR_ACCOUNT_ALREADY_EXIST')
  503. }
  504. // Create the account
  505. const localAuth = await WIKI.db.authentication.getStrategy('local')
  506. const newUsr = await WIKI.db.users.query().insert({
  507. email,
  508. name,
  509. auth: {
  510. [localAuth.id]: {
  511. password: await bcrypt.hash(password, 12),
  512. mustChangePwd: mustChangePassword,
  513. restrictLogin: false,
  514. tfaRequired: false,
  515. tfaSecret: ''
  516. }
  517. },
  518. localeCode: 'en',
  519. hasAvatar: false,
  520. isSystem: false,
  521. isActive: true,
  522. isVerified: true,
  523. meta: {
  524. jobTitle: '',
  525. location: '',
  526. pronouns: ''
  527. },
  528. prefs: {
  529. cvd: 'none',
  530. timezone: WIKI.config.userDefaults.timezone || 'America/New_York',
  531. appearance: 'site',
  532. dateFormat: WIKI.config.userDefaults.dateFormat || 'YYYY-MM-DD',
  533. timeFormat: WIKI.config.userDefaults.timeFormat || '12h'
  534. }
  535. })
  536. // Assign to group(s)
  537. if (groups.length > 0) {
  538. await newUsr.$relatedQuery('groups').relate(groups)
  539. }
  540. if (sendWelcomeEmail) {
  541. // Send welcome email
  542. await WIKI.mail.send({
  543. template: 'accountWelcome',
  544. to: email,
  545. subject: `Welcome to the wiki ${WIKI.config.title}`,
  546. data: {
  547. preheadertext: `You've been invited to the wiki ${WIKI.config.title}`,
  548. title: `You've been invited to the wiki ${WIKI.config.title}`,
  549. content: `Click the button below to access the wiki.`,
  550. buttonLink: `${WIKI.config.host}/login`,
  551. buttonText: 'Login'
  552. },
  553. text: `You've been invited to the wiki ${WIKI.config.title}: ${WIKI.config.host}/login`
  554. })
  555. }
  556. }
  557. /**
  558. * Update an existing user
  559. *
  560. * @param {Object} param0 User ID and fields to update
  561. */
  562. static async updateUser (id, { email, name, groups, isVerified, isActive, meta, prefs }) {
  563. const usr = await WIKI.db.users.query().findById(id)
  564. if (usr) {
  565. let usrData = {}
  566. if (!isEmpty(email) && email !== usr.email) {
  567. const dupUsr = await WIKI.db.users.query().select('id').where({ email }).first()
  568. if (dupUsr) {
  569. throw new WIKI.Error.AuthAccountAlreadyExists()
  570. }
  571. usrData.email = email.toLowerCase()
  572. }
  573. if (!isEmpty(name) && name !== usr.name) {
  574. usrData.name = name.trim()
  575. }
  576. if (isArray(groups)) {
  577. const usrGroupsRaw = await usr.$relatedQuery('groups')
  578. const usrGroups = usrGroupsRaw.map(g => g.id)
  579. // Relate added groups
  580. const addUsrGroups = difference(groups, usrGroups)
  581. for (const grp of addUsrGroups) {
  582. await usr.$relatedQuery('groups').relate(grp)
  583. }
  584. // Unrelate removed groups
  585. const remUsrGroups = difference(usrGroups, groups)
  586. for (const grp of remUsrGroups) {
  587. await usr.$relatedQuery('groups').unrelate().where('groupId', grp)
  588. }
  589. }
  590. if (!isNil(isVerified)) {
  591. usrData.isVerified = isVerified
  592. }
  593. if (!isNil(isActive)) {
  594. usrData.isVerified = isActive
  595. }
  596. if (!isEmpty(meta)) {
  597. usrData.meta = meta
  598. }
  599. if (!isEmpty(prefs)) {
  600. usrData.prefs = prefs
  601. }
  602. await WIKI.db.users.query().patch(usrData).findById(id)
  603. } else {
  604. throw new WIKI.Error.UserNotFound()
  605. }
  606. }
  607. /**
  608. * Delete a User
  609. *
  610. * @param {*} id User ID
  611. */
  612. static async deleteUser (id, replaceId) {
  613. const usr = await WIKI.db.users.query().findById(id)
  614. if (usr) {
  615. await WIKI.db.assets.query().patch({ authorId: replaceId }).where('authorId', id)
  616. await WIKI.db.comments.query().patch({ authorId: replaceId }).where('authorId', id)
  617. await WIKI.db.pageHistory.query().patch({ authorId: replaceId }).where('authorId', id)
  618. await WIKI.db.pages.query().patch({ authorId: replaceId }).where('authorId', id)
  619. await WIKI.db.pages.query().patch({ creatorId: replaceId }).where('creatorId', id)
  620. await WIKI.db.userKeys.query().delete().where('userId', id)
  621. await WIKI.db.users.query().deleteById(id)
  622. } else {
  623. throw new WIKI.Error.UserNotFound()
  624. }
  625. }
  626. /**
  627. * Register a new user (client-side registration)
  628. *
  629. * @param {Object} param0 User fields
  630. * @param {Object} context GraphQL Context
  631. */
  632. static async register ({ email, password, name, verify = false, bypassChecks = false }, context) {
  633. const localStrg = await WIKI.db.authentication.getStrategy('local')
  634. // Check if self-registration is enabled
  635. if (localStrg.selfRegistration || bypassChecks) {
  636. // Input sanitization
  637. email = email.toLowerCase()
  638. // Input validation
  639. const validation = validate({
  640. email,
  641. password,
  642. name
  643. }, {
  644. email: {
  645. email: true,
  646. length: {
  647. maximum: 255
  648. }
  649. },
  650. password: {
  651. presence: {
  652. allowEmpty: false
  653. },
  654. length: {
  655. minimum: 6
  656. }
  657. },
  658. name: {
  659. presence: {
  660. allowEmpty: false
  661. },
  662. length: {
  663. minimum: 2,
  664. maximum: 255
  665. }
  666. }
  667. }, { format: 'flat' })
  668. if (validation && validation.length > 0) {
  669. throw new WIKI.Error.InputInvalid(validation[0])
  670. }
  671. // Check if email domain is whitelisted
  672. if (get(localStrg, 'domainWhitelist.v', []).length > 0 && !bypassChecks) {
  673. const emailDomain = last(email.split('@'))
  674. if (!localStrg.domainWhitelist.v.includes(emailDomain)) {
  675. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  676. }
  677. }
  678. // Check if email already exists
  679. const usr = await WIKI.db.users.query().findOne({ email, providerKey: 'local' })
  680. if (!usr) {
  681. // Create the account
  682. const newUsr = await WIKI.db.users.query().insert({
  683. provider: 'local',
  684. email,
  685. name,
  686. password,
  687. locale: 'en',
  688. defaultEditor: 'markdown',
  689. tfaIsActive: false,
  690. isSystem: false,
  691. isActive: true,
  692. isVerified: false
  693. })
  694. // Assign to group(s)
  695. if (get(localStrg, 'autoEnrollGroups.v', []).length > 0) {
  696. await newUsr.$relatedQuery('groups').relate(localStrg.autoEnrollGroups.v)
  697. }
  698. if (verify) {
  699. // Create verification token
  700. const verificationToken = await WIKI.db.userKeys.generateToken({
  701. kind: 'verify',
  702. userId: newUsr.id
  703. })
  704. // Send verification email
  705. await WIKI.mail.send({
  706. template: 'accountVerify',
  707. to: email,
  708. subject: 'Verify your account',
  709. data: {
  710. preheadertext: 'Verify your account in order to gain access to the wiki.',
  711. title: 'Verify your account',
  712. content: 'Click the button below in order to verify your account and gain access to the wiki.',
  713. buttonLink: `${WIKI.config.host}/verify/${verificationToken}`,
  714. buttonText: 'Verify'
  715. },
  716. 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}`
  717. })
  718. }
  719. return true
  720. } else {
  721. throw new WIKI.Error.AuthAccountAlreadyExists()
  722. }
  723. } else {
  724. throw new WIKI.Error.AuthRegistrationDisabled()
  725. }
  726. }
  727. /**
  728. * Logout the current user
  729. */
  730. static async logout (context) {
  731. if (!context.req.user || context.req.user.id === WIKI.config.auth.guestUserId) {
  732. return '/'
  733. }
  734. if (context.req.user.strategyId && has(WIKI.auth.strategies, context.req.user.strategyId)) {
  735. const selStrategy = WIKI.auth.strategies[context.req.user.strategyId]
  736. if (!selStrategy.isEnabled) {
  737. throw new WIKI.Error.AuthProviderInvalid()
  738. }
  739. const provider = find(WIKI.data.authentication, ['key', selStrategy.module])
  740. if (provider.logout) {
  741. return provider.logout(provider.config)
  742. }
  743. }
  744. return '/'
  745. }
  746. static async getGuestUser () {
  747. const user = await WIKI.db.users.query().findById(WIKI.config.auth.guestUserId).withGraphJoined('groups').modifyGraph('groups', builder => {
  748. builder.select('groups.id', 'permissions')
  749. })
  750. if (!user) {
  751. WIKI.logger.error('CRITICAL ERROR: Guest user is missing!')
  752. process.exit(1)
  753. }
  754. user.permissions = user.getPermissions()
  755. return user
  756. }
  757. static async getRootUser () {
  758. let user = await WIKI.db.users.query().findById(WIKI.config.auth.rootAdminUserId)
  759. if (!user) {
  760. WIKI.logger.error('CRITICAL ERROR: Root Administrator user is missing!')
  761. process.exit(1)
  762. }
  763. user.permissions = ['manage:system']
  764. return user
  765. }
  766. /**
  767. * Add / Update User Avatar Data
  768. */
  769. static async updateUserAvatarData (userId, data) {
  770. try {
  771. WIKI.logger.debug(`Updating user ${userId} avatar data...`)
  772. if (data.length > 1024 * 1024) {
  773. throw new Error('Avatar image filesize is too large. 1MB max.')
  774. }
  775. const existing = await WIKI.db.knex('userAvatars').select('id').where('id', userId).first()
  776. if (existing) {
  777. await WIKI.db.knex('userAvatars').where({
  778. id: userId
  779. }).update({
  780. data
  781. })
  782. } else {
  783. await WIKI.db.knex('userAvatars').insert({
  784. id: userId,
  785. data
  786. })
  787. }
  788. } catch (err) {
  789. WIKI.logger.warn(`Failed to process binary thumbnail data for user ${userId}: ${err.message}`)
  790. }
  791. }
  792. static async getUserAvatarData (userId) {
  793. try {
  794. const usrData = await WIKI.db.knex('userAvatars').where('id', userId).first()
  795. if (usrData) {
  796. return usrData.data
  797. } else {
  798. return null
  799. }
  800. } catch (err) {
  801. WIKI.logger.warn(`Failed to process binary thumbnail data for user ${userId}`)
  802. }
  803. }
  804. }