2
0

users.mjs 27 KB

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