users.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  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'},
  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', providerKey])
  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
  188. let pictureUrl = _.truncate(_.get(profile, 'picture', _.get(user, 'pictureUrl', null)), {
  189. length: 255,
  190. omission: ''
  191. })
  192. // Update existing user
  193. if (user) {
  194. if (!user.isActive) {
  195. throw new WIKI.Error.AuthAccountBanned()
  196. }
  197. if (user.isSystem) {
  198. throw new Error('This is a system reserved account and cannot be used.')
  199. }
  200. user = await user.$query().patchAndFetch({
  201. email: primaryEmail,
  202. name: displayName,
  203. pictureUrl: pictureUrl
  204. })
  205. return user
  206. }
  207. // Self-registration
  208. if (provider.selfRegistration) {
  209. // Check if email domain is whitelisted
  210. if (_.get(provider, 'domainWhitelist', []).length > 0) {
  211. const emailDomain = _.last(primaryEmail.split('@'))
  212. if (!_.includes(provider.domainWhitelist, emailDomain)) {
  213. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  214. }
  215. }
  216. // Create account
  217. user = await WIKI.models.users.query().insertAndFetch({
  218. providerKey: providerKey,
  219. providerId: _.toString(profile.id),
  220. email: primaryEmail,
  221. name: displayName,
  222. pictureUrl: pictureUrl,
  223. localeCode: WIKI.config.lang.code,
  224. defaultEditor: 'markdown',
  225. tfaIsActive: false,
  226. isSystem: false,
  227. isActive: true,
  228. isVerified: true
  229. })
  230. // Assign to group(s)
  231. if (provider.autoEnrollGroups.length > 0) {
  232. await user.$relatedQuery('groups').relate(provider.autoEnrollGroups)
  233. }
  234. return user
  235. }
  236. throw new Error('You are not authorized to login.')
  237. }
  238. static async login (opts, context) {
  239. if (_.has(WIKI.auth.strategies, opts.strategy)) {
  240. const strInfo = _.find(WIKI.data.authentication, ['key', opts.strategy])
  241. // Inject form user/pass
  242. if (strInfo.useForm) {
  243. _.set(context.req, 'body.email', opts.username)
  244. _.set(context.req, 'body.password', opts.password)
  245. }
  246. // Authenticate
  247. return new Promise((resolve, reject) => {
  248. WIKI.auth.passport.authenticate(opts.strategy, {
  249. session: !strInfo.useForm,
  250. scope: strInfo.scopes ? strInfo.scopes : null
  251. }, async (err, user, info) => {
  252. if (err) { return reject(err) }
  253. if (!user) { return reject(new WIKI.Error.AuthLoginFailed()) }
  254. try {
  255. const resp = await WIKI.models.users.afterLoginChecks(user, context)
  256. resolve(resp)
  257. } catch (err) {
  258. reject(err)
  259. }
  260. })(context.req, context.res, () => {})
  261. })
  262. } else {
  263. throw new WIKI.Error.AuthProviderInvalid()
  264. }
  265. }
  266. static async afterLoginChecks (user, 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. redirect = user.groups[0].redirectOnLogin
  272. }
  273. // Is 2FA required?
  274. if (!skipTFA) {
  275. if (user.tfaIsActive && user.tfaSecret) {
  276. try {
  277. const tfaToken = await WIKI.models.userKeys.generateToken({
  278. kind: 'tfa',
  279. userId: user.id
  280. })
  281. return {
  282. mustProvideTFA: true,
  283. continuationToken: tfaToken,
  284. redirect
  285. }
  286. } catch (errc) {
  287. WIKI.logger.warn(errc)
  288. throw new WIKI.Error.AuthGenericError()
  289. }
  290. } else if (WIKI.config.auth.enforce2FA || (user.tfaIsActive && !user.tfaSecret)) {
  291. try {
  292. const tfaQRImage = await user.generateTFA()
  293. const tfaToken = await WIKI.models.userKeys.generateToken({
  294. kind: 'tfaSetup',
  295. userId: user.id
  296. })
  297. return {
  298. mustSetupTFA: true,
  299. continuationToken: tfaToken,
  300. tfaQRImage,
  301. redirect
  302. }
  303. } catch (errc) {
  304. WIKI.logger.warn(errc)
  305. throw new WIKI.Error.AuthGenericError()
  306. }
  307. }
  308. }
  309. // Must Change Password?
  310. if (!skipChangePwd && user.mustChangePwd) {
  311. try {
  312. const pwdChangeToken = await WIKI.models.userKeys.generateToken({
  313. kind: 'changePwd',
  314. userId: user.id
  315. })
  316. return {
  317. mustChangePwd: true,
  318. continuationToken: pwdChangeToken,
  319. redirect
  320. }
  321. } catch (errc) {
  322. WIKI.logger.warn(errc)
  323. throw new WIKI.Error.AuthGenericError()
  324. }
  325. }
  326. return new Promise((resolve, reject) => {
  327. context.req.login(user, { session: false }, async errc => {
  328. if (errc) { return reject(errc) }
  329. const jwtToken = await WIKI.models.users.refreshToken(user)
  330. resolve({ jwt: jwtToken.token, redirect })
  331. })
  332. })
  333. }
  334. static async refreshToken(user) {
  335. if (_.isSafeInteger(user)) {
  336. user = await WIKI.models.users.query().findById(user).withGraphFetched('groups').modifyGraph('groups', builder => {
  337. builder.select('groups.id', 'permissions')
  338. })
  339. if (!user) {
  340. WIKI.logger.warn(`Failed to refresh token for user ${user}: Not found.`)
  341. throw new WIKI.Error.AuthGenericError()
  342. }
  343. if (!user.isActive) {
  344. WIKI.logger.warn(`Failed to refresh token for user ${user}: Inactive.`)
  345. throw new WIKI.Error.AuthAccountBanned()
  346. }
  347. } else if (_.isNil(user.groups)) {
  348. user.groups = await user.$relatedQuery('groups').select('groups.id', 'permissions')
  349. }
  350. // Update Last Login Date
  351. // -> Bypass Objection.js to avoid updating the updatedAt field
  352. await WIKI.models.knex('users').where('id', user.id).update({ lastLoginAt: new Date().toISOString() })
  353. return {
  354. token: jwt.sign({
  355. id: user.id,
  356. email: user.email,
  357. name: user.name,
  358. av: user.pictureUrl,
  359. tz: user.timezone,
  360. lc: user.localeCode,
  361. df: user.dateFormat,
  362. ap: user.appearance,
  363. // defaultEditor: user.defaultEditor,
  364. permissions: user.getGlobalPermissions(),
  365. groups: user.getGroups()
  366. }, {
  367. key: WIKI.config.certs.private,
  368. passphrase: WIKI.config.sessionSecret
  369. }, {
  370. algorithm: 'RS256',
  371. expiresIn: WIKI.config.auth.tokenExpiration,
  372. audience: WIKI.config.auth.audience,
  373. issuer: 'urn:wiki.js'
  374. }),
  375. user
  376. }
  377. }
  378. static async loginTFA ({ securityCode, continuationToken, setup }, context) {
  379. if (securityCode.length === 6 && continuationToken.length > 1) {
  380. const user = await WIKI.models.userKeys.validateToken({
  381. kind: setup ? 'tfaSetup' : 'tfa',
  382. token: continuationToken,
  383. skipDelete: setup
  384. })
  385. if (user) {
  386. if (user.verifyTFA(securityCode)) {
  387. if (setup) {
  388. await user.enableTFA()
  389. }
  390. return WIKI.models.users.afterLoginChecks(user, context, { skipTFA: true })
  391. } else {
  392. throw new WIKI.Error.AuthTFAFailed()
  393. }
  394. }
  395. }
  396. throw new WIKI.Error.AuthTFAInvalid()
  397. }
  398. /**
  399. * Change Password from a Mandatory Password Change after Login
  400. */
  401. static async loginChangePassword ({ continuationToken, newPassword }, context) {
  402. if (!newPassword || newPassword.length < 6) {
  403. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  404. }
  405. const usr = await WIKI.models.userKeys.validateToken({
  406. kind: 'changePwd',
  407. token: continuationToken
  408. })
  409. if (usr) {
  410. await WIKI.models.users.query().patch({
  411. password: newPassword,
  412. mustChangePwd: false
  413. }).findById(usr.id)
  414. return new Promise((resolve, reject) => {
  415. context.req.logIn(usr, { session: false }, async err => {
  416. if (err) { return reject(err) }
  417. const jwtToken = await WIKI.models.users.refreshToken(usr)
  418. resolve({ jwt: jwtToken.token })
  419. })
  420. })
  421. } else {
  422. throw new WIKI.Error.UserNotFound()
  423. }
  424. }
  425. /**
  426. * Create a new user
  427. *
  428. * @param {Object} param0 User Fields
  429. */
  430. static async createNewUser ({ providerKey, email, passwordRaw, name, groups, mustChangePassword, sendWelcomeEmail }) {
  431. // Input sanitization
  432. email = _.toLower(email)
  433. // Input validation
  434. let validation = null
  435. if (providerKey === 'local') {
  436. validation = validate({
  437. email,
  438. passwordRaw,
  439. name
  440. }, {
  441. email: {
  442. email: true,
  443. length: {
  444. maximum: 255
  445. }
  446. },
  447. passwordRaw: {
  448. presence: {
  449. allowEmpty: false
  450. },
  451. length: {
  452. minimum: 6
  453. }
  454. },
  455. name: {
  456. presence: {
  457. allowEmpty: false
  458. },
  459. length: {
  460. minimum: 2,
  461. maximum: 255
  462. }
  463. }
  464. }, { format: 'flat' })
  465. } else {
  466. validation = validate({
  467. email,
  468. name
  469. }, {
  470. email: {
  471. email: true,
  472. length: {
  473. maximum: 255
  474. }
  475. },
  476. name: {
  477. presence: {
  478. allowEmpty: false
  479. },
  480. length: {
  481. minimum: 2,
  482. maximum: 255
  483. }
  484. }
  485. }, { format: 'flat' })
  486. }
  487. if (validation && validation.length > 0) {
  488. throw new WIKI.Error.InputInvalid(validation[0])
  489. }
  490. // Check if email already exists
  491. const usr = await WIKI.models.users.query().findOne({ email, providerKey })
  492. if (!usr) {
  493. // Create the account
  494. let newUsrData = {
  495. providerKey,
  496. email,
  497. name,
  498. locale: 'en',
  499. defaultEditor: 'markdown',
  500. tfaIsActive: false,
  501. isSystem: false,
  502. isActive: true,
  503. isVerified: true,
  504. mustChangePwd: false
  505. }
  506. if (providerKey === `local`) {
  507. newUsrData.password = passwordRaw
  508. newUsrData.mustChangePwd = (mustChangePassword === true)
  509. }
  510. const newUsr = await WIKI.models.users.query().insert(newUsrData)
  511. // Assign to group(s)
  512. if (groups.length > 0) {
  513. await newUsr.$relatedQuery('groups').relate(groups)
  514. }
  515. if (sendWelcomeEmail) {
  516. // Send welcome email
  517. await WIKI.mail.send({
  518. template: 'accountWelcome',
  519. to: email,
  520. subject: `Welcome to the wiki ${WIKI.config.title}`,
  521. data: {
  522. preheadertext: `You've been invited to the wiki ${WIKI.config.title}`,
  523. title: `You've been invited to the wiki ${WIKI.config.title}`,
  524. content: `Click the button below to access the wiki.`,
  525. buttonLink: `${WIKI.config.host}/login`,
  526. buttonText: 'Login'
  527. },
  528. text: `You've been invited to the wiki ${WIKI.config.title}: ${WIKI.config.host}/login`
  529. })
  530. }
  531. } else {
  532. throw new WIKI.Error.AuthAccountAlreadyExists()
  533. }
  534. }
  535. /**
  536. * Update an existing user
  537. *
  538. * @param {Object} param0 User ID and fields to update
  539. */
  540. static async updateUser ({ id, email, name, newPassword, groups, location, jobTitle, timezone, dateFormat, appearance }) {
  541. const usr = await WIKI.models.users.query().findById(id)
  542. if (usr) {
  543. let usrData = {}
  544. if (!_.isEmpty(email) && email !== usr.email) {
  545. const dupUsr = await WIKI.models.users.query().select('id').where({
  546. email,
  547. providerKey: usr.providerKey
  548. }).first()
  549. if (dupUsr) {
  550. throw new WIKI.Error.AuthAccountAlreadyExists()
  551. }
  552. usrData.email = email
  553. }
  554. if (!_.isEmpty(name) && name !== usr.name) {
  555. usrData.name = _.trim(name)
  556. }
  557. if (!_.isEmpty(newPassword)) {
  558. if (newPassword.length < 6) {
  559. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  560. }
  561. usrData.password = newPassword
  562. }
  563. if (_.isArray(groups)) {
  564. const usrGroupsRaw = await usr.$relatedQuery('groups')
  565. const usrGroups = _.map(usrGroupsRaw, 'id')
  566. // Relate added groups
  567. const addUsrGroups = _.difference(groups, usrGroups)
  568. for (const grp of addUsrGroups) {
  569. await usr.$relatedQuery('groups').relate(grp)
  570. }
  571. // Unrelate removed groups
  572. const remUsrGroups = _.difference(usrGroups, groups)
  573. for (const grp of remUsrGroups) {
  574. await usr.$relatedQuery('groups').unrelate().where('groupId', grp)
  575. }
  576. }
  577. if (!_.isEmpty(location) && location !== usr.location) {
  578. usrData.location = _.trim(location)
  579. }
  580. if (!_.isEmpty(jobTitle) && jobTitle !== usr.jobTitle) {
  581. usrData.jobTitle = _.trim(jobTitle)
  582. }
  583. if (!_.isEmpty(timezone) && timezone !== usr.timezone) {
  584. usrData.timezone = timezone
  585. }
  586. if (!_.isNil(dateFormat) && dateFormat !== usr.dateFormat) {
  587. usrData.dateFormat = dateFormat
  588. }
  589. if (!_.isNil(appearance) && appearance !== usr.appearance) {
  590. usrData.appearance = appearance
  591. }
  592. await WIKI.models.users.query().patch(usrData).findById(id)
  593. } else {
  594. throw new WIKI.Error.UserNotFound()
  595. }
  596. }
  597. /**
  598. * Delete a User
  599. *
  600. * @param {*} id User ID
  601. */
  602. static async deleteUser (id, replaceId) {
  603. const usr = await WIKI.models.users.query().findById(id)
  604. if (usr) {
  605. await WIKI.models.assets.query().patch({ authorId: replaceId }).where('authorId', id)
  606. await WIKI.models.comments.query().patch({ authorId: replaceId }).where('authorId', id)
  607. await WIKI.models.pageHistory.query().patch({ authorId: replaceId }).where('authorId', id)
  608. await WIKI.models.pages.query().patch({ authorId: replaceId }).where('authorId', id)
  609. await WIKI.models.pages.query().patch({ creatorId: replaceId }).where('creatorId', id)
  610. await WIKI.models.userKeys.query().delete().where('userId', id)
  611. await WIKI.models.users.query().deleteById(id)
  612. } else {
  613. throw new WIKI.Error.UserNotFound()
  614. }
  615. }
  616. /**
  617. * Register a new user (client-side registration)
  618. *
  619. * @param {Object} param0 User fields
  620. * @param {Object} context GraphQL Context
  621. */
  622. static async register ({ email, password, name, verify = false, bypassChecks = false }, context) {
  623. const localStrg = await WIKI.models.authentication.getStrategy('local')
  624. // Check if self-registration is enabled
  625. if (localStrg.selfRegistration || bypassChecks) {
  626. // Input sanitization
  627. email = _.toLower(email)
  628. // Input validation
  629. const validation = validate({
  630. email,
  631. password,
  632. name
  633. }, {
  634. email: {
  635. email: true,
  636. length: {
  637. maximum: 255
  638. }
  639. },
  640. password: {
  641. presence: {
  642. allowEmpty: false
  643. },
  644. length: {
  645. minimum: 6
  646. }
  647. },
  648. name: {
  649. presence: {
  650. allowEmpty: false
  651. },
  652. length: {
  653. minimum: 2,
  654. maximum: 255
  655. }
  656. }
  657. }, { format: 'flat' })
  658. if (validation && validation.length > 0) {
  659. throw new WIKI.Error.InputInvalid(validation[0])
  660. }
  661. // Check if email domain is whitelisted
  662. if (_.get(localStrg, 'domainWhitelist.v', []).length > 0 && !bypassChecks) {
  663. const emailDomain = _.last(email.split('@'))
  664. if (!_.includes(localStrg.domainWhitelist.v, emailDomain)) {
  665. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  666. }
  667. }
  668. // Check if email already exists
  669. const usr = await WIKI.models.users.query().findOne({ email, providerKey: 'local' })
  670. if (!usr) {
  671. // Create the account
  672. const newUsr = await WIKI.models.users.query().insert({
  673. provider: 'local',
  674. email,
  675. name,
  676. password,
  677. locale: 'en',
  678. defaultEditor: 'markdown',
  679. tfaIsActive: false,
  680. isSystem: false,
  681. isActive: true,
  682. isVerified: false
  683. })
  684. // Assign to group(s)
  685. if (_.get(localStrg, 'autoEnrollGroups.v', []).length > 0) {
  686. await newUsr.$relatedQuery('groups').relate(localStrg.autoEnrollGroups.v)
  687. }
  688. if (verify) {
  689. // Create verification token
  690. const verificationToken = await WIKI.models.userKeys.generateToken({
  691. kind: 'verify',
  692. userId: newUsr.id
  693. })
  694. // Send verification email
  695. await WIKI.mail.send({
  696. template: 'accountVerify',
  697. to: email,
  698. subject: 'Verify your account',
  699. data: {
  700. preheadertext: 'Verify your account in order to gain access to the wiki.',
  701. title: 'Verify your account',
  702. content: 'Click the button below in order to verify your account and gain access to the wiki.',
  703. buttonLink: `${WIKI.config.host}/verify/${verificationToken}`,
  704. buttonText: 'Verify'
  705. },
  706. 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}`
  707. })
  708. }
  709. return true
  710. } else {
  711. throw new WIKI.Error.AuthAccountAlreadyExists()
  712. }
  713. } else {
  714. throw new WIKI.Error.AuthRegistrationDisabled()
  715. }
  716. }
  717. static async getGuestUser () {
  718. const user = await WIKI.models.users.query().findById(2).withGraphJoined('groups').modifyGraph('groups', builder => {
  719. builder.select('groups.id', 'permissions')
  720. })
  721. if (!user) {
  722. WIKI.logger.error('CRITICAL ERROR: Guest user is missing!')
  723. process.exit(1)
  724. }
  725. user.permissions = user.getGlobalPermissions()
  726. return user
  727. }
  728. static async getRootUser () {
  729. let user = await WIKI.models.users.query().findById(1)
  730. if (!user) {
  731. WIKI.logger.error('CRITICAL ERROR: Root Administrator user is missing!')
  732. process.exit(1)
  733. }
  734. user.permissions = ['manage:system']
  735. return user
  736. }
  737. }