users.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  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.key, {
  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. // Is 2FA required?
  307. if (!skipTFA) {
  308. if (user.tfaIsActive && user.tfaSecret) {
  309. try {
  310. const tfaToken = await WIKI.models.userKeys.generateToken({
  311. kind: 'tfa',
  312. userId: user.id
  313. })
  314. return {
  315. mustProvideTFA: true,
  316. continuationToken: tfaToken,
  317. redirect
  318. }
  319. } catch (errc) {
  320. WIKI.logger.warn(errc)
  321. throw new WIKI.Error.AuthGenericError()
  322. }
  323. } else if (WIKI.config.auth.enforce2FA || (user.tfaIsActive && !user.tfaSecret)) {
  324. try {
  325. const tfaQRImage = await user.generateTFA()
  326. const tfaToken = await WIKI.models.userKeys.generateToken({
  327. kind: 'tfaSetup',
  328. userId: user.id
  329. })
  330. return {
  331. mustSetupTFA: true,
  332. continuationToken: tfaToken,
  333. tfaQRImage,
  334. redirect
  335. }
  336. } catch (errc) {
  337. WIKI.logger.warn(errc)
  338. throw new WIKI.Error.AuthGenericError()
  339. }
  340. }
  341. }
  342. // Must Change Password?
  343. if (!skipChangePwd && user.mustChangePwd) {
  344. try {
  345. const pwdChangeToken = await WIKI.models.userKeys.generateToken({
  346. kind: 'changePwd',
  347. userId: user.id
  348. })
  349. return {
  350. mustChangePwd: true,
  351. continuationToken: pwdChangeToken,
  352. redirect
  353. }
  354. } catch (errc) {
  355. WIKI.logger.warn(errc)
  356. throw new WIKI.Error.AuthGenericError()
  357. }
  358. }
  359. return new Promise((resolve, reject) => {
  360. context.req.login(user, { session: false }, async errc => {
  361. if (errc) { return reject(errc) }
  362. const jwtToken = await WIKI.models.users.refreshToken(user)
  363. resolve({ jwt: jwtToken.token, redirect })
  364. })
  365. })
  366. }
  367. /**
  368. * Generate a new token for a user
  369. */
  370. static async refreshToken(user) {
  371. if (_.isSafeInteger(user)) {
  372. user = await WIKI.models.users.query().findById(user).withGraphFetched('groups').modifyGraph('groups', builder => {
  373. builder.select('groups.id', 'permissions')
  374. })
  375. if (!user) {
  376. WIKI.logger.warn(`Failed to refresh token for user ${user}: Not found.`)
  377. throw new WIKI.Error.AuthGenericError()
  378. }
  379. if (!user.isActive) {
  380. WIKI.logger.warn(`Failed to refresh token for user ${user}: Inactive.`)
  381. throw new WIKI.Error.AuthAccountBanned()
  382. }
  383. } else if (_.isNil(user.groups)) {
  384. user.groups = await user.$relatedQuery('groups').select('groups.id', 'permissions')
  385. }
  386. // Update Last Login Date
  387. // -> Bypass Objection.js to avoid updating the updatedAt field
  388. await WIKI.models.knex('users').where('id', user.id).update({ lastLoginAt: new Date().toISOString() })
  389. return {
  390. token: jwt.sign({
  391. id: user.id,
  392. email: user.email,
  393. name: user.name,
  394. av: user.pictureUrl,
  395. tz: user.timezone,
  396. lc: user.localeCode,
  397. df: user.dateFormat,
  398. ap: user.appearance,
  399. // defaultEditor: user.defaultEditor,
  400. permissions: user.getGlobalPermissions(),
  401. groups: user.getGroups()
  402. }, {
  403. key: WIKI.config.certs.private,
  404. passphrase: WIKI.config.sessionSecret
  405. }, {
  406. algorithm: 'RS256',
  407. expiresIn: WIKI.config.auth.tokenExpiration,
  408. audience: WIKI.config.auth.audience,
  409. issuer: 'urn:wiki.js'
  410. }),
  411. user
  412. }
  413. }
  414. /**
  415. * Verify a TFA login
  416. */
  417. static async loginTFA ({ securityCode, continuationToken, setup }, context) {
  418. if (securityCode.length === 6 && continuationToken.length > 1) {
  419. const user = await WIKI.models.userKeys.validateToken({
  420. kind: setup ? 'tfaSetup' : 'tfa',
  421. token: continuationToken,
  422. skipDelete: setup
  423. })
  424. if (user) {
  425. if (user.verifyTFA(securityCode)) {
  426. if (setup) {
  427. await user.enableTFA()
  428. }
  429. return WIKI.models.users.afterLoginChecks(user, context, { skipTFA: true })
  430. } else {
  431. throw new WIKI.Error.AuthTFAFailed()
  432. }
  433. }
  434. }
  435. throw new WIKI.Error.AuthTFAInvalid()
  436. }
  437. /**
  438. * Change Password from a Mandatory Password Change after Login
  439. */
  440. static async loginChangePassword ({ continuationToken, newPassword }, context) {
  441. if (!newPassword || newPassword.length < 6) {
  442. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  443. }
  444. const usr = await WIKI.models.userKeys.validateToken({
  445. kind: 'changePwd',
  446. token: continuationToken
  447. })
  448. if (usr) {
  449. if (!usr.isActive) {
  450. throw new WIKI.Error.AuthAccountBanned()
  451. }
  452. await WIKI.models.users.query().patch({
  453. password: newPassword,
  454. mustChangePwd: false
  455. }).findById(usr.id)
  456. return new Promise((resolve, reject) => {
  457. context.req.logIn(usr, { session: false }, async err => {
  458. if (err) { return reject(err) }
  459. const jwtToken = await WIKI.models.users.refreshToken(usr)
  460. resolve({ jwt: jwtToken.token })
  461. })
  462. })
  463. } else {
  464. throw new WIKI.Error.UserNotFound()
  465. }
  466. }
  467. /**
  468. * Send a password reset request
  469. */
  470. static async loginForgotPassword ({ email }, context) {
  471. const usr = await WIKI.models.users.query().where({
  472. email,
  473. providerKey: 'local'
  474. }).first()
  475. if (!usr) {
  476. WIKI.logger.debug(`Password reset attempt on nonexistant local account ${email}: [DISCARDED]`)
  477. return
  478. } else if (!usr.isActive) {
  479. WIKI.logger.debug(`Password reset attempt on disabled local account ${email}: [DISCARDED]`)
  480. return
  481. }
  482. const resetToken = await WIKI.models.userKeys.generateToken({
  483. userId: usr.id,
  484. kind: 'resetPwd'
  485. })
  486. await WIKI.mail.send({
  487. template: 'accountResetPwd',
  488. to: email,
  489. subject: `Password Reset Request`,
  490. data: {
  491. preheadertext: `A password reset was requested for ${WIKI.config.title}`,
  492. title: `A password reset was requested for ${WIKI.config.title}`,
  493. content: `Click the button below to reset your password. If you didn't request this password reset, simply discard this email.`,
  494. buttonLink: `${WIKI.config.host}/login-reset/${resetToken}`,
  495. buttonText: 'Reset Password'
  496. },
  497. text: `A password reset was requested for wiki ${WIKI.config.title}. Open the following link to proceed: ${WIKI.config.host}/login-reset/${resetToken}`
  498. })
  499. }
  500. /**
  501. * Create a new user
  502. *
  503. * @param {Object} param0 User Fields
  504. */
  505. static async createNewUser ({ providerKey, email, passwordRaw, name, groups, mustChangePassword, sendWelcomeEmail }) {
  506. // Input sanitization
  507. email = _.toLower(email)
  508. // Input validation
  509. let validation = null
  510. if (providerKey === 'local') {
  511. validation = validate({
  512. email,
  513. passwordRaw,
  514. name
  515. }, {
  516. email: {
  517. email: true,
  518. length: {
  519. maximum: 255
  520. }
  521. },
  522. passwordRaw: {
  523. presence: {
  524. allowEmpty: false
  525. },
  526. length: {
  527. minimum: 6
  528. }
  529. },
  530. name: {
  531. presence: {
  532. allowEmpty: false
  533. },
  534. length: {
  535. minimum: 2,
  536. maximum: 255
  537. }
  538. }
  539. }, { format: 'flat' })
  540. } else {
  541. validation = validate({
  542. email,
  543. name
  544. }, {
  545. email: {
  546. email: true,
  547. length: {
  548. maximum: 255
  549. }
  550. },
  551. name: {
  552. presence: {
  553. allowEmpty: false
  554. },
  555. length: {
  556. minimum: 2,
  557. maximum: 255
  558. }
  559. }
  560. }, { format: 'flat' })
  561. }
  562. if (validation && validation.length > 0) {
  563. throw new WIKI.Error.InputInvalid(validation[0])
  564. }
  565. // Check if email already exists
  566. const usr = await WIKI.models.users.query().findOne({ email, providerKey })
  567. if (!usr) {
  568. // Create the account
  569. let newUsrData = {
  570. providerKey,
  571. email,
  572. name,
  573. locale: 'en',
  574. defaultEditor: 'markdown',
  575. tfaIsActive: false,
  576. isSystem: false,
  577. isActive: true,
  578. isVerified: true,
  579. mustChangePwd: false
  580. }
  581. if (providerKey === `local`) {
  582. newUsrData.password = passwordRaw
  583. newUsrData.mustChangePwd = (mustChangePassword === true)
  584. }
  585. const newUsr = await WIKI.models.users.query().insert(newUsrData)
  586. // Assign to group(s)
  587. if (groups.length > 0) {
  588. await newUsr.$relatedQuery('groups').relate(groups)
  589. }
  590. if (sendWelcomeEmail) {
  591. // Send welcome email
  592. await WIKI.mail.send({
  593. template: 'accountWelcome',
  594. to: email,
  595. subject: `Welcome to the wiki ${WIKI.config.title}`,
  596. data: {
  597. preheadertext: `You've been invited to the wiki ${WIKI.config.title}`,
  598. title: `You've been invited to the wiki ${WIKI.config.title}`,
  599. content: `Click the button below to access the wiki.`,
  600. buttonLink: `${WIKI.config.host}/login`,
  601. buttonText: 'Login'
  602. },
  603. text: `You've been invited to the wiki ${WIKI.config.title}: ${WIKI.config.host}/login`
  604. })
  605. }
  606. } else {
  607. throw new WIKI.Error.AuthAccountAlreadyExists()
  608. }
  609. }
  610. /**
  611. * Update an existing user
  612. *
  613. * @param {Object} param0 User ID and fields to update
  614. */
  615. static async updateUser ({ id, email, name, newPassword, groups, location, jobTitle, timezone, dateFormat, appearance }) {
  616. const usr = await WIKI.models.users.query().findById(id)
  617. if (usr) {
  618. let usrData = {}
  619. if (!_.isEmpty(email) && email !== usr.email) {
  620. const dupUsr = await WIKI.models.users.query().select('id').where({
  621. email,
  622. providerKey: usr.providerKey
  623. }).first()
  624. if (dupUsr) {
  625. throw new WIKI.Error.AuthAccountAlreadyExists()
  626. }
  627. usrData.email = _.toLower(email)
  628. }
  629. if (!_.isEmpty(name) && name !== usr.name) {
  630. usrData.name = _.trim(name)
  631. }
  632. if (!_.isEmpty(newPassword)) {
  633. if (newPassword.length < 6) {
  634. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  635. }
  636. usrData.password = newPassword
  637. }
  638. if (_.isArray(groups)) {
  639. const usrGroupsRaw = await usr.$relatedQuery('groups')
  640. const usrGroups = _.map(usrGroupsRaw, 'id')
  641. // Relate added groups
  642. const addUsrGroups = _.difference(groups, usrGroups)
  643. for (const grp of addUsrGroups) {
  644. await usr.$relatedQuery('groups').relate(grp)
  645. }
  646. // Unrelate removed groups
  647. const remUsrGroups = _.difference(usrGroups, groups)
  648. for (const grp of remUsrGroups) {
  649. await usr.$relatedQuery('groups').unrelate().where('groupId', grp)
  650. }
  651. }
  652. if (!_.isEmpty(location) && location !== usr.location) {
  653. usrData.location = _.trim(location)
  654. }
  655. if (!_.isEmpty(jobTitle) && jobTitle !== usr.jobTitle) {
  656. usrData.jobTitle = _.trim(jobTitle)
  657. }
  658. if (!_.isEmpty(timezone) && timezone !== usr.timezone) {
  659. usrData.timezone = timezone
  660. }
  661. if (!_.isNil(dateFormat) && dateFormat !== usr.dateFormat) {
  662. usrData.dateFormat = dateFormat
  663. }
  664. if (!_.isNil(appearance) && appearance !== usr.appearance) {
  665. usrData.appearance = appearance
  666. }
  667. await WIKI.models.users.query().patch(usrData).findById(id)
  668. } else {
  669. throw new WIKI.Error.UserNotFound()
  670. }
  671. }
  672. /**
  673. * Delete a User
  674. *
  675. * @param {*} id User ID
  676. */
  677. static async deleteUser (id, replaceId) {
  678. const usr = await WIKI.models.users.query().findById(id)
  679. if (usr) {
  680. await WIKI.models.assets.query().patch({ authorId: replaceId }).where('authorId', id)
  681. await WIKI.models.comments.query().patch({ authorId: replaceId }).where('authorId', id)
  682. await WIKI.models.pageHistory.query().patch({ authorId: replaceId }).where('authorId', id)
  683. await WIKI.models.pages.query().patch({ authorId: replaceId }).where('authorId', id)
  684. await WIKI.models.pages.query().patch({ creatorId: replaceId }).where('creatorId', id)
  685. await WIKI.models.userKeys.query().delete().where('userId', id)
  686. await WIKI.models.users.query().deleteById(id)
  687. } else {
  688. throw new WIKI.Error.UserNotFound()
  689. }
  690. }
  691. /**
  692. * Register a new user (client-side registration)
  693. *
  694. * @param {Object} param0 User fields
  695. * @param {Object} context GraphQL Context
  696. */
  697. static async register ({ email, password, name, verify = false, bypassChecks = false }, context) {
  698. const localStrg = await WIKI.models.authentication.getStrategy('local')
  699. // Check if self-registration is enabled
  700. if (localStrg.selfRegistration || bypassChecks) {
  701. // Input sanitization
  702. email = _.toLower(email)
  703. // Input validation
  704. const validation = validate({
  705. email,
  706. password,
  707. name
  708. }, {
  709. email: {
  710. email: true,
  711. length: {
  712. maximum: 255
  713. }
  714. },
  715. password: {
  716. presence: {
  717. allowEmpty: false
  718. },
  719. length: {
  720. minimum: 6
  721. }
  722. },
  723. name: {
  724. presence: {
  725. allowEmpty: false
  726. },
  727. length: {
  728. minimum: 2,
  729. maximum: 255
  730. }
  731. }
  732. }, { format: 'flat' })
  733. if (validation && validation.length > 0) {
  734. throw new WIKI.Error.InputInvalid(validation[0])
  735. }
  736. // Check if email domain is whitelisted
  737. if (_.get(localStrg, 'domainWhitelist.v', []).length > 0 && !bypassChecks) {
  738. const emailDomain = _.last(email.split('@'))
  739. if (!_.includes(localStrg.domainWhitelist.v, emailDomain)) {
  740. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  741. }
  742. }
  743. // Check if email already exists
  744. const usr = await WIKI.models.users.query().findOne({ email, providerKey: 'local' })
  745. if (!usr) {
  746. // Create the account
  747. const newUsr = await WIKI.models.users.query().insert({
  748. provider: 'local',
  749. email,
  750. name,
  751. password,
  752. locale: 'en',
  753. defaultEditor: 'markdown',
  754. tfaIsActive: false,
  755. isSystem: false,
  756. isActive: true,
  757. isVerified: false
  758. })
  759. // Assign to group(s)
  760. if (_.get(localStrg, 'autoEnrollGroups.v', []).length > 0) {
  761. await newUsr.$relatedQuery('groups').relate(localStrg.autoEnrollGroups.v)
  762. }
  763. if (verify) {
  764. // Create verification token
  765. const verificationToken = await WIKI.models.userKeys.generateToken({
  766. kind: 'verify',
  767. userId: newUsr.id
  768. })
  769. // Send verification email
  770. await WIKI.mail.send({
  771. template: 'accountVerify',
  772. to: email,
  773. subject: 'Verify your account',
  774. data: {
  775. preheadertext: 'Verify your account in order to gain access to the wiki.',
  776. title: 'Verify your account',
  777. content: 'Click the button below in order to verify your account and gain access to the wiki.',
  778. buttonLink: `${WIKI.config.host}/verify/${verificationToken}`,
  779. buttonText: 'Verify'
  780. },
  781. 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}`
  782. })
  783. }
  784. return true
  785. } else {
  786. throw new WIKI.Error.AuthAccountAlreadyExists()
  787. }
  788. } else {
  789. throw new WIKI.Error.AuthRegistrationDisabled()
  790. }
  791. }
  792. /**
  793. * Logout the current user
  794. */
  795. static async logout (context) {
  796. if (!context.req.user || context.req.user.id === 2) {
  797. return '/'
  798. }
  799. const usr = await WIKI.models.users.query().findById(context.req.user.id).select('providerKey')
  800. const provider = _.find(WIKI.auth.strategies, ['key', usr.providerKey])
  801. return provider.logout ? provider.logout(provider.config, context) : '/'
  802. }
  803. static async getGuestUser () {
  804. const user = await WIKI.models.users.query().findById(2).withGraphJoined('groups').modifyGraph('groups', builder => {
  805. builder.select('groups.id', 'permissions')
  806. })
  807. if (!user) {
  808. WIKI.logger.error('CRITICAL ERROR: Guest user is missing!')
  809. process.exit(1)
  810. }
  811. user.permissions = user.getGlobalPermissions()
  812. return user
  813. }
  814. static async getRootUser () {
  815. let user = await WIKI.models.users.query().findById(1)
  816. if (!user) {
  817. WIKI.logger.error('CRITICAL ERROR: Root Administrator user is missing!')
  818. process.exit(1)
  819. }
  820. user.permissions = ['manage:system']
  821. return user
  822. }
  823. /**
  824. * Add / Update User Avatar Data
  825. */
  826. static async updateUserAvatarData (userId, data) {
  827. try {
  828. WIKI.logger.debug(`Updating user ${userId} avatar data...`)
  829. if (data.length > 1024 * 1024) {
  830. throw new Error('Avatar image filesize is too large. 1MB max.')
  831. }
  832. const existing = await WIKI.models.knex('userAvatars').select('id').where('id', userId).first()
  833. if (existing) {
  834. await WIKI.models.knex('userAvatars').where({
  835. id: userId
  836. }).update({
  837. data
  838. })
  839. } else {
  840. await WIKI.models.knex('userAvatars').insert({
  841. id: userId,
  842. data
  843. })
  844. }
  845. } catch (err) {
  846. WIKI.logger.warn(`Failed to process binary thumbnail data for user ${userId}: ${err.message}`)
  847. }
  848. }
  849. static async getUserAvatarData (userId) {
  850. try {
  851. const usrData = await WIKI.models.knex('userAvatars').where('id', userId).first()
  852. if (usrData) {
  853. return usrData.data
  854. } else {
  855. return null
  856. }
  857. } catch (err) {
  858. WIKI.logger.warn(`Failed to process binary thumbnail data for user ${userId}`)
  859. }
  860. }
  861. }