users.mjs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879
  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. hasAvatar: false,
  519. isSystem: false,
  520. isActive: true,
  521. isVerified: true,
  522. meta: {
  523. jobTitle: '',
  524. location: '',
  525. pronouns: ''
  526. },
  527. prefs: {
  528. cvd: 'none',
  529. timezone: WIKI.config.userDefaults.timezone || 'America/New_York',
  530. appearance: 'site',
  531. dateFormat: WIKI.config.userDefaults.dateFormat || 'YYYY-MM-DD',
  532. timeFormat: WIKI.config.userDefaults.timeFormat || '12h'
  533. }
  534. })
  535. // Assign to group(s)
  536. if (groups.length > 0) {
  537. await newUsr.$relatedQuery('groups').relate(groups)
  538. }
  539. if (sendWelcomeEmail) {
  540. // Send welcome email
  541. await WIKI.mail.send({
  542. template: 'accountWelcome',
  543. to: email,
  544. subject: `Welcome to the wiki ${WIKI.config.title}`,
  545. data: {
  546. preheadertext: `You've been invited to the wiki ${WIKI.config.title}`,
  547. title: `You've been invited to the wiki ${WIKI.config.title}`,
  548. content: `Click the button below to access the wiki.`,
  549. buttonLink: `${WIKI.config.host}/login`,
  550. buttonText: 'Login'
  551. },
  552. text: `You've been invited to the wiki ${WIKI.config.title}: ${WIKI.config.host}/login`
  553. })
  554. }
  555. }
  556. /**
  557. * Update an existing user
  558. *
  559. * @param {Object} param0 User ID and fields to update
  560. */
  561. static async updateUser (id, { email, name, groups, isVerified, isActive, meta, prefs }) {
  562. const usr = await WIKI.db.users.query().findById(id)
  563. if (usr) {
  564. let usrData = {}
  565. if (!isEmpty(email) && email !== usr.email) {
  566. const dupUsr = await WIKI.db.users.query().select('id').where({ email }).first()
  567. if (dupUsr) {
  568. throw new WIKI.Error.AuthAccountAlreadyExists()
  569. }
  570. usrData.email = email.toLowerCase()
  571. }
  572. if (!isEmpty(name) && name !== usr.name) {
  573. usrData.name = name.trim()
  574. }
  575. if (isArray(groups)) {
  576. const usrGroupsRaw = await usr.$relatedQuery('groups')
  577. const usrGroups = usrGroupsRaw.map(g => g.id)
  578. // Relate added groups
  579. const addUsrGroups = difference(groups, usrGroups)
  580. for (const grp of addUsrGroups) {
  581. await usr.$relatedQuery('groups').relate(grp)
  582. }
  583. // Unrelate removed groups
  584. const remUsrGroups = difference(usrGroups, groups)
  585. for (const grp of remUsrGroups) {
  586. await usr.$relatedQuery('groups').unrelate().where('groupId', grp)
  587. }
  588. }
  589. if (!isNil(isVerified)) {
  590. usrData.isVerified = isVerified
  591. }
  592. if (!isNil(isActive)) {
  593. usrData.isVerified = isActive
  594. }
  595. if (!isEmpty(meta)) {
  596. usrData.meta = meta
  597. }
  598. if (!isEmpty(prefs)) {
  599. usrData.prefs = prefs
  600. }
  601. await WIKI.db.users.query().patch(usrData).findById(id)
  602. } else {
  603. throw new WIKI.Error.UserNotFound()
  604. }
  605. }
  606. /**
  607. * Delete a User
  608. *
  609. * @param {*} id User ID
  610. */
  611. static async deleteUser (id, replaceId) {
  612. const usr = await WIKI.db.users.query().findById(id)
  613. if (usr) {
  614. await WIKI.db.assets.query().patch({ authorId: replaceId }).where('authorId', id)
  615. await WIKI.db.comments.query().patch({ authorId: replaceId }).where('authorId', id)
  616. await WIKI.db.pageHistory.query().patch({ authorId: replaceId }).where('authorId', id)
  617. await WIKI.db.pages.query().patch({ authorId: replaceId }).where('authorId', id)
  618. await WIKI.db.pages.query().patch({ creatorId: replaceId }).where('creatorId', id)
  619. await WIKI.db.userKeys.query().delete().where('userId', id)
  620. await WIKI.db.users.query().deleteById(id)
  621. } else {
  622. throw new WIKI.Error.UserNotFound()
  623. }
  624. }
  625. /**
  626. * Register a new user (client-side registration)
  627. *
  628. * @param {Object} param0 User fields
  629. * @param {Object} context GraphQL Context
  630. */
  631. static async register ({ email, password, name, verify = false, bypassChecks = false }, context) {
  632. const localStrg = await WIKI.db.authentication.getStrategy('local')
  633. // Check if self-registration is enabled
  634. if (localStrg.selfRegistration || bypassChecks) {
  635. // Input sanitization
  636. email = email.toLowerCase()
  637. // Input validation
  638. const validation = validate({
  639. email,
  640. password,
  641. name
  642. }, {
  643. email: {
  644. email: true,
  645. length: {
  646. maximum: 255
  647. }
  648. },
  649. password: {
  650. presence: {
  651. allowEmpty: false
  652. },
  653. length: {
  654. minimum: 6
  655. }
  656. },
  657. name: {
  658. presence: {
  659. allowEmpty: false
  660. },
  661. length: {
  662. minimum: 2,
  663. maximum: 255
  664. }
  665. }
  666. }, { format: 'flat' })
  667. if (validation && validation.length > 0) {
  668. throw new WIKI.Error.InputInvalid(validation[0])
  669. }
  670. // Check if email domain is whitelisted
  671. if (get(localStrg, 'domainWhitelist.v', []).length > 0 && !bypassChecks) {
  672. const emailDomain = last(email.split('@'))
  673. if (!localStrg.domainWhitelist.v.includes(emailDomain)) {
  674. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  675. }
  676. }
  677. // Check if email already exists
  678. const usr = await WIKI.db.users.query().findOne({ email, providerKey: 'local' })
  679. if (!usr) {
  680. // Create the account
  681. const newUsr = await WIKI.db.users.query().insert({
  682. provider: 'local',
  683. email,
  684. name,
  685. password,
  686. locale: 'en',
  687. defaultEditor: 'markdown',
  688. tfaIsActive: false,
  689. isSystem: false,
  690. isActive: true,
  691. isVerified: false
  692. })
  693. // Assign to group(s)
  694. if (get(localStrg, 'autoEnrollGroups.v', []).length > 0) {
  695. await newUsr.$relatedQuery('groups').relate(localStrg.autoEnrollGroups.v)
  696. }
  697. if (verify) {
  698. // Create verification token
  699. const verificationToken = await WIKI.db.userKeys.generateToken({
  700. kind: 'verify',
  701. userId: newUsr.id
  702. })
  703. // Send verification email
  704. await WIKI.mail.send({
  705. template: 'accountVerify',
  706. to: email,
  707. subject: 'Verify your account',
  708. data: {
  709. preheadertext: 'Verify your account in order to gain access to the wiki.',
  710. title: 'Verify your account',
  711. content: 'Click the button below in order to verify your account and gain access to the wiki.',
  712. buttonLink: `${WIKI.config.host}/verify/${verificationToken}`,
  713. buttonText: 'Verify'
  714. },
  715. 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}`
  716. })
  717. }
  718. return true
  719. } else {
  720. throw new WIKI.Error.AuthAccountAlreadyExists()
  721. }
  722. } else {
  723. throw new WIKI.Error.AuthRegistrationDisabled()
  724. }
  725. }
  726. /**
  727. * Logout the current user
  728. */
  729. static async logout (context) {
  730. if (!context.req.user || context.req.user.id === WIKI.config.auth.guestUserId) {
  731. return '/'
  732. }
  733. if (context.req.user.strategyId && has(WIKI.auth.strategies, context.req.user.strategyId)) {
  734. const selStrategy = WIKI.auth.strategies[context.req.user.strategyId]
  735. if (!selStrategy.isEnabled) {
  736. throw new WIKI.Error.AuthProviderInvalid()
  737. }
  738. const provider = find(WIKI.data.authentication, ['key', selStrategy.module])
  739. if (provider.logout) {
  740. return provider.logout(provider.config)
  741. }
  742. }
  743. return '/'
  744. }
  745. static async getGuestUser () {
  746. const user = await WIKI.db.users.query().findById(WIKI.config.auth.guestUserId).withGraphJoined('groups').modifyGraph('groups', builder => {
  747. builder.select('groups.id', 'permissions')
  748. })
  749. if (!user) {
  750. WIKI.logger.error('CRITICAL ERROR: Guest user is missing!')
  751. process.exit(1)
  752. }
  753. user.permissions = user.getPermissions()
  754. return user
  755. }
  756. static async getRootUser () {
  757. let user = await WIKI.db.users.query().findById(WIKI.config.auth.rootAdminUserId)
  758. if (!user) {
  759. WIKI.logger.error('CRITICAL ERROR: Root Administrator user is missing!')
  760. process.exit(1)
  761. }
  762. user.permissions = ['manage:system']
  763. return user
  764. }
  765. /**
  766. * Add / Update User Avatar Data
  767. */
  768. static async updateUserAvatarData (userId, data) {
  769. try {
  770. WIKI.logger.debug(`Updating user ${userId} avatar data...`)
  771. if (data.length > 1024 * 1024) {
  772. throw new Error('Avatar image filesize is too large. 1MB max.')
  773. }
  774. const existing = await WIKI.db.knex('userAvatars').select('id').where('id', userId).first()
  775. if (existing) {
  776. await WIKI.db.knex('userAvatars').where({
  777. id: userId
  778. }).update({
  779. data
  780. })
  781. } else {
  782. await WIKI.db.knex('userAvatars').insert({
  783. id: userId,
  784. data
  785. })
  786. }
  787. } catch (err) {
  788. WIKI.logger.warn(`Failed to process binary thumbnail data for user ${userId}: ${err.message}`)
  789. }
  790. }
  791. static async getUserAvatarData (userId) {
  792. try {
  793. const usrData = await WIKI.db.knex('userAvatars').where('id', userId).first()
  794. if (usrData) {
  795. return usrData.data
  796. } else {
  797. return null
  798. }
  799. } catch (err) {
  800. WIKI.logger.warn(`Failed to process binary thumbnail data for user ${userId}`)
  801. }
  802. }
  803. }