User.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  1. const request = require('./request')
  2. const settings = require('settings-sharelatex')
  3. const { db, ObjectId } = require('../../../../app/src/infrastructure/mongojs')
  4. const UserModel = require('../../../../app/src/models/User').User
  5. const UserUpdater = require('../../../../app/src/Features/User/UserUpdater')
  6. const AuthenticationManager = require('../../../../app/src/Features/Authentication/AuthenticationManager')
  7. const { promisify } = require('util')
  8. let count = 0
  9. class User {
  10. constructor(options) {
  11. if (options == null) {
  12. options = {}
  13. }
  14. this.emails = [
  15. {
  16. email: options.email || `acceptance-test-${count}@example.com`,
  17. createdAt: new Date()
  18. }
  19. ]
  20. this.email = this.emails[0].email
  21. this.password = `acceptance-test-${count}-password`
  22. count++
  23. this.jar = request.jar()
  24. this.request = request.defaults({
  25. jar: this.jar
  26. })
  27. }
  28. setExtraAttributes(user) {
  29. if ((user != null ? user._id : undefined) == null) {
  30. throw new Error('User does not exist')
  31. }
  32. this.id = user._id.toString()
  33. this._id = user._id.toString()
  34. this.first_name = user.first_name
  35. this.referal_id = user.referal_id
  36. }
  37. get(callback) {
  38. db.users.findOne({ _id: ObjectId(this._id) }, callback)
  39. }
  40. mongoUpdate(updateOp, callback) {
  41. db.users.update({ _id: ObjectId(this._id) }, updateOp, callback)
  42. }
  43. register(callback) {
  44. this.registerWithQuery('', callback)
  45. }
  46. registerWithQuery(query, callback) {
  47. if (this._id != null) {
  48. return callback(new Error('User already registered'))
  49. }
  50. this.getCsrfToken(error => {
  51. if (error != null) {
  52. return callback(error)
  53. }
  54. this.request.post(
  55. {
  56. url: `/register${query}`,
  57. json: { email: this.email, password: this.password }
  58. },
  59. (error, response, body) => {
  60. if (error != null) {
  61. return callback(error)
  62. }
  63. db.users.findOne({ email: this.email }, (error, user) => {
  64. if (error != null) {
  65. return callback(error)
  66. }
  67. this.setExtraAttributes(user)
  68. callback(null, user)
  69. })
  70. }
  71. )
  72. })
  73. }
  74. login(callback) {
  75. this.loginWith(this.email, callback)
  76. }
  77. loginWith(email, callback) {
  78. this.ensureUserExists(error => {
  79. if (error != null) {
  80. return callback(error)
  81. }
  82. this.getCsrfToken(error => {
  83. if (error != null) {
  84. return callback(error)
  85. }
  86. this.request.post(
  87. {
  88. url: settings.enableLegacyLogin ? '/login/legacy' : '/login',
  89. json: { email, password: this.password }
  90. },
  91. callback
  92. )
  93. })
  94. })
  95. }
  96. ensureUserExists(callback) {
  97. const filter = { email: this.email }
  98. const options = { upsert: true, new: true, setDefaultsOnInsert: true }
  99. UserModel.findOneAndUpdate(filter, {}, options, (error, user) => {
  100. if (error != null) {
  101. return callback(error)
  102. }
  103. this.setExtraAttributes(user)
  104. AuthenticationManager.setUserPasswordInV2(
  105. user._id,
  106. this.password,
  107. error => {
  108. if (error != null) {
  109. return callback(error)
  110. }
  111. this.mongoUpdate({ $set: { emails: this.emails } }, error => {
  112. if (error != null) {
  113. return callback(error)
  114. }
  115. callback(null, this.password)
  116. })
  117. }
  118. )
  119. })
  120. }
  121. setFeatures(features, callback) {
  122. const update = {}
  123. for (let key in features) {
  124. const value = features[key]
  125. update[`features.${key}`] = value
  126. }
  127. UserModel.update({ _id: this.id }, update, callback)
  128. }
  129. setFeaturesOverride(featuresOverride, callback) {
  130. const update = { $push: { featuresOverrides: featuresOverride } }
  131. UserModel.update({ _id: this.id }, update, callback)
  132. }
  133. setOverleafId(overleafId, callback) {
  134. UserModel.update({ _id: this.id }, { 'overleaf.id': overleafId }, callback)
  135. }
  136. logout(callback) {
  137. this.getCsrfToken(error => {
  138. if (error != null) {
  139. return callback(error)
  140. }
  141. this.request.post(
  142. {
  143. url: '/logout',
  144. json: {
  145. email: this.email,
  146. password: this.password
  147. }
  148. },
  149. (error, response, body) => {
  150. if (error != null) {
  151. return callback(error)
  152. }
  153. db.users.findOne({ email: this.email }, (error, user) => {
  154. if (error != null) {
  155. return callback(error)
  156. }
  157. if (user == null) {
  158. return callback()
  159. }
  160. this.id = user._id.toString()
  161. this._id = user._id.toString()
  162. callback()
  163. })
  164. }
  165. )
  166. })
  167. }
  168. addEmail(email, callback) {
  169. this.emails.push({ email, createdAt: new Date() })
  170. UserUpdater.addEmailAddress(
  171. this.id,
  172. email,
  173. {},
  174. { initiatorId: this._id, ipAddress: '127:0:0:0' },
  175. callback
  176. )
  177. }
  178. confirmEmail(email, callback) {
  179. for (let idx = 0; idx < this.emails.length; idx++) {
  180. const emailData = this.emails[idx]
  181. if (emailData.email === email) {
  182. this.emails[idx].confirmedAt = new Date()
  183. }
  184. }
  185. UserUpdater.confirmEmail(this.id, email, callback)
  186. }
  187. ensureAdmin(callback) {
  188. db.users.update(
  189. { _id: ObjectId(this.id) },
  190. { $set: { isAdmin: true } },
  191. callback
  192. )
  193. }
  194. ensureStaffAccess(flag, callback) {
  195. const update = { $set: {} }
  196. update.$set[`staffAccess.${flag}`] = true
  197. db.users.update({ _id: ObjectId(this.id) }, update, callback)
  198. }
  199. upgradeFeatures(callback) {
  200. const features = {
  201. collaborators: -1, // Infinite
  202. versioning: true,
  203. dropbox: true,
  204. compileTimeout: 60,
  205. compileGroup: 'priority',
  206. templates: true,
  207. references: true,
  208. trackChanges: true,
  209. trackChangesVisible: true
  210. }
  211. db.users.update(
  212. { _id: ObjectId(this.id) },
  213. { $set: { features } },
  214. callback
  215. )
  216. }
  217. downgradeFeatures(callback) {
  218. const features = {
  219. collaborators: 1,
  220. versioning: false,
  221. dropbox: false,
  222. compileTimeout: 60,
  223. compileGroup: 'standard',
  224. templates: false,
  225. references: false,
  226. trackChanges: false,
  227. trackChangesVisible: false
  228. }
  229. db.users.update(
  230. { _id: ObjectId(this.id) },
  231. { $set: { features } },
  232. callback
  233. )
  234. }
  235. defaultFeatures(callback) {
  236. const features = settings.defaultFeatures
  237. db.users.update(
  238. { _id: ObjectId(this.id) },
  239. { $set: { features } },
  240. callback
  241. )
  242. }
  243. getFeatures(callback) {
  244. db.users.findOne(
  245. { _id: ObjectId(this.id) },
  246. { features: 1 },
  247. (error, user) => callback(error, user && user.features)
  248. )
  249. }
  250. fullDeleteUser(email, callback) {
  251. db.users.findOne({ email }, (error, user) => {
  252. if (error != null) {
  253. return callback(error)
  254. }
  255. if (user == null) {
  256. return callback()
  257. }
  258. const userId = user._id
  259. db.projects.remove(
  260. { owner_ref: ObjectId(userId) },
  261. { multi: true },
  262. err => {
  263. if (err != null) {
  264. callback(err)
  265. }
  266. db.users.remove({ _id: ObjectId(userId) }, callback)
  267. }
  268. )
  269. })
  270. }
  271. deleteUser(callback) {
  272. this.getCsrfToken(error => {
  273. if (error) {
  274. return callback(error)
  275. }
  276. this.request.post(
  277. {
  278. url: '/user/delete',
  279. json: { password: this.password }
  280. },
  281. (err, res) => {
  282. if (err) {
  283. return callback(err)
  284. }
  285. if (res.statusCode < 200 || res.statusCode >= 300) {
  286. return callback(
  287. new Error('Error received from API: ' + res.statusCode)
  288. )
  289. }
  290. callback()
  291. }
  292. )
  293. })
  294. }
  295. getProject(projectId, callback) {
  296. db.projects.findOne({ _id: ObjectId(projectId.toString()) }, callback)
  297. }
  298. saveProject(project, callback) {
  299. db.projects.update({ _id: project._id }, project, callback)
  300. }
  301. createProject(name, options, callback) {
  302. if (typeof options === 'function') {
  303. callback = options
  304. options = {}
  305. }
  306. this.request.post(
  307. {
  308. url: '/project/new',
  309. json: Object.assign({ projectName: name }, options)
  310. },
  311. (error, response, body) => {
  312. if (error != null) {
  313. return callback(error)
  314. }
  315. if ((body != null ? body.project_id : undefined) == null) {
  316. error = new Error(
  317. JSON.stringify([
  318. 'SOMETHING WENT WRONG CREATING PROJECT',
  319. name,
  320. options,
  321. response.statusCode,
  322. response.headers['location'],
  323. body
  324. ])
  325. )
  326. callback(error)
  327. } else {
  328. callback(null, body.project_id)
  329. }
  330. }
  331. )
  332. }
  333. deleteProject(projectId, callback) {
  334. this.request.delete(
  335. {
  336. url: `/project/${projectId}`
  337. },
  338. (error, response, body) => {
  339. if (error != null) {
  340. return callback(error)
  341. }
  342. callback(null)
  343. }
  344. )
  345. }
  346. deleteProjects(callback) {
  347. db.projects.remove({ owner_ref: ObjectId(this.id) }, { multi: true }, err =>
  348. callback(err)
  349. )
  350. }
  351. openProject(projectId, callback) {
  352. this.request.get(
  353. {
  354. url: `/project/${projectId}`
  355. },
  356. (error, response, body) => {
  357. if (error != null) {
  358. return callback(error)
  359. }
  360. if (response.statusCode !== 200) {
  361. const err = new Error(
  362. `Non-success response when opening project: ${response.statusCode}`
  363. )
  364. return callback(err)
  365. }
  366. callback(null)
  367. }
  368. )
  369. }
  370. createDocInProject(projectId, parentFolderId, name, callback) {
  371. this.getCsrfToken(error => {
  372. if (error != null) {
  373. return callback(error)
  374. }
  375. this.request.post(
  376. {
  377. url: `/project/${projectId}/doc`,
  378. json: {
  379. name,
  380. parentFolderId
  381. }
  382. },
  383. (error, response, body) => {
  384. if (error != null) {
  385. return callback(error)
  386. }
  387. callback(null, body._id)
  388. }
  389. )
  390. })
  391. }
  392. addUserToProject(projectId, user, privileges, callback) {
  393. let updateOp
  394. if (privileges === 'readAndWrite') {
  395. updateOp = { $addToSet: { collaberator_refs: user._id } }
  396. } else if (privileges === 'readOnly') {
  397. updateOp = { $addToSet: { readOnly_refs: user._id } }
  398. }
  399. db.projects.update({ _id: db.ObjectId(projectId) }, updateOp, err =>
  400. callback(err)
  401. )
  402. }
  403. makePublic(projectId, level, callback) {
  404. this.request.post(
  405. {
  406. url: `/project/${projectId}/settings/admin`,
  407. json: {
  408. publicAccessLevel: level
  409. }
  410. },
  411. (error, response, body) => {
  412. if (error != null) {
  413. return callback(error)
  414. }
  415. callback(null)
  416. }
  417. )
  418. }
  419. makePrivate(projectId, callback) {
  420. this.request.post(
  421. {
  422. url: `/project/${projectId}/settings/admin`,
  423. json: {
  424. publicAccessLevel: 'private'
  425. }
  426. },
  427. (error, response, body) => {
  428. if (error != null) {
  429. return callback(error)
  430. }
  431. callback(null)
  432. }
  433. )
  434. }
  435. makeTokenBased(projectId, callback) {
  436. this.request.post(
  437. {
  438. url: `/project/${projectId}/settings/admin`,
  439. json: {
  440. publicAccessLevel: 'tokenBased'
  441. }
  442. },
  443. (error, response, body) => {
  444. if (error != null) {
  445. return callback(error)
  446. }
  447. callback(null)
  448. }
  449. )
  450. }
  451. getCsrfToken(callback) {
  452. this.request.get(
  453. {
  454. url: '/dev/csrf'
  455. },
  456. (err, response, body) => {
  457. if (err != null) {
  458. return callback(err)
  459. }
  460. this.csrfToken = body
  461. this.request = this.request.defaults({
  462. headers: {
  463. 'x-csrf-token': this.csrfToken
  464. }
  465. })
  466. callback()
  467. }
  468. )
  469. }
  470. changePassword(callback) {
  471. this.getCsrfToken(error => {
  472. if (error != null) {
  473. return callback(error)
  474. }
  475. this.request.post(
  476. {
  477. url: '/user/password/update',
  478. json: {
  479. currentPassword: this.password,
  480. newPassword1: this.password,
  481. newPassword2: this.password
  482. }
  483. },
  484. (error, response, body) => {
  485. if (error != null) {
  486. return callback(error)
  487. }
  488. db.users.findOne({ email: this.email }, (error, user) => {
  489. if (error != null) {
  490. return callback(error)
  491. }
  492. callback()
  493. })
  494. }
  495. )
  496. })
  497. }
  498. reconfirmAccountRequest(userEmail, callback) {
  499. this.getCsrfToken(error => {
  500. if (error != null) {
  501. return callback(error)
  502. }
  503. this.request.post(
  504. {
  505. url: '/user/reconfirm',
  506. json: {
  507. email: userEmail
  508. }
  509. },
  510. (error, response, body) => {
  511. callback(error, response)
  512. }
  513. )
  514. })
  515. }
  516. getUserSettingsPage(callback) {
  517. this.getCsrfToken(error => {
  518. if (error != null) {
  519. return callback(error)
  520. }
  521. this.request.get(
  522. {
  523. url: '/user/settings'
  524. },
  525. (error, response, body) => {
  526. if (error != null) {
  527. return callback(error)
  528. }
  529. callback(null, response.statusCode)
  530. }
  531. )
  532. })
  533. }
  534. activateSudoMode(callback) {
  535. this.getCsrfToken(error => {
  536. if (error != null) {
  537. return callback(error)
  538. }
  539. this.request.post(
  540. {
  541. uri: '/confirm-password',
  542. json: {
  543. password: this.password
  544. }
  545. },
  546. callback
  547. )
  548. })
  549. }
  550. updateSettings(newSettings, callback) {
  551. this.getCsrfToken(error => {
  552. if (error != null) {
  553. return callback(error)
  554. }
  555. this.request.post(
  556. {
  557. url: '/user/settings',
  558. json: newSettings
  559. },
  560. callback
  561. )
  562. })
  563. }
  564. getProjectListPage(callback) {
  565. this.getCsrfToken(error => {
  566. if (error != null) {
  567. return callback(error)
  568. }
  569. this.request.get(
  570. {
  571. url: '/project'
  572. },
  573. (error, response, body) => {
  574. if (error != null) {
  575. return callback(error)
  576. }
  577. callback(null, response.statusCode)
  578. }
  579. )
  580. })
  581. }
  582. isLoggedIn(callback) {
  583. this.request.get('/user/personal_info', (error, response, body) => {
  584. if (error != null) {
  585. return callback(error)
  586. }
  587. if (response.statusCode === 200) {
  588. callback(null, true)
  589. } else if (response.statusCode === 302) {
  590. callback(null, false)
  591. } else {
  592. callback(
  593. new Error(
  594. `unexpected status code from /user/personal_info: ${
  595. response.statusCode
  596. }`
  597. )
  598. )
  599. }
  600. })
  601. }
  602. transferProjectOwnership(projectId, userId, callback) {
  603. this.getCsrfToken(err => {
  604. if (err != null) {
  605. return callback(err)
  606. }
  607. this.request.post(
  608. {
  609. url: `/project/${projectId.toString()}/transfer-ownership`,
  610. json: {
  611. user_id: userId.toString()
  612. }
  613. },
  614. (err, response) => {
  615. if (err != null) {
  616. return callback(err)
  617. }
  618. if (response.statusCode !== 204) {
  619. return callback(
  620. new Error(`Unexpected status code: ${response.statusCode}`)
  621. )
  622. }
  623. callback()
  624. }
  625. )
  626. })
  627. }
  628. setV1Id(v1Id, callback) {
  629. UserModel.update(
  630. {
  631. _id: this._id
  632. },
  633. {
  634. overleaf: {
  635. id: v1Id
  636. }
  637. },
  638. callback
  639. )
  640. }
  641. setCollaboratorInfo(projectId, userId, info, callback) {
  642. this.getCsrfToken(err => {
  643. if (err != null) {
  644. return callback(err)
  645. }
  646. this.request.put(
  647. {
  648. url: `/project/${projectId.toString()}/users/${userId.toString()}`,
  649. json: info
  650. },
  651. (err, response) => {
  652. if (err != null) {
  653. return callback(err)
  654. }
  655. if (response.statusCode !== 204) {
  656. return callback(
  657. new Error(`Unexpected status code: ${response.statusCode}`)
  658. )
  659. }
  660. callback()
  661. }
  662. )
  663. })
  664. }
  665. }
  666. User.promises = class extends User {
  667. doRequest(method, params) {
  668. return new Promise((resolve, reject) => {
  669. this.request[method.toLowerCase()](params, (err, response, body) => {
  670. if (err) {
  671. reject(err)
  672. } else {
  673. resolve({ response, body })
  674. }
  675. })
  676. })
  677. }
  678. }
  679. // promisify User class methods - works for methods with 0-1 output parameters,
  680. // otherwise we will need to implement the method manually instead
  681. const nonPromiseMethods = ['constructor', 'setExtraAttributes']
  682. Object.getOwnPropertyNames(User.prototype).forEach(methodName => {
  683. const method = User.prototype[methodName]
  684. if (typeof method === 'function' && !nonPromiseMethods.includes(methodName)) {
  685. User.promises.prototype[methodName] = promisify(method)
  686. }
  687. })
  688. module.exports = User