2
0

users.js 24 KB

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