User.mjs 33 KB

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