User.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. const OError = require('@overleaf/o-error')
  2. const request = require('./request')
  3. const settings = require('@overleaf/settings')
  4. const { db, ObjectId } = require('../../../../app/src/infrastructure/mongodb')
  5. const UserModel = require('../../../../app/src/models/User').User
  6. const UserUpdater = require('../../../../app/src/Features/User/UserUpdater')
  7. const AuthenticationManager = require('../../../../app/src/Features/Authentication/AuthenticationManager')
  8. const { promisify } = require('util')
  9. const fs = require('fs')
  10. const Path = require('path')
  11. let count = settings.test.counterInit
  12. class User {
  13. constructor(options) {
  14. if (options == null) {
  15. options = {}
  16. }
  17. this.emails = [
  18. {
  19. email: options.email || `acceptance-test-${count}@example.com`,
  20. createdAt: new Date(),
  21. confirmedAt: options.confirmedAt,
  22. },
  23. ]
  24. this.email = this.emails[0].email
  25. this.password = `a-terrible-secret-${count}`
  26. count++
  27. this.jar = request.jar()
  28. this.request = request.defaults({
  29. jar: this.jar,
  30. })
  31. }
  32. resetCookies() {
  33. this.jar = request.jar()
  34. this.request = request.defaults({
  35. jar: this.jar,
  36. })
  37. }
  38. setExtraAttributes(user) {
  39. if ((user != null ? user._id : undefined) == null) {
  40. throw new Error('User does not exist')
  41. }
  42. this.id = user._id.toString()
  43. this._id = user._id.toString()
  44. this.first_name = user.first_name
  45. this.referal_id = user.referal_id
  46. this.enrollment = user.enrollment
  47. }
  48. get(callback) {
  49. db.users.findOne({ _id: new ObjectId(this._id) }, callback)
  50. }
  51. getAuditLog(callback) {
  52. this.get((error, user) => {
  53. if (error) return callback(error)
  54. if (!user) return callback(new Error('User not found'))
  55. db.userAuditLogEntries
  56. .find({ userId: new ObjectId(this._id) })
  57. .toArray((error, auditLog) => {
  58. if (error) return callback(error)
  59. callback(null, auditLog || [])
  60. })
  61. })
  62. }
  63. getAuditLogWithoutNoise(callback) {
  64. this.getAuditLog((error, auditLog) => {
  65. if (error) return callback(error)
  66. callback(
  67. null,
  68. auditLog.filter(entry => {
  69. return entry.operation !== 'login'
  70. })
  71. )
  72. })
  73. }
  74. mongoUpdate(updateOp, callback) {
  75. db.users.updateOne({ _id: new ObjectId(this._id) }, updateOp, callback)
  76. }
  77. register(callback) {
  78. this.registerWithQuery('', callback)
  79. }
  80. registerWithQuery(query, callback) {
  81. if (this._id != null) {
  82. return callback(new Error('User already registered'))
  83. }
  84. this.getCsrfToken(error => {
  85. if (error != null) {
  86. return callback(error)
  87. }
  88. this.request.post(
  89. {
  90. url: `/register${query}`,
  91. json: { email: this.email, password: this.password },
  92. },
  93. (error, response, body) => {
  94. if (error != null) {
  95. return callback(error)
  96. }
  97. if (response.statusCode !== 200) {
  98. return callback(
  99. new Error(
  100. `register failed: status=${
  101. response.statusCode
  102. } body=${JSON.stringify(body)}`
  103. )
  104. )
  105. }
  106. db.users.findOne({ email: this.email }, (error, user) => {
  107. if (error != null) {
  108. return callback(error)
  109. }
  110. this.setExtraAttributes(user)
  111. callback(null, user)
  112. })
  113. }
  114. )
  115. })
  116. }
  117. login(callback) {
  118. this.loginWith(this.email, callback)
  119. }
  120. loginWith(email, callback) {
  121. this.ensureUserExists(error => {
  122. if (error != null) {
  123. return callback(error)
  124. }
  125. this.loginWithEmailPassword(email, this.password, callback)
  126. })
  127. }
  128. loginNoUpdate(callback) {
  129. this.loginWithEmailPassword(this.email, this.password, callback)
  130. }
  131. loginWithEmailPassword(email, password, callback) {
  132. this.getCsrfToken(error => {
  133. if (error != null) {
  134. return callback(error)
  135. }
  136. this.request.post(
  137. {
  138. url: settings.enableLegacyLogin ? '/login/legacy' : '/login',
  139. json: {
  140. email,
  141. password,
  142. 'g-recaptcha-response': 'valid',
  143. },
  144. },
  145. (error, response, body) => {
  146. if (error != null) {
  147. return callback(error)
  148. }
  149. if (response.statusCode !== 200) {
  150. return callback(
  151. new OError(
  152. `login failed: status=${
  153. response.statusCode
  154. } body=${JSON.stringify(body)}`,
  155. { response, body }
  156. )
  157. )
  158. }
  159. // get new csrf token, then return result of login
  160. this.getCsrfToken(err => {
  161. if (err) {
  162. return callback(OError.tag(err, 'after login'))
  163. }
  164. callback(null, response, body)
  165. })
  166. }
  167. )
  168. })
  169. }
  170. ensureUserExists(callback) {
  171. const filter = { email: this.email }
  172. const options = { upsert: true, new: true, setDefaultsOnInsert: true }
  173. AuthenticationManager.hashPassword(
  174. this.password,
  175. (error, hashedPassword) => {
  176. if (error != null) {
  177. return callback(error)
  178. }
  179. UserModel.findOneAndUpdate(
  180. filter,
  181. { $set: { hashedPassword, emails: this.emails } },
  182. options,
  183. (error, user) => {
  184. if (error != null) {
  185. return callback(error)
  186. }
  187. this.setExtraAttributes(user)
  188. callback(null, this.password)
  189. }
  190. )
  191. }
  192. )
  193. }
  194. setFeatures(features, callback) {
  195. const update = {}
  196. for (const key in features) {
  197. const value = features[key]
  198. update[`features.${key}`] = value
  199. }
  200. UserModel.updateOne({ _id: this.id }, update, callback)
  201. }
  202. setFeaturesOverride(featuresOverride, callback) {
  203. const update = { $push: { featuresOverrides: featuresOverride } }
  204. UserModel.updateOne({ _id: this.id }, update, callback)
  205. }
  206. setOverleafId(overleafId, callback) {
  207. UserModel.updateOne(
  208. { _id: this.id },
  209. { 'overleaf.id': overleafId },
  210. callback
  211. )
  212. }
  213. setEmails(emails, callback) {
  214. UserModel.updateOne({ _id: this.id }, { emails }, callback)
  215. }
  216. logout(callback) {
  217. this.getCsrfToken(error => {
  218. if (error != null) {
  219. return callback(error)
  220. }
  221. this.request.post(
  222. {
  223. url: '/logout',
  224. json: {
  225. email: this.email,
  226. password: this.password,
  227. },
  228. },
  229. (error, response, body) => {
  230. if (error != null) {
  231. return callback(error)
  232. }
  233. if (response.statusCode !== 200) {
  234. return callback(
  235. new Error(
  236. `logout failed: status=${
  237. response.statusCode
  238. } body=${JSON.stringify(body)}`
  239. )
  240. )
  241. }
  242. db.users.findOne({ email: this.email }, (error, user) => {
  243. if (error != null) {
  244. return callback(error)
  245. }
  246. if (user == null) {
  247. return callback()
  248. }
  249. this.id = user._id.toString()
  250. this._id = user._id.toString()
  251. callback()
  252. })
  253. }
  254. )
  255. })
  256. }
  257. addEmail(email, callback) {
  258. this.emails.push({ email, createdAt: new Date() })
  259. UserUpdater.addEmailAddress(
  260. this.id,
  261. email,
  262. {},
  263. { initiatorId: this._id, ipAddress: '127:0:0:0' },
  264. callback
  265. )
  266. }
  267. confirmEmail(email, callback) {
  268. for (let idx = 0; idx < this.emails.length; idx++) {
  269. const emailData = this.emails[idx]
  270. if (emailData.email === email) {
  271. this.emails[idx].confirmedAt = new Date()
  272. }
  273. }
  274. UserUpdater.confirmEmail(this.id, email, callback)
  275. }
  276. ensureAdmin(callback) {
  277. this.mongoUpdate({ $set: { isAdmin: true } }, callback)
  278. }
  279. ensureStaffAccess(flag, callback) {
  280. const update = { $set: {} }
  281. update.$set[`staffAccess.${flag}`] = true
  282. this.mongoUpdate(update, callback)
  283. }
  284. upgradeFeatures(callback) {
  285. const features = {
  286. collaborators: -1, // Infinite
  287. versioning: true,
  288. dropbox: true,
  289. compileTimeout: 60,
  290. compileGroup: 'priority',
  291. templates: true,
  292. references: true,
  293. trackChanges: true,
  294. trackChangesVisible: true,
  295. }
  296. this.mongoUpdate({ $set: { features } }, callback)
  297. }
  298. downgradeFeatures(callback) {
  299. const features = {
  300. collaborators: 1,
  301. versioning: false,
  302. dropbox: false,
  303. compileTimeout: 60,
  304. compileGroup: 'standard',
  305. templates: false,
  306. references: false,
  307. trackChanges: false,
  308. trackChangesVisible: false,
  309. }
  310. this.mongoUpdate({ $set: { features } }, callback)
  311. }
  312. defaultFeatures(callback) {
  313. const features = settings.defaultFeatures
  314. this.mongoUpdate({ $set: { features } }, callback)
  315. }
  316. getFeatures(callback) {
  317. db.users.findOne(
  318. { _id: new ObjectId(this.id) },
  319. { projection: { features: 1 } },
  320. (error, user) => callback(error, user && user.features)
  321. )
  322. }
  323. fullDeleteUser(email, callback) {
  324. db.users.findOne({ email }, (error, user) => {
  325. if (error != null) {
  326. return callback(error)
  327. }
  328. if (user == null) {
  329. return callback()
  330. }
  331. const userId = user._id
  332. db.projects.deleteMany({ owner_ref: new ObjectId(userId) }, err => {
  333. if (err != null) {
  334. callback(err)
  335. }
  336. db.users.deleteOne({ _id: new ObjectId(userId) }, callback)
  337. })
  338. })
  339. }
  340. deleteUser(callback) {
  341. this.getCsrfToken(error => {
  342. if (error) {
  343. return callback(error)
  344. }
  345. this.request.post(
  346. {
  347. url: '/user/delete',
  348. json: { password: this.password },
  349. },
  350. (err, response, body) => {
  351. if (err) {
  352. return callback(err)
  353. }
  354. if (response.statusCode !== 200) {
  355. return callback(
  356. new Error(
  357. `user deletion failed: status=${
  358. response.statusCode
  359. } body=${JSON.stringify(body)}`
  360. )
  361. )
  362. }
  363. callback()
  364. }
  365. )
  366. })
  367. }
  368. getProject(projectId, callback) {
  369. db.projects.findOne({ _id: new ObjectId(projectId.toString()) }, callback)
  370. }
  371. saveProject(project, callback) {
  372. db.projects.updateOne({ _id: project._id }, { $set: project }, callback)
  373. }
  374. createProject(name, options, callback) {
  375. if (typeof options === 'function') {
  376. callback = options
  377. options = {}
  378. }
  379. this.request.post(
  380. {
  381. url: '/project/new',
  382. json: Object.assign({ projectName: name }, options),
  383. },
  384. (error, response, body) => {
  385. if (error != null) {
  386. return callback(error)
  387. }
  388. if (response.statusCode !== 200) {
  389. return callback(
  390. new Error(
  391. `project creation failed: status=${
  392. response.statusCode
  393. } body=${JSON.stringify(body)}`
  394. )
  395. )
  396. }
  397. if ((body != null ? body.project_id : undefined) == null) {
  398. error = new Error(
  399. JSON.stringify([
  400. 'SOMETHING WENT WRONG CREATING PROJECT',
  401. name,
  402. options,
  403. response.statusCode,
  404. response.headers.location,
  405. body,
  406. ])
  407. )
  408. callback(error)
  409. } else {
  410. callback(null, body.project_id)
  411. }
  412. }
  413. )
  414. }
  415. deleteProject(projectId, callback) {
  416. this.request.delete(
  417. {
  418. url: `/project/${projectId}`,
  419. },
  420. (error, response, body) => {
  421. if (error != null) {
  422. return callback(error)
  423. }
  424. if (response.statusCode !== 200) {
  425. return callback(
  426. new Error(
  427. `project deletion failed: status=${
  428. response.statusCode
  429. } body=${JSON.stringify(body)}`
  430. )
  431. )
  432. }
  433. callback(null)
  434. }
  435. )
  436. }
  437. undeleteProject(projectId, callback) {
  438. this.request.post(
  439. {
  440. url: `/admin/project/${projectId}/undelete`,
  441. },
  442. (error, response, body) => {
  443. if (error) {
  444. return callback(error)
  445. }
  446. if (response.statusCode !== 204) {
  447. return callback(
  448. new Error(
  449. `project un-deletion failed: status=${
  450. response.statusCode
  451. } body=${JSON.stringify(body)}`
  452. )
  453. )
  454. }
  455. callback(null)
  456. }
  457. )
  458. }
  459. deleteProjects(callback) {
  460. db.projects.deleteMany({ owner_ref: new ObjectId(this.id) }, callback)
  461. }
  462. openProject(projectId, callback) {
  463. this.request.get(
  464. {
  465. url: `/project/${projectId}`,
  466. },
  467. (error, response, body) => {
  468. if (error != null) {
  469. return callback(error)
  470. }
  471. if (response.statusCode !== 200) {
  472. return callback(
  473. new Error(
  474. `opening project failed: status=${
  475. response.statusCode
  476. } body=${JSON.stringify(body)}`
  477. )
  478. )
  479. }
  480. callback(null)
  481. }
  482. )
  483. }
  484. createDocInProject(projectId, parentFolderId, name, callback) {
  485. this.getCsrfToken(error => {
  486. if (error != null) {
  487. return callback(error)
  488. }
  489. this.request.post(
  490. {
  491. url: `/project/${projectId}/doc`,
  492. json: {
  493. name,
  494. parentFolderId,
  495. },
  496. },
  497. (error, response, body) => {
  498. if (error != null) {
  499. return callback(error)
  500. }
  501. if (response.statusCode !== 200) {
  502. return callback(
  503. new Error(
  504. `doc creation in project failed: status=${
  505. response.statusCode
  506. } body=${JSON.stringify(body)}`
  507. )
  508. )
  509. }
  510. callback(null, body._id)
  511. }
  512. )
  513. })
  514. }
  515. uploadFileInProject(projectId, folderId, file, name, contentType, callback) {
  516. const fileStream = fs.createReadStream(
  517. Path.resolve(Path.join(__dirname, '..', '..', 'files', file))
  518. )
  519. this.request.post(
  520. {
  521. uri: `project/${projectId}/upload`,
  522. qs: {
  523. folder_id: String(folderId),
  524. },
  525. formData: {
  526. name,
  527. qqfile: {
  528. value: fileStream,
  529. options: {
  530. filename: name,
  531. contentType,
  532. },
  533. },
  534. },
  535. },
  536. (error, response, body) => {
  537. if (error) {
  538. return callback(error)
  539. }
  540. if (response.statusCode !== 200) {
  541. return callback(
  542. new Error(
  543. `uploading file failed: status=${
  544. response.statusCode
  545. } body=${JSON.stringify(body)}`
  546. )
  547. )
  548. }
  549. callback(null, JSON.parse(body).entity_id)
  550. }
  551. )
  552. }
  553. uploadExampleFileInProject(projectId, folderId, name, callback) {
  554. this.uploadFileInProject(
  555. projectId,
  556. folderId,
  557. '1pixel.png',
  558. name,
  559. 'image/png',
  560. callback
  561. )
  562. }
  563. moveItemInProject(projectId, type, itemId, folderId, callback) {
  564. this.request.post(
  565. {
  566. uri: `project/${projectId}/${type}/${itemId}/move`,
  567. json: {
  568. folder_id: folderId,
  569. },
  570. },
  571. (error, response, body) => {
  572. if (error) {
  573. return callback(error)
  574. }
  575. if (response.statusCode !== 200) {
  576. return callback(
  577. new Error(
  578. `move item in project failed: type=${type} status=${
  579. response.statusCode
  580. } body=${JSON.stringify(body)}`
  581. )
  582. )
  583. }
  584. callback()
  585. }
  586. )
  587. }
  588. renameItemInProject(projectId, type, itemId, name, callback) {
  589. this.request.post(
  590. {
  591. uri: `project/${projectId}/${type}/${itemId}/rename`,
  592. json: {
  593. name,
  594. },
  595. },
  596. (error, response, body) => {
  597. if (error) {
  598. return callback(error)
  599. }
  600. if (response.statusCode !== 204) {
  601. return callback(
  602. new Error(
  603. `rename item in project failed: type=${type} status=${
  604. response.statusCode
  605. } body=${JSON.stringify(body)}`
  606. )
  607. )
  608. }
  609. callback()
  610. }
  611. )
  612. }
  613. deleteItemInProject(projectId, type, itemId, callback) {
  614. this.request.delete(
  615. `project/${projectId}/${type}/${itemId}`,
  616. (error, response, body) => {
  617. if (error) {
  618. return callback(error)
  619. }
  620. if (response.statusCode !== 204) {
  621. return callback(
  622. new Error(
  623. `delete item in project failed: type=${type} status=${
  624. response.statusCode
  625. } body=${JSON.stringify(body)}`
  626. )
  627. )
  628. }
  629. callback()
  630. }
  631. )
  632. }
  633. joinProject(projectId, callback) {
  634. this.request.post(
  635. {
  636. url: `/project/${projectId}/join`,
  637. auth: {
  638. user: settings.apis.web.user,
  639. pass: settings.apis.web.pass,
  640. sendImmediately: true,
  641. },
  642. json: { userId: this._id },
  643. jar: false,
  644. },
  645. (error, response, body) => {
  646. if (error) {
  647. return callback(error)
  648. }
  649. if (response.statusCode !== 200) {
  650. return callback(
  651. new Error(
  652. `join project failed: status=${
  653. response.statusCode
  654. } body=${JSON.stringify(body)}`
  655. )
  656. )
  657. }
  658. callback(null, body)
  659. }
  660. )
  661. }
  662. addUserToProject(projectId, user, privileges, callback) {
  663. let updateOp
  664. if (privileges === 'readAndWrite') {
  665. updateOp = { $addToSet: { collaberator_refs: user._id } }
  666. } else if (privileges === 'readOnly') {
  667. updateOp = { $addToSet: { readOnly_refs: user._id } }
  668. }
  669. db.projects.updateOne({ _id: new ObjectId(projectId) }, updateOp, callback)
  670. }
  671. makePublic(projectId, level, callback) {
  672. // A fudge, to get around the fact that `readOnly` and `readAndWrite` are now disallowed
  673. // via the API, but we still need to test the behaviour of projects with these values set.
  674. db.projects.updateOne(
  675. { _id: new ObjectId(projectId) },
  676. // NOTE: Yes, there is a typo in the db schema.
  677. { $set: { publicAccesLevel: level } },
  678. callback
  679. )
  680. }
  681. makePrivate(projectId, callback) {
  682. this.request.post(
  683. {
  684. url: `/project/${projectId}/settings/admin`,
  685. json: {
  686. publicAccessLevel: 'private',
  687. },
  688. },
  689. (error, response, body) => {
  690. if (error != null) {
  691. return callback(error)
  692. }
  693. if (response.statusCode !== 204) {
  694. return callback(
  695. new Error(
  696. `disable link sharing failed: status=${
  697. response.statusCode
  698. } body=${JSON.stringify(body)}`
  699. )
  700. )
  701. }
  702. callback(null)
  703. }
  704. )
  705. }
  706. makeTokenBased(projectId, callback) {
  707. this.request.post(
  708. {
  709. url: `/project/${projectId}/settings/admin`,
  710. json: {
  711. publicAccessLevel: 'tokenBased',
  712. },
  713. },
  714. (error, response, body) => {
  715. if (error != null) {
  716. return callback(error)
  717. }
  718. if (response.statusCode !== 204) {
  719. return callback(
  720. new Error(
  721. `enable link sharing failed: status=${
  722. response.statusCode
  723. } body=${JSON.stringify(body)}`
  724. )
  725. )
  726. }
  727. callback(null)
  728. }
  729. )
  730. }
  731. getCsrfToken(callback) {
  732. this.request.get(
  733. {
  734. url: '/dev/csrf',
  735. },
  736. (err, response, body) => {
  737. if (err != null) {
  738. return callback(err)
  739. }
  740. if (response.statusCode !== 200) {
  741. return callback(
  742. new Error(
  743. `get csrf token failed: status=${
  744. response.statusCode
  745. } body=${JSON.stringify(body)}`
  746. )
  747. )
  748. }
  749. this.csrfToken = body
  750. this.request = this.request.defaults({
  751. headers: {
  752. 'x-csrf-token': this.csrfToken,
  753. },
  754. })
  755. callback()
  756. }
  757. )
  758. }
  759. changePassword(newPassword, callback) {
  760. this.getCsrfToken(error => {
  761. if (error != null) {
  762. return callback(error)
  763. }
  764. this.request.post(
  765. {
  766. url: '/user/password/update',
  767. json: {
  768. currentPassword: this.password,
  769. newPassword1: newPassword,
  770. newPassword2: newPassword,
  771. },
  772. },
  773. (err, response, body) => {
  774. if (err) {
  775. return callback(err)
  776. }
  777. if (response.statusCode !== 200) {
  778. return callback(
  779. new Error(
  780. `change password failed: status=${
  781. response.statusCode
  782. } body=${JSON.stringify(body)}`
  783. )
  784. )
  785. }
  786. this.password = newPassword
  787. callback()
  788. }
  789. )
  790. })
  791. }
  792. reconfirmAccountRequest(userEmail, callback) {
  793. this.getCsrfToken(error => {
  794. if (error != null) {
  795. return callback(error)
  796. }
  797. this.request.post(
  798. {
  799. url: '/user/reconfirm',
  800. json: {
  801. email: userEmail,
  802. },
  803. },
  804. (error, response) => {
  805. callback(error, response)
  806. }
  807. )
  808. })
  809. }
  810. getUserSettingsPage(callback) {
  811. this.getCsrfToken(error => {
  812. if (error != null) {
  813. return callback(error)
  814. }
  815. this.request.get(
  816. {
  817. url: '/user/settings',
  818. },
  819. (error, response, body) => {
  820. if (error != null) {
  821. return callback(error)
  822. }
  823. if (response.statusCode !== 200) {
  824. return callback(
  825. new Error(
  826. `open settings page failed: status=${
  827. response.statusCode
  828. } body=${JSON.stringify(body)}`
  829. )
  830. )
  831. }
  832. callback(null, response.statusCode)
  833. }
  834. )
  835. })
  836. }
  837. updateSettings(newSettings, callback) {
  838. this.getCsrfToken(error => {
  839. if (error != null) {
  840. return callback(error)
  841. }
  842. this.request.post(
  843. {
  844. url: '/user/settings',
  845. json: newSettings,
  846. },
  847. (err, response, body) => {
  848. if (err) return callback(err)
  849. if (response.statusCode !== 200) {
  850. return callback(
  851. new Error(
  852. `login failed: status=${
  853. response.statusCode
  854. } body=${JSON.stringify(body)}`
  855. )
  856. )
  857. }
  858. callback()
  859. }
  860. )
  861. })
  862. }
  863. getProjectListPage(callback) {
  864. this.request.get('/project', (error, response) => {
  865. if (error != null) {
  866. return callback(error)
  867. }
  868. callback(null, response.statusCode)
  869. })
  870. }
  871. isLoggedIn(callback) {
  872. this.request.get('/user/personal_info', (error, response, body) => {
  873. if (error != null) {
  874. return callback(error)
  875. }
  876. if (response.statusCode === 200) {
  877. callback(null, true)
  878. } else if (response.statusCode === 302) {
  879. callback(null, false)
  880. } else {
  881. callback(
  882. new Error(
  883. `unexpected status code from /user/personal_info: status=${response.statusCode} body=${body}`
  884. )
  885. )
  886. }
  887. })
  888. }
  889. transferProjectOwnership(projectId, userId, callback) {
  890. this.getCsrfToken(err => {
  891. if (err != null) {
  892. return callback(err)
  893. }
  894. this.request.post(
  895. {
  896. url: `/project/${projectId.toString()}/transfer-ownership`,
  897. json: {
  898. user_id: userId.toString(),
  899. },
  900. },
  901. (err, response, body) => {
  902. if (err != null) {
  903. return callback(err)
  904. }
  905. if (response.statusCode !== 204) {
  906. return callback(
  907. new Error(
  908. `transfer project ownership failed: status=${
  909. response.statusCode
  910. } body=${JSON.stringify(body)}`
  911. )
  912. )
  913. }
  914. callback()
  915. }
  916. )
  917. })
  918. }
  919. setV1Id(v1Id, callback) {
  920. UserModel.updateOne(
  921. {
  922. _id: this._id,
  923. },
  924. {
  925. overleaf: {
  926. id: v1Id,
  927. },
  928. },
  929. callback
  930. )
  931. }
  932. setCollaboratorInfo(projectId, userId, info, callback) {
  933. this.getCsrfToken(err => {
  934. if (err != null) {
  935. return callback(err)
  936. }
  937. this.request.put(
  938. {
  939. url: `/project/${projectId.toString()}/users/${userId.toString()}`,
  940. json: info,
  941. },
  942. (err, response, body) => {
  943. if (err != null) {
  944. return callback(err)
  945. }
  946. if (response.statusCode !== 204) {
  947. return callback(
  948. new Error(
  949. `update collaborator access failed: status=${
  950. response.statusCode
  951. } body=${JSON.stringify(body)}`
  952. )
  953. )
  954. }
  955. callback()
  956. }
  957. )
  958. })
  959. }
  960. }
  961. User.promises = class extends User {
  962. doRequest(method, params) {
  963. return new Promise((resolve, reject) => {
  964. this.request[method.toLowerCase()](params, (err, response, body) => {
  965. if (err) {
  966. reject(err)
  967. } else {
  968. resolve({ response, body })
  969. }
  970. })
  971. })
  972. }
  973. }
  974. // promisify User class methods - works for methods with 0-1 output parameters,
  975. // otherwise we will need to implement the method manually instead
  976. const nonPromiseMethods = ['constructor', 'setExtraAttributes']
  977. Object.getOwnPropertyNames(User.prototype).forEach(methodName => {
  978. const method = User.prototype[methodName]
  979. if (typeof method === 'function' && !nonPromiseMethods.includes(methodName)) {
  980. User.promises.prototype[methodName] = promisify(method)
  981. }
  982. })
  983. module.exports = User