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.

754 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. } else if (_.isNil(user.groups)) {
  299. user.groups = await user.$relatedQuery('groups').select('groups.id', 'permissions')
  300. }
  301. // Update Last Login Date
  302. // -> Bypass Objection.js to avoid updating the updatedAt field
  303. await WIKI.models.knex('users').where('id', user.id).update({ lastLoginAt: new Date().toISOString() })
  304. return {
  305. token: jwt.sign({
  306. id: user.id,
  307. email: user.email,
  308. name: user.name,
  309. av: user.pictureUrl,
  310. tz: user.timezone,
  311. lc: user.localeCode,
  312. df: user.dateFormat,
  313. ap: user.appearance,
  314. // defaultEditor: user.defaultEditor,
  315. permissions: user.getGlobalPermissions(),
  316. groups: user.getGroups()
  317. }, {
  318. key: WIKI.config.certs.private,
  319. passphrase: WIKI.config.sessionSecret
  320. }, {
  321. algorithm: 'RS256',
  322. expiresIn: WIKI.config.auth.tokenExpiration,
  323. audience: WIKI.config.auth.audience,
  324. issuer: 'urn:wiki.js'
  325. }),
  326. user
  327. }
  328. }
  329. static async loginTFA (opts, context) {
  330. if (opts.securityCode.length === 6 && opts.loginToken.length === 64) {
  331. let result = await WIKI.redis.get(`tfa:${opts.loginToken}`)
  332. if (result) {
  333. let userId = _.toSafeInteger(result)
  334. if (userId && userId > 0) {
  335. let user = await WIKI.models.users.query().findById(userId)
  336. if (user && user.verifyTFA(opts.securityCode)) {
  337. return Promise.fromCallback(clb => {
  338. context.req.logIn(user, clb)
  339. }).return({
  340. succeeded: true,
  341. message: 'Login Successful'
  342. }).catch(err => {
  343. WIKI.logger.warn(err)
  344. throw new WIKI.Error.AuthGenericError()
  345. })
  346. } else {
  347. throw new WIKI.Error.AuthTFAFailed()
  348. }
  349. }
  350. }
  351. }
  352. throw new WIKI.Error.AuthTFAInvalid()
  353. }
  354. /**
  355. * Change Password from a Mandatory Password Change after Login
  356. */
  357. static async loginChangePassword ({ continuationToken, newPassword }, context) {
  358. if (!newPassword || newPassword.length < 6) {
  359. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  360. }
  361. const usr = await WIKI.models.userKeys.validateToken({
  362. kind: 'changePwd',
  363. token: continuationToken
  364. })
  365. if (usr) {
  366. await WIKI.models.users.query().patch({
  367. password: newPassword,
  368. mustChangePwd: false
  369. }).findById(usr.id)
  370. return new Promise((resolve, reject) => {
  371. context.req.logIn(usr, { session: false }, async err => {
  372. if (err) { return reject(err) }
  373. const jwtToken = await WIKI.models.users.refreshToken(usr)
  374. resolve({ jwt: jwtToken.token })
  375. })
  376. })
  377. } else {
  378. throw new WIKI.Error.UserNotFound()
  379. }
  380. }
  381. /**
  382. * Create a new user
  383. *
  384. * @param {Object} param0 User Fields
  385. */
  386. static async createNewUser ({ providerKey, email, passwordRaw, name, groups, mustChangePassword, sendWelcomeEmail }) {
  387. // Input sanitization
  388. email = _.toLower(email)
  389. // Input validation
  390. let validation = null
  391. if (providerKey === 'local') {
  392. validation = validate({
  393. email,
  394. passwordRaw,
  395. name
  396. }, {
  397. email: {
  398. email: true,
  399. length: {
  400. maximum: 255
  401. }
  402. },
  403. passwordRaw: {
  404. presence: {
  405. allowEmpty: false
  406. },
  407. length: {
  408. minimum: 6
  409. }
  410. },
  411. name: {
  412. presence: {
  413. allowEmpty: false
  414. },
  415. length: {
  416. minimum: 2,
  417. maximum: 255
  418. }
  419. }
  420. }, { format: 'flat' })
  421. } else {
  422. validation = validate({
  423. email,
  424. name
  425. }, {
  426. email: {
  427. email: true,
  428. length: {
  429. maximum: 255
  430. }
  431. },
  432. name: {
  433. presence: {
  434. allowEmpty: false
  435. },
  436. length: {
  437. minimum: 2,
  438. maximum: 255
  439. }
  440. }
  441. }, { format: 'flat' })
  442. }
  443. if (validation && validation.length > 0) {
  444. throw new WIKI.Error.InputInvalid(validation[0])
  445. }
  446. // Check if email already exists
  447. const usr = await WIKI.models.users.query().findOne({ email, providerKey })
  448. if (!usr) {
  449. // Create the account
  450. let newUsrData = {
  451. providerKey,
  452. email,
  453. name,
  454. locale: 'en',
  455. defaultEditor: 'markdown',
  456. tfaIsActive: false,
  457. isSystem: false,
  458. isActive: true,
  459. isVerified: true,
  460. mustChangePwd: false
  461. }
  462. if (providerKey === `local`) {
  463. newUsrData.password = passwordRaw
  464. newUsrData.mustChangePwd = (mustChangePassword === true)
  465. }
  466. const newUsr = await WIKI.models.users.query().insert(newUsrData)
  467. // Assign to group(s)
  468. if (groups.length > 0) {
  469. await newUsr.$relatedQuery('groups').relate(groups)
  470. }
  471. if (sendWelcomeEmail) {
  472. // Send welcome email
  473. await WIKI.mail.send({
  474. template: 'accountWelcome',
  475. to: email,
  476. subject: `Welcome to the wiki ${WIKI.config.title}`,
  477. data: {
  478. preheadertext: `You've been invited to the wiki ${WIKI.config.title}`,
  479. title: `You've been invited to the wiki ${WIKI.config.title}`,
  480. content: `Click the button below to access the wiki.`,
  481. buttonLink: `${WIKI.config.host}/login`,
  482. buttonText: 'Login'
  483. },
  484. text: `You've been invited to the wiki ${WIKI.config.title}: ${WIKI.config.host}/login`
  485. })
  486. }
  487. } else {
  488. throw new WIKI.Error.AuthAccountAlreadyExists()
  489. }
  490. }
  491. /**
  492. * Update an existing user
  493. *
  494. * @param {Object} param0 User ID and fields to update
  495. */
  496. static async updateUser ({ id, email, name, newPassword, groups, location, jobTitle, timezone, dateFormat, appearance }) {
  497. const usr = await WIKI.models.users.query().findById(id)
  498. if (usr) {
  499. let usrData = {}
  500. if (!_.isEmpty(email) && email !== usr.email) {
  501. const dupUsr = await WIKI.models.users.query().select('id').where({
  502. email,
  503. providerKey: usr.providerKey
  504. }).first()
  505. if (dupUsr) {
  506. throw new WIKI.Error.AuthAccountAlreadyExists()
  507. }
  508. usrData.email = email
  509. }
  510. if (!_.isEmpty(name) && name !== usr.name) {
  511. usrData.name = _.trim(name)
  512. }
  513. if (!_.isEmpty(newPassword)) {
  514. if (newPassword.length < 6) {
  515. throw new WIKI.Error.InputInvalid('Password must be at least 6 characters!')
  516. }
  517. usrData.password = newPassword
  518. }
  519. if (_.isArray(groups)) {
  520. const usrGroupsRaw = await usr.$relatedQuery('groups')
  521. const usrGroups = _.map(usrGroupsRaw, 'id')
  522. // Relate added groups
  523. const addUsrGroups = _.difference(groups, usrGroups)
  524. for (const grp of addUsrGroups) {
  525. await usr.$relatedQuery('groups').relate(grp)
  526. }
  527. // Unrelate removed groups
  528. const remUsrGroups = _.difference(usrGroups, groups)
  529. for (const grp of remUsrGroups) {
  530. await usr.$relatedQuery('groups').unrelate().where('groupId', grp)
  531. }
  532. }
  533. if (!_.isEmpty(location) && location !== usr.location) {
  534. usrData.location = _.trim(location)
  535. }
  536. if (!_.isEmpty(jobTitle) && jobTitle !== usr.jobTitle) {
  537. usrData.jobTitle = _.trim(jobTitle)
  538. }
  539. if (!_.isEmpty(timezone) && timezone !== usr.timezone) {
  540. usrData.timezone = timezone
  541. }
  542. if (!_.isNil(dateFormat) && dateFormat !== usr.dateFormat) {
  543. usrData.dateFormat = dateFormat
  544. }
  545. if (!_.isNil(appearance) && appearance !== usr.appearance) {
  546. usrData.appearance = appearance
  547. }
  548. await WIKI.models.users.query().patch(usrData).findById(id)
  549. } else {
  550. throw new WIKI.Error.UserNotFound()
  551. }
  552. }
  553. /**
  554. * Delete a User
  555. *
  556. * @param {*} id User ID
  557. */
  558. static async deleteUser (id) {
  559. const usr = await WIKI.models.users.query().findById(id)
  560. if (usr) {
  561. await WIKI.models.userKeys.query().delete().where('userId', id)
  562. await WIKI.models.users.query().deleteById(id)
  563. } else {
  564. throw new WIKI.Error.UserNotFound()
  565. }
  566. }
  567. /**
  568. * Register a new user (client-side registration)
  569. *
  570. * @param {Object} param0 User fields
  571. * @param {Object} context GraphQL Context
  572. */
  573. static async register ({ email, password, name, verify = false, bypassChecks = false }, context) {
  574. const localStrg = await WIKI.models.authentication.getStrategy('local')
  575. // Check if self-registration is enabled
  576. if (localStrg.selfRegistration || bypassChecks) {
  577. // Input sanitization
  578. email = _.toLower(email)
  579. // Input validation
  580. const validation = validate({
  581. email,
  582. password,
  583. name
  584. }, {
  585. email: {
  586. email: true,
  587. length: {
  588. maximum: 255
  589. }
  590. },
  591. password: {
  592. presence: {
  593. allowEmpty: false
  594. },
  595. length: {
  596. minimum: 6
  597. }
  598. },
  599. name: {
  600. presence: {
  601. allowEmpty: false
  602. },
  603. length: {
  604. minimum: 2,
  605. maximum: 255
  606. }
  607. }
  608. }, { format: 'flat' })
  609. if (validation && validation.length > 0) {
  610. throw new WIKI.Error.InputInvalid(validation[0])
  611. }
  612. // Check if email domain is whitelisted
  613. if (_.get(localStrg, 'domainWhitelist.v', []).length > 0 && !bypassChecks) {
  614. const emailDomain = _.last(email.split('@'))
  615. if (!_.includes(localStrg.domainWhitelist.v, emailDomain)) {
  616. throw new WIKI.Error.AuthRegistrationDomainUnauthorized()
  617. }
  618. }
  619. // Check if email already exists
  620. const usr = await WIKI.models.users.query().findOne({ email, providerKey: 'local' })
  621. if (!usr) {
  622. // Create the account
  623. const newUsr = await WIKI.models.users.query().insert({
  624. provider: 'local',
  625. email,
  626. name,
  627. password,
  628. locale: 'en',
  629. defaultEditor: 'markdown',
  630. tfaIsActive: false,
  631. isSystem: false,
  632. isActive: true,
  633. isVerified: false
  634. })
  635. // Assign to group(s)
  636. if (_.get(localStrg, 'autoEnrollGroups.v', []).length > 0) {
  637. await newUsr.$relatedQuery('groups').relate(localStrg.autoEnrollGroups.v)
  638. }
  639. if (verify) {
  640. // Create verification token
  641. const verificationToken = await WIKI.models.userKeys.generateToken({
  642. kind: 'verify',
  643. userId: newUsr.id
  644. })
  645. // Send verification email
  646. await WIKI.mail.send({
  647. template: 'accountVerify',
  648. to: email,
  649. subject: 'Verify your account',
  650. data: {
  651. preheadertext: 'Verify your account in order to gain access to the wiki.',
  652. title: 'Verify your account',
  653. content: 'Click the button below in order to verify your account and gain access to the wiki.',
  654. buttonLink: `${WIKI.config.host}/verify/${verificationToken}`,
  655. buttonText: 'Verify'
  656. },
  657. 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}`
  658. })
  659. }
  660. return true
  661. } else {
  662. throw new WIKI.Error.AuthAccountAlreadyExists()
  663. }
  664. } else {
  665. throw new WIKI.Error.AuthRegistrationDisabled()
  666. }
  667. }
  668. static async getGuestUser () {
  669. const user = await WIKI.models.users.query().findById(2).withGraphJoined('groups').modifyGraph('groups', builder => {
  670. builder.select('groups.id', 'permissions')
  671. })
  672. if (!user) {
  673. WIKI.logger.error('CRITICAL ERROR: Guest user is missing!')
  674. process.exit(1)
  675. }
  676. user.permissions = user.getGlobalPermissions()
  677. return user
  678. }
  679. static async getRootUser () {
  680. let user = await WIKI.models.users.query().findById(1)
  681. if (!user) {
  682. WIKI.logger.error('CRITICAL ERROR: Root Administrator user is missing!')
  683. process.exit(1)
  684. }
  685. user.permissions = ['manage:system']
  686. return user
  687. }
  688. }