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.

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