users.js 27 KB

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