User.mjs 33 KB

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