You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

934 lines
27 KiB

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