User.mjs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351
  1. import OError from '@overleaf/o-error'
  2. import request from './request.js'
  3. import settings from '@overleaf/settings'
  4. import { db, ObjectId } from '../../../../app/src/infrastructure/mongodb.js'
  5. import { User as UserModel } from '../../../../app/src/models/User.js'
  6. import UserUpdater from '../../../../app/src/Features/User/UserUpdater.js'
  7. import AuthenticationManager from '../../../../app/src/Features/Authentication/AuthenticationManager.js'
  8. import { promisifyClass } from '@overleaf/promise-utils'
  9. import fs from 'node:fs'
  10. import Path from 'node:path'
  11. import { fileURLToPath } from 'node:url'
  12. import { Cookie } from 'tough-cookie'
  13. const __dirname = fileURLToPath(new URL('.', import.meta.url))
  14. const COOKIE_DOMAIN = settings.cookieDomain
  15. // The cookie domain has a leading '.' but the cookie jar stores it without.
  16. const DEFAULT_COOKIE_URL = `https://${COOKIE_DOMAIN.replace(/^\./, '')}/`
  17. let count = settings.test.counterInit
  18. class User {
  19. constructor(options) {
  20. if (options == null) {
  21. options = {}
  22. }
  23. this.emails = [
  24. {
  25. email: options.email || `acceptance-test-${count}@example.com`,
  26. createdAt: new Date(),
  27. confirmedAt: options.confirmedAt,
  28. },
  29. ]
  30. this.email = this.emails[0].email
  31. this.password = `a-terrible-secret-${count}`
  32. count++
  33. this.jar = request.jar()
  34. this.request = request.defaults({
  35. jar: this.jar,
  36. })
  37. this.signUpDate = options.signUpDate ?? new Date()
  38. this.labsProgram = options.labsProgram || false
  39. }
  40. getSession(options, callback) {
  41. if (typeof options === 'function') {
  42. callback = options
  43. options = {}
  44. }
  45. this.request.get(
  46. {
  47. url: '/dev/session',
  48. qs: options.set,
  49. },
  50. (err, response, body) => {
  51. if (err != null) {
  52. return callback(err)
  53. }
  54. if (response.statusCode !== 200) {
  55. return callback(
  56. new Error(
  57. `get session failed: status=${
  58. response.statusCode
  59. } body=${JSON.stringify(body)}`
  60. )
  61. )
  62. }
  63. const session = JSON.parse(response.body)
  64. callback(null, session)
  65. }
  66. )
  67. }
  68. setInSession(params, callback) {
  69. this.getCsrfToken(error => {
  70. if (error != null) {
  71. return callback(error)
  72. }
  73. this.request.post(
  74. {
  75. url: '/dev/set_in_session',
  76. json: params,
  77. },
  78. (err, response, body) => {
  79. if (err != null) {
  80. return callback(err)
  81. }
  82. if (response.statusCode !== 200) {
  83. return callback(
  84. new Error(
  85. `post set in session failed: status=${
  86. response.statusCode
  87. } body=${JSON.stringify(body)}`
  88. )
  89. )
  90. }
  91. callback(null)
  92. }
  93. )
  94. })
  95. }
  96. getSplitTestAssignment(splitTestName, query, callback) {
  97. if (!callback) {
  98. callback = query
  99. }
  100. const params = new URLSearchParams({
  101. splitTestName,
  102. ...query,
  103. }).toString()
  104. this.request.get(
  105. {
  106. url: `/dev/split_test/get_assignment?${params}`,
  107. },
  108. (err, response, body) => {
  109. if (err != null) {
  110. return callback(err)
  111. }
  112. if (response.statusCode !== 200) {
  113. return callback(
  114. new Error(
  115. `get split test assignment failed: status=${
  116. response.statusCode
  117. } body=${JSON.stringify(body)}`
  118. )
  119. )
  120. }
  121. const assignment = JSON.parse(response.body)
  122. callback(null, assignment)
  123. }
  124. )
  125. }
  126. doSessionMaintenance(callback) {
  127. this.request.post(
  128. {
  129. url: `/dev/split_test/session_maintenance`,
  130. },
  131. (err, response, body) => {
  132. if (err != null) {
  133. return callback(err)
  134. }
  135. if (response.statusCode !== 200) {
  136. return callback(
  137. new Error(
  138. `post session maintenance failed: status=${
  139. response.statusCode
  140. } body=${JSON.stringify(body)}`
  141. )
  142. )
  143. }
  144. callback(null)
  145. }
  146. )
  147. }
  148. optIntoBeta(callback) {
  149. this.request.post(
  150. {
  151. url: '/beta/opt-in',
  152. },
  153. (err, response, body) => {
  154. if (err != null) {
  155. return callback(err)
  156. }
  157. if (response.statusCode !== 302) {
  158. return callback(
  159. new Error(
  160. `post beta opt-in failed: status=${
  161. response.statusCode
  162. } body=${JSON.stringify(body)}`
  163. )
  164. )
  165. }
  166. callback(null)
  167. }
  168. )
  169. }
  170. optOutOfBeta(callback) {
  171. this.request.post(
  172. {
  173. url: '/beta/opt-out',
  174. },
  175. (err, response, body) => {
  176. if (err != null) {
  177. return callback(err)
  178. }
  179. if (response.statusCode !== 302) {
  180. return callback(
  181. new Error(
  182. `post beta opt-out failed: status=${
  183. response.statusCode
  184. } body=${JSON.stringify(body)}`
  185. )
  186. )
  187. }
  188. callback(null)
  189. }
  190. )
  191. }
  192. /* Return the session cookie, url decoded. Use the option {raw:true} to get the original undecoded value */
  193. sessionCookie(options) {
  194. const cookie = Cookie.parse(this.jar.getCookieString(DEFAULT_COOKIE_URL))
  195. if (cookie?.value && !options?.raw) {
  196. cookie.value = decodeURIComponent(cookie.value)
  197. }
  198. return cookie
  199. }
  200. /* Set the session cookie from a string and store it in the cookie jar, so that it will be used
  201. for subsequent requests. */
  202. setSessionCookie(cookie) {
  203. const sessionCookie = request.cookie(
  204. `${settings.cookieName}=${cookie}; Domain=${COOKIE_DOMAIN}; Max-age=3600; Path=/; SameSite=Lax`
  205. )
  206. this.jar.setCookie(sessionCookie, DEFAULT_COOKIE_URL)
  207. }
  208. getEmailConfirmationCode(callback) {
  209. this.getSession((err, session) => {
  210. if (err != null) {
  211. return callback(err)
  212. }
  213. const code = session.pendingUserRegistration?.confirmCode
  214. if (!code) {
  215. return callback(new Error('No confirmation code found in session'))
  216. }
  217. callback(null, code)
  218. })
  219. }
  220. resetCookies() {
  221. this.jar = request.jar()
  222. this.request = request.defaults({
  223. jar: this.jar,
  224. })
  225. }
  226. setExtraAttributes(user) {
  227. if (!user?._id) {
  228. throw new Error('User does not exist')
  229. }
  230. this.id = user._id.toString()
  231. this._id = user._id.toString()
  232. this.first_name = user.first_name
  233. this.referal_id = user.referal_id
  234. this.enrollment = user.enrollment
  235. }
  236. get(callback) {
  237. db.users.findOne({ _id: new ObjectId(this._id) }, callback)
  238. }
  239. getAuditLog(callback) {
  240. this.get((error, user) => {
  241. if (error) {
  242. return callback(error)
  243. }
  244. if (!user) {
  245. return callback(new Error('User not found'))
  246. }
  247. db.userAuditLogEntries
  248. .find({ userId: new ObjectId(this._id) })
  249. .toArray((error, auditLog) => {
  250. if (error) {
  251. return callback(error)
  252. }
  253. callback(null, auditLog || [])
  254. })
  255. })
  256. }
  257. getAuditLogWithoutNoise(callback) {
  258. this.getAuditLog((error, auditLog) => {
  259. if (error) {
  260. return callback(error)
  261. }
  262. callback(
  263. null,
  264. auditLog.filter(entry => {
  265. return entry.operation !== 'login'
  266. })
  267. )
  268. })
  269. }
  270. mongoUpdate(updateOp, callback) {
  271. db.users.updateOne({ _id: new ObjectId(this._id) }, updateOp, callback)
  272. }
  273. register(callback) {
  274. this.registerWithQuery('', callback)
  275. }
  276. registerWithQuery(query, callback) {
  277. if (this._id != null) {
  278. return callback(new Error('User already registered'))
  279. }
  280. this.getCsrfToken(error => {
  281. if (error != null) {
  282. return callback(error)
  283. }
  284. this.request.post(
  285. {
  286. url: `/register${query}`,
  287. json: { email: this.email, password: this.password },
  288. },
  289. (error, response, body) => {
  290. if (error != null) {
  291. return callback(error)
  292. }
  293. if (response.statusCode !== 200) {
  294. return callback(
  295. new Error(
  296. `register failed: status=${
  297. response.statusCode
  298. } body=${JSON.stringify(body)}`
  299. )
  300. )
  301. }
  302. this.getEmailConfirmationCode((error, code) => {
  303. if (error != null) {
  304. return callback(error)
  305. }
  306. this.request.post(
  307. {
  308. url: '/registration/confirm-email',
  309. json: { code },
  310. },
  311. (error, response, body) => {
  312. if (error != null) {
  313. return callback(error)
  314. }
  315. if (response.statusCode !== 200) {
  316. return callback(
  317. new Error(
  318. `email confirmation failed: status=${
  319. response.statusCode
  320. } body=${JSON.stringify(body)}`
  321. )
  322. )
  323. }
  324. db.users.findOne({ email: this.email }, (error, user) => {
  325. if (error != null) {
  326. return callback(error)
  327. }
  328. this.setExtraAttributes(user)
  329. callback(null, user, response)
  330. })
  331. }
  332. )
  333. })
  334. }
  335. )
  336. })
  337. }
  338. login(callback) {
  339. this.loginWith(this.email, callback)
  340. }
  341. loginWith(email, callback) {
  342. this.ensureUserExists(error => {
  343. if (error != null) {
  344. return callback(error)
  345. }
  346. this.loginWithEmailPassword(email, this.password, callback)
  347. })
  348. }
  349. loginNoUpdate(callback) {
  350. this.loginWithEmailPassword(this.email, this.password, callback)
  351. }
  352. loginWithEmailPassword(email, password, callback) {
  353. this.getCsrfToken(error => {
  354. if (error != null) {
  355. return callback(error)
  356. }
  357. this.request.post(
  358. {
  359. url: settings.enableLegacyLogin ? '/login/legacy' : '/login',
  360. json: {
  361. email,
  362. password,
  363. 'g-recaptcha-response': 'valid',
  364. },
  365. },
  366. (error, response, body) => {
  367. if (error != null) {
  368. return callback(error)
  369. }
  370. if (response.statusCode !== 200) {
  371. return callback(
  372. new OError(
  373. `login failed: status=${
  374. response.statusCode
  375. } body=${JSON.stringify(body)}`,
  376. { response, body }
  377. )
  378. )
  379. }
  380. // get new csrf token, then return result of login
  381. this.getCsrfToken(err => {
  382. if (err) {
  383. return callback(OError.tag(err, 'after login'))
  384. }
  385. callback(null, response, body)
  386. })
  387. }
  388. )
  389. })
  390. }
  391. ensureUserExists(callback) {
  392. if (this._id) {
  393. return callback()
  394. } // already exists
  395. const filter = { email: this.email }
  396. const options = { upsert: true, new: true, setDefaultsOnInsert: true }
  397. AuthenticationManager.hashPassword(
  398. this.password,
  399. (error, hashedPassword) => {
  400. if (error != null) {
  401. return callback(error)
  402. }
  403. UserModel.findOneAndUpdate(
  404. filter,
  405. {
  406. $set: {
  407. hashedPassword,
  408. emails: this.emails,
  409. signUpDate: this.signUpDate,
  410. labsProgram: this.labsProgram,
  411. },
  412. },
  413. options
  414. )
  415. .then(user => {
  416. this.setExtraAttributes(user)
  417. callback(null, this.password)
  418. })
  419. .catch(callback)
  420. }
  421. )
  422. }
  423. // Update and persist feature upgrade. Downgrades will be flaky!
  424. upgradeFeatures(features, callback) {
  425. this.setFeatures(features, err => {
  426. if (err) {
  427. return callback(err)
  428. }
  429. // Persist the feature update, otherwise the next feature refresh will reset them.
  430. this.setFeaturesOverride(
  431. {
  432. createdAt: new Date(),
  433. note: 'Some note',
  434. features,
  435. },
  436. callback
  437. )
  438. })
  439. }
  440. // Low-level. Temporary feature change. A feature refresh might reset them, e.g. "some time" after logging in.
  441. setFeatures(features, callback) {
  442. const update = {}
  443. for (const key in features) {
  444. const value = features[key]
  445. update[`features.${key}`] = value
  446. }
  447. UserModel.updateOne({ _id: this.id }, update)
  448. .then((...args) => callback(null, ...args))
  449. .catch(callback)
  450. }
  451. // Low-level. Permanent feature change. Feature overrides are not applied right away. A feature refresh might populate them "some time" after login/changing subscriptions.
  452. setFeaturesOverride(featuresOverride, callback) {
  453. if (!featuresOverride?.features) {
  454. throw new Error('bad featuresOverride schema')
  455. }
  456. const update = { $push: { featuresOverrides: featuresOverride } }
  457. UserModel.updateOne({ _id: this.id }, update)
  458. .then((...args) => callback(null, ...args))
  459. .catch(callback)
  460. }
  461. setOverleafId(overleafId, callback) {
  462. UserModel.updateOne({ _id: this.id }, { 'overleaf.id': overleafId })
  463. .then((...args) => callback(null, ...args))
  464. .catch(callback)
  465. }
  466. setEmails(emails, callback) {
  467. UserModel.updateOne({ _id: this.id }, { emails })
  468. .then((...args) => callback(null, ...args))
  469. .catch(callback)
  470. }
  471. setSuspended(suspended, callback) {
  472. UserModel.updateOne({ _id: this.id }, { suspended })
  473. .then((...args) => callback(null, ...args))
  474. .catch(callback)
  475. }
  476. logout(callback) {
  477. this.getCsrfToken(error => {
  478. if (error != null) {
  479. return callback(error)
  480. }
  481. this.request.post(
  482. {
  483. url: '/logout',
  484. },
  485. (error, response, body) => {
  486. if (error != null) {
  487. return callback(error)
  488. }
  489. if (response.statusCode >= 400) {
  490. return callback(
  491. new Error(
  492. `logout failed: status=${
  493. response.statusCode
  494. } body=${JSON.stringify(body)}`
  495. )
  496. )
  497. }
  498. db.users.findOne({ email: this.email }, (error, user) => {
  499. if (error != null) {
  500. return callback(error)
  501. }
  502. if (user == null) {
  503. return callback()
  504. }
  505. this.id = user._id.toString()
  506. this._id = user._id.toString()
  507. callback()
  508. })
  509. }
  510. )
  511. })
  512. }
  513. addEmail(email, callback) {
  514. this.emails.push({ email, createdAt: new Date() })
  515. UserUpdater.addEmailAddress(
  516. this.id,
  517. email,
  518. {},
  519. { initiatorId: this._id, ipAddress: '127:0:0:0' },
  520. callback
  521. )
  522. }
  523. confirmEmail(email, callback) {
  524. for (let idx = 0; idx < this.emails.length; idx++) {
  525. const emailData = this.emails[idx]
  526. if (emailData.email === email) {
  527. this.emails[idx].confirmedAt = new Date()
  528. }
  529. }
  530. UserUpdater.confirmEmail(this.id, email, callback)
  531. }
  532. ensureAdmin(callback) {
  533. this.mongoUpdate({ $set: { isAdmin: true } }, callback)
  534. }
  535. ensureStaffAccess(flag, callback) {
  536. const update = { $set: {} }
  537. update.$set[`staffAccess.${flag}`] = true
  538. this.mongoUpdate(update, callback)
  539. }
  540. upgradeSomeFeatures(callback) {
  541. const features = {
  542. collaborators: -1, // Infinite
  543. versioning: true,
  544. dropbox: true,
  545. compileTimeout: 60,
  546. compileGroup: 'priority',
  547. references: true,
  548. trackChanges: true,
  549. trackChangesVisible: true,
  550. }
  551. this.mongoUpdate({ $set: { features } }, callback)
  552. }
  553. downgradeFeatures(callback) {
  554. const features = {
  555. collaborators: 1,
  556. versioning: false,
  557. dropbox: false,
  558. compileTimeout: 60,
  559. compileGroup: 'standard',
  560. references: false,
  561. trackChanges: false,
  562. trackChangesVisible: false,
  563. }
  564. this.mongoUpdate({ $set: { features } }, callback)
  565. }
  566. defaultFeatures(callback) {
  567. const features = settings.defaultFeatures
  568. this.mongoUpdate({ $set: { features } }, callback)
  569. }
  570. getFeatures(callback) {
  571. db.users.findOne(
  572. { _id: new ObjectId(this.id) },
  573. { projection: { features: 1 } },
  574. (error, user) => callback(error, user && user.features)
  575. )
  576. }
  577. fullDeleteUser(email, callback) {
  578. db.users.findOne({ email }, (error, user) => {
  579. if (error != null) {
  580. return callback(error)
  581. }
  582. if (user == null) {
  583. return callback()
  584. }
  585. const userId = user._id
  586. db.projects.deleteMany({ owner_ref: new ObjectId(userId) }, err => {
  587. if (err != null) {
  588. callback(err)
  589. }
  590. db.users.deleteOne({ _id: new ObjectId(userId) }, callback)
  591. })
  592. })
  593. }
  594. deleteUser(callback) {
  595. this.getCsrfToken(error => {
  596. if (error) {
  597. return callback(error)
  598. }
  599. this.request.post(
  600. {
  601. url: '/user/delete',
  602. json: { password: this.password },
  603. },
  604. (err, response, body) => {
  605. if (err) {
  606. return callback(err)
  607. }
  608. if (response.statusCode !== 200) {
  609. return callback(
  610. new Error(
  611. `user deletion failed: status=${
  612. response.statusCode
  613. } body=${JSON.stringify(body)}`
  614. )
  615. )
  616. }
  617. callback()
  618. }
  619. )
  620. })
  621. }
  622. getProject(projectId, callback) {
  623. db.projects.findOne({ _id: new ObjectId(projectId.toString()) }, callback)
  624. }
  625. saveProject(project, callback) {
  626. db.projects.updateOne({ _id: project._id }, { $set: project }, callback)
  627. }
  628. createProject(name, options, callback) {
  629. if (typeof options === 'function') {
  630. callback = options
  631. options = {}
  632. }
  633. this.request.post(
  634. {
  635. url: '/project/new',
  636. json: Object.assign({ projectName: name }, options),
  637. },
  638. (error, response, body) => {
  639. if (error != null) {
  640. return callback(error)
  641. }
  642. if (response.statusCode !== 200) {
  643. return callback(
  644. new Error(
  645. `project creation failed: status=${
  646. response.statusCode
  647. } body=${JSON.stringify(body)}`
  648. )
  649. )
  650. }
  651. if ((body != null ? body.project_id : undefined) == null) {
  652. error = new Error(
  653. JSON.stringify([
  654. 'SOMETHING WENT WRONG CREATING PROJECT',
  655. name,
  656. options,
  657. response.statusCode,
  658. response.headers.location,
  659. body,
  660. ])
  661. )
  662. callback(error)
  663. } else {
  664. callback(null, body.project_id)
  665. }
  666. }
  667. )
  668. }
  669. deleteProject(projectId, callback) {
  670. this.request.delete(
  671. {
  672. url: `/project/${projectId}`,
  673. },
  674. (error, response, body) => {
  675. if (error != null) {
  676. return callback(error)
  677. }
  678. if (response.statusCode !== 200) {
  679. return callback(
  680. new Error(
  681. `project deletion failed: status=${
  682. response.statusCode
  683. } body=${JSON.stringify(body)}`
  684. )
  685. )
  686. }
  687. callback(null)
  688. }
  689. )
  690. }
  691. undeleteProject(projectId, callback) {
  692. this.request.post(
  693. {
  694. url: `/admin/project/${projectId}/undelete`,
  695. },
  696. (error, response, body) => {
  697. if (error) {
  698. return callback(error)
  699. }
  700. if (response.statusCode !== 204) {
  701. return callback(
  702. new Error(
  703. `project un-deletion failed: status=${
  704. response.statusCode
  705. } body=${JSON.stringify(body)}`
  706. )
  707. )
  708. }
  709. callback(null)
  710. }
  711. )
  712. }
  713. deleteProjects(callback) {
  714. db.projects.deleteMany({ owner_ref: new ObjectId(this.id) }, callback)
  715. }
  716. openProject(projectId, callback) {
  717. this.request.get(
  718. {
  719. url: `/project/${projectId}`,
  720. },
  721. (error, response, body) => {
  722. if (error != null) {
  723. return callback(error)
  724. }
  725. if (response.statusCode !== 200) {
  726. return callback(
  727. new Error(
  728. `opening project failed: status=${
  729. response.statusCode
  730. } body=${JSON.stringify(body)}`
  731. )
  732. )
  733. }
  734. callback(null)
  735. }
  736. )
  737. }
  738. createDocInProject(projectId, parentFolderId, name, callback) {
  739. this.getCsrfToken(error => {
  740. if (error != null) {
  741. return callback(error)
  742. }
  743. this.request.post(
  744. {
  745. url: `/project/${projectId}/doc`,
  746. json: {
  747. name,
  748. parentFolderId,
  749. },
  750. },
  751. (error, response, body) => {
  752. if (error != null) {
  753. return callback(error)
  754. }
  755. if (response.statusCode !== 200) {
  756. return callback(
  757. new Error(
  758. `doc creation in project failed: status=${
  759. response.statusCode
  760. } body=${JSON.stringify(body)}`
  761. )
  762. )
  763. }
  764. callback(null, body._id)
  765. }
  766. )
  767. })
  768. }
  769. uploadFileInProject(projectId, folderId, file, name, contentType, callback) {
  770. this.uploadFileInProjectFull(
  771. projectId,
  772. folderId,
  773. file,
  774. name,
  775. contentType,
  776. (err, body) => callback(err, body?.entity_id)
  777. )
  778. }
  779. uploadFileInProjectFull(
  780. projectId,
  781. folderId,
  782. file,
  783. name,
  784. contentType,
  785. callback
  786. ) {
  787. const fileStream = fs.createReadStream(
  788. Path.resolve(Path.join(__dirname, '..', '..', 'files', file))
  789. )
  790. this.request.post(
  791. {
  792. uri: `project/${projectId}/upload`,
  793. qs: {
  794. folder_id: String(folderId),
  795. },
  796. formData: {
  797. name,
  798. qqfile: {
  799. value: fileStream,
  800. options: {
  801. filename: name,
  802. contentType,
  803. },
  804. },
  805. },
  806. },
  807. (error, response, body) => {
  808. if (error) {
  809. return callback(error)
  810. }
  811. if (response.statusCode !== 200) {
  812. return callback(
  813. new Error(
  814. `uploading file failed: status=${
  815. response.statusCode
  816. } body=${JSON.stringify(body)}`
  817. )
  818. )
  819. }
  820. callback(null, JSON.parse(body))
  821. }
  822. )
  823. }
  824. uploadExampleFileInProject(projectId, folderId, name, callback) {
  825. this.uploadFileInProject(
  826. projectId,
  827. folderId,
  828. '1pixel.png',
  829. name,
  830. 'image/png',
  831. callback
  832. )
  833. }
  834. moveItemInProject(projectId, type, itemId, folderId, callback) {
  835. this.request.post(
  836. {
  837. uri: `project/${projectId}/${type}/${itemId}/move`,
  838. json: {
  839. folder_id: folderId,
  840. },
  841. },
  842. (error, response, body) => {
  843. if (error) {
  844. return callback(error)
  845. }
  846. if (response.statusCode !== 200) {
  847. return callback(
  848. new Error(
  849. `move item in project failed: type=${type} status=${
  850. response.statusCode
  851. } body=${JSON.stringify(body)}`
  852. )
  853. )
  854. }
  855. callback()
  856. }
  857. )
  858. }
  859. renameItemInProject(projectId, type, itemId, name, callback) {
  860. this.request.post(
  861. {
  862. uri: `project/${projectId}/${type}/${itemId}/rename`,
  863. json: {
  864. name,
  865. },
  866. },
  867. (error, response, body) => {
  868. if (error) {
  869. return callback(error)
  870. }
  871. if (response.statusCode !== 204) {
  872. return callback(
  873. new Error(
  874. `rename item in project failed: type=${type} status=${
  875. response.statusCode
  876. } body=${JSON.stringify(body)}`
  877. )
  878. )
  879. }
  880. callback()
  881. }
  882. )
  883. }
  884. deleteItemInProject(projectId, type, itemId, callback) {
  885. this.request.delete(
  886. `project/${projectId}/${type}/${itemId}`,
  887. (error, response, body) => {
  888. if (error) {
  889. return callback(error)
  890. }
  891. if (response.statusCode !== 204) {
  892. return callback(
  893. new Error(
  894. `delete item in project failed: type=${type} status=${
  895. response.statusCode
  896. } body=${JSON.stringify(body)}`
  897. )
  898. )
  899. }
  900. callback()
  901. }
  902. )
  903. }
  904. joinProject(projectId, callback) {
  905. this.request.post(
  906. {
  907. url: `/project/${projectId}/join`,
  908. auth: {
  909. user: settings.apis.web.user,
  910. pass: settings.apis.web.pass,
  911. sendImmediately: true,
  912. },
  913. json: { userId: this._id },
  914. jar: false,
  915. },
  916. (error, response, body) => {
  917. if (error) {
  918. return callback(error)
  919. }
  920. if (response.statusCode !== 200) {
  921. return callback(
  922. new Error(
  923. `join project failed: status=${
  924. response.statusCode
  925. } body=${JSON.stringify(body)}`
  926. )
  927. )
  928. }
  929. callback(null, body)
  930. }
  931. )
  932. }
  933. addUserToProject(projectId, user, privileges, callback) {
  934. let updateOp
  935. if (privileges === 'readAndWrite') {
  936. updateOp = { $addToSet: { collaberator_refs: user._id } }
  937. } else if (privileges === 'readOnly') {
  938. updateOp = { $addToSet: { readOnly_refs: user._id } }
  939. } else if (privileges === 'pendingEditor') {
  940. updateOp = {
  941. $addToSet: { readOnly_refs: user._id, pendingEditor_refs: user._id },
  942. }
  943. } else if (privileges === 'pendingReviewer') {
  944. updateOp = {
  945. $addToSet: { readOnly_refs: user._id, pendingReviewer_refs: user._id },
  946. }
  947. } else if (privileges === 'review') {
  948. updateOp = {
  949. $addToSet: { reviewer_refs: user._id },
  950. }
  951. }
  952. db.projects.updateOne({ _id: new ObjectId(projectId) }, updateOp, callback)
  953. }
  954. makePublic(projectId, level, callback) {
  955. // A fudge, to get around the fact that `readOnly` and `readAndWrite` are now disallowed
  956. // via the API, but we still need to test the behaviour of projects with these values set.
  957. db.projects.updateOne(
  958. { _id: new ObjectId(projectId) },
  959. // NOTE: Yes, there is a typo in the db schema.
  960. { $set: { publicAccesLevel: level } },
  961. callback
  962. )
  963. }
  964. makePrivate(projectId, callback) {
  965. this.request.post(
  966. {
  967. url: `/project/${projectId}/settings/admin`,
  968. json: {
  969. publicAccessLevel: 'private',
  970. },
  971. },
  972. (error, response, body) => {
  973. if (error != null) {
  974. return callback(error)
  975. }
  976. if (response.statusCode !== 204) {
  977. return callback(
  978. new Error(
  979. `disable link sharing failed: status=${
  980. response.statusCode
  981. } body=${JSON.stringify(body)}`
  982. )
  983. )
  984. }
  985. callback(null)
  986. }
  987. )
  988. }
  989. makeTokenBased(projectId, callback) {
  990. this.request.post(
  991. {
  992. url: `/project/${projectId}/settings/admin`,
  993. json: {
  994. publicAccessLevel: 'tokenBased',
  995. },
  996. },
  997. (error, response, body) => {
  998. if (error != null) {
  999. return callback(error)
  1000. }
  1001. if (response.statusCode !== 204) {
  1002. return callback(
  1003. new Error(
  1004. `enable link sharing failed: status=${
  1005. response.statusCode
  1006. } body=${JSON.stringify(body)}`
  1007. )
  1008. )
  1009. }
  1010. callback(null)
  1011. }
  1012. )
  1013. }
  1014. getCsrfToken(callback) {
  1015. this.request.get(
  1016. {
  1017. url: '/dev/csrf',
  1018. },
  1019. (err, response, body) => {
  1020. if (err != null) {
  1021. return callback(err)
  1022. }
  1023. if (response.statusCode !== 200) {
  1024. return callback(
  1025. new Error(
  1026. `get csrf token failed: status=${
  1027. response.statusCode
  1028. } body=${JSON.stringify(body)}`
  1029. )
  1030. )
  1031. }
  1032. this.csrfToken = body
  1033. this.request = this.request.defaults({
  1034. headers: {
  1035. 'x-csrf-token': this.csrfToken,
  1036. },
  1037. })
  1038. callback()
  1039. }
  1040. )
  1041. }
  1042. changePassword(newPassword, callback) {
  1043. this.getCsrfToken(error => {
  1044. if (error != null) {
  1045. return callback(error)
  1046. }
  1047. this.request.post(
  1048. {
  1049. url: '/user/password/update',
  1050. json: {
  1051. currentPassword: this.password,
  1052. newPassword1: newPassword,
  1053. newPassword2: newPassword,
  1054. },
  1055. },
  1056. (err, response, body) => {
  1057. if (err) {
  1058. return callback(err)
  1059. }
  1060. if (response.statusCode !== 200) {
  1061. return callback(
  1062. new Error(
  1063. `change password failed: status=${
  1064. response.statusCode
  1065. } body=${JSON.stringify(body)}`
  1066. )
  1067. )
  1068. }
  1069. this.password = newPassword
  1070. callback()
  1071. }
  1072. )
  1073. })
  1074. }
  1075. reconfirmAccountRequest(userEmail, callback) {
  1076. this.getCsrfToken(error => {
  1077. if (error != null) {
  1078. return callback(error)
  1079. }
  1080. this.request.post(
  1081. {
  1082. url: '/user/reconfirm',
  1083. json: {
  1084. email: userEmail,
  1085. },
  1086. },
  1087. (error, response) => {
  1088. callback(error, response)
  1089. }
  1090. )
  1091. })
  1092. }
  1093. getUserSettingsPage(callback) {
  1094. this.getCsrfToken(error => {
  1095. if (error != null) {
  1096. return callback(error)
  1097. }
  1098. this.request.get(
  1099. {
  1100. url: '/user/settings',
  1101. },
  1102. (error, response, body) => {
  1103. if (error != null) {
  1104. return callback(error)
  1105. }
  1106. if (response.statusCode !== 200) {
  1107. return callback(
  1108. new Error(
  1109. `open settings page failed: status=${
  1110. response.statusCode
  1111. } body=${JSON.stringify(body)}`
  1112. )
  1113. )
  1114. }
  1115. callback(null, response.statusCode)
  1116. }
  1117. )
  1118. })
  1119. }
  1120. updateSettings(newSettings, callback) {
  1121. this.getCsrfToken(error => {
  1122. if (error != null) {
  1123. return callback(error)
  1124. }
  1125. this.request.post(
  1126. {
  1127. url: '/user/settings',
  1128. json: newSettings,
  1129. },
  1130. (err, response, body) => {
  1131. if (err) {
  1132. return callback(err)
  1133. }
  1134. if (response.statusCode !== 200) {
  1135. return callback(
  1136. new Error(
  1137. `update settings failed: status=${
  1138. response.statusCode
  1139. } body=${JSON.stringify(body)}`
  1140. )
  1141. )
  1142. }
  1143. callback()
  1144. }
  1145. )
  1146. })
  1147. }
  1148. getProjectListPage(callback) {
  1149. this.request.get('/project', (error, response) => {
  1150. if (error != null) {
  1151. return callback(error)
  1152. }
  1153. callback(null, response.statusCode)
  1154. })
  1155. }
  1156. isLoggedIn(callback) {
  1157. this.request.get('/user/personal_info', (error, response, body) => {
  1158. if (error != null) {
  1159. return callback(error)
  1160. }
  1161. if (response.statusCode === 200) {
  1162. callback(null, true)
  1163. } else if (response.statusCode === 302) {
  1164. callback(null, false)
  1165. } else {
  1166. callback(
  1167. new Error(
  1168. `unexpected status code from /user/personal_info: status=${response.statusCode} body=${body}`
  1169. )
  1170. )
  1171. }
  1172. })
  1173. }
  1174. transferProjectOwnership(projectId, userId, callback) {
  1175. this.getCsrfToken(err => {
  1176. if (err != null) {
  1177. return callback(err)
  1178. }
  1179. this.request.post(
  1180. {
  1181. url: `/project/${projectId.toString()}/transfer-ownership`,
  1182. json: {
  1183. user_id: userId.toString(),
  1184. },
  1185. },
  1186. (err, response, body) => {
  1187. if (err != null) {
  1188. return callback(err)
  1189. }
  1190. if (response.statusCode !== 204) {
  1191. return callback(
  1192. new Error(
  1193. `transfer project ownership failed: status=${
  1194. response.statusCode
  1195. } body=${JSON.stringify(body)}`
  1196. )
  1197. )
  1198. }
  1199. callback()
  1200. }
  1201. )
  1202. })
  1203. }
  1204. setV1Id(v1Id, callback) {
  1205. UserModel.updateOne(
  1206. {
  1207. _id: this._id,
  1208. },
  1209. {
  1210. overleaf: {
  1211. id: v1Id,
  1212. },
  1213. }
  1214. )
  1215. .then((...args) => callback(null, ...args))
  1216. .catch(callback)
  1217. }
  1218. setCollaboratorInfo(projectId, userId, info, callback) {
  1219. this.getCsrfToken(err => {
  1220. if (err != null) {
  1221. return callback(err)
  1222. }
  1223. this.request.put(
  1224. {
  1225. url: `/project/${projectId.toString()}/users/${userId.toString()}`,
  1226. json: info,
  1227. },
  1228. (err, response, body) => {
  1229. if (err != null) {
  1230. return callback(err)
  1231. }
  1232. if (response.statusCode !== 204) {
  1233. return callback(
  1234. new Error(
  1235. `update collaborator access failed: status=${
  1236. response.statusCode
  1237. } body=${JSON.stringify(body)}`
  1238. )
  1239. )
  1240. }
  1241. callback()
  1242. }
  1243. )
  1244. })
  1245. }
  1246. }
  1247. User.promises = promisifyClass(User, {
  1248. without: ['setExtraAttributes', 'sessionCookie', 'setSessionCookie'],
  1249. })
  1250. User.promises.prototype.doRequest = async function (method, params) {
  1251. return new Promise((resolve, reject) => {
  1252. this.request[method.toLowerCase()](params, (err, response, body) => {
  1253. if (err) {
  1254. reject(err)
  1255. } else {
  1256. resolve({ response, body })
  1257. }
  1258. })
  1259. })
  1260. }
  1261. export default User