User.mjs 33 KB

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