You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

764 lines
22 KiB

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