users.js 27 KB

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