UserControllerTests.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. const sinon = require('sinon')
  2. const { expect } = require('chai')
  3. const modulePath = '../../../../app/src/Features/User/UserController.js'
  4. const SandboxedModule = require('sandboxed-module')
  5. const OError = require('@overleaf/o-error')
  6. const Errors = require('../../../../app/src/Features/Errors/Errors')
  7. describe('UserController', function () {
  8. beforeEach(function () {
  9. this.user_id = '323123'
  10. this.user = {
  11. _id: this.user_id,
  12. email: 'email@overleaf.com',
  13. save: sinon.stub().callsArgWith(0),
  14. ace: {},
  15. }
  16. this.req = {
  17. user: {},
  18. session: {
  19. destroy() {},
  20. user: {
  21. _id: this.user_id,
  22. email: 'old@something.com',
  23. },
  24. },
  25. sessionID: '123',
  26. body: {},
  27. i18n: {
  28. translate: text => text,
  29. },
  30. ip: '0:0:0:0',
  31. query: {},
  32. }
  33. this.UserDeleter = { deleteUser: sinon.stub().yields() }
  34. this.UserGetter = {
  35. getUser: sinon.stub().callsArgWith(1, null, this.user),
  36. promises: { getUser: sinon.stub().resolves(this.user) },
  37. }
  38. this.User = { findById: sinon.stub().callsArgWith(1, null, this.user) }
  39. this.NewsLetterManager = { unsubscribe: sinon.stub().callsArgWith(1) }
  40. this.UserRegistrationHandler = { registerNewUser: sinon.stub() }
  41. this.AuthenticationController = {
  42. establishUserSession: sinon.stub().callsArg(2),
  43. getLoggedInUserId: sinon.stub().returns(this.user._id),
  44. getSessionUser: sinon.stub().returns(this.req.session.user),
  45. setInSessionUser: sinon.stub(),
  46. }
  47. this.AuthenticationManager = {
  48. authenticate: sinon.stub(),
  49. validatePassword: sinon.stub(),
  50. promises: {
  51. authenticate: sinon.stub(),
  52. setUserPassword: sinon.stub(),
  53. },
  54. }
  55. this.UserUpdater = {
  56. changeEmailAddress: sinon.stub(),
  57. promises: {
  58. confirmEmail: sinon.stub().resolves(),
  59. addAffiliationForNewUser: sinon.stub().resolves(),
  60. },
  61. }
  62. this.settings = { siteUrl: 'sharelatex.example.com' }
  63. this.UserHandler = { populateTeamInvites: sinon.stub().callsArgWith(1) }
  64. this.UserSessionsManager = {
  65. trackSession: sinon.stub(),
  66. untrackSession: sinon.stub(),
  67. revokeAllUserSessions: sinon.stub().callsArgWith(2, null),
  68. promises: {
  69. getAllUserSessions: sinon.stub().resolves(),
  70. revokeAllUserSessions: sinon.stub().resolves(),
  71. },
  72. }
  73. this.HttpErrorHandler = {
  74. badRequest: sinon.stub(),
  75. conflict: sinon.stub(),
  76. unprocessableEntity: sinon.stub(),
  77. legacyInternal: sinon.stub(),
  78. }
  79. this.UrlHelper = {
  80. getSafeRedirectPath: sinon.stub(),
  81. }
  82. this.UrlHelper.getSafeRedirectPath
  83. .withArgs('https://evil.com')
  84. .returns(undefined)
  85. this.UrlHelper.getSafeRedirectPath.returnsArg(0)
  86. this.UserController = SandboxedModule.require(modulePath, {
  87. requires: {
  88. '../Helpers/UrlHelper': this.UrlHelper,
  89. './UserGetter': this.UserGetter,
  90. './UserDeleter': this.UserDeleter,
  91. './UserUpdater': this.UserUpdater,
  92. '../../models/User': {
  93. User: this.User,
  94. },
  95. '../Newsletter/NewsletterManager': this.NewsLetterManager,
  96. './UserRegistrationHandler': this.UserRegistrationHandler,
  97. '../Authentication/AuthenticationController': this
  98. .AuthenticationController,
  99. '../Authentication/AuthenticationManager': this.AuthenticationManager,
  100. '../../infrastructure/Features': (this.Features = {
  101. hasFeature: sinon.stub(),
  102. }),
  103. './UserAuditLogHandler': (this.UserAuditLogHandler = {
  104. promises: {
  105. addEntry: sinon.stub().resolves(),
  106. },
  107. }),
  108. './UserHandler': this.UserHandler,
  109. './UserSessionsManager': this.UserSessionsManager,
  110. '../Errors/HttpErrorHandler': this.HttpErrorHandler,
  111. 'settings-sharelatex': this.settings,
  112. '@overleaf/metrics': {
  113. inc() {},
  114. },
  115. '@overleaf/o-error': OError,
  116. '../Email/EmailHandler': (this.EmailHandler = {
  117. sendEmail: sinon.stub(),
  118. promises: { sendEmail: sinon.stub().resolves() },
  119. }),
  120. },
  121. })
  122. this.res = {
  123. send: sinon.stub(),
  124. status: sinon.stub(),
  125. sendStatus: sinon.stub(),
  126. json: sinon.stub(),
  127. }
  128. this.res.status.returns(this.res)
  129. this.next = sinon.stub()
  130. this.callback = sinon.stub()
  131. })
  132. describe('tryDeleteUser', function () {
  133. beforeEach(function () {
  134. this.req.body.password = 'wat'
  135. this.req.logout = sinon.stub()
  136. this.req.session.destroy = sinon.stub().callsArgWith(0, null)
  137. this.AuthenticationController.getLoggedInUserId = sinon
  138. .stub()
  139. .returns(this.user._id)
  140. this.AuthenticationManager.authenticate = sinon
  141. .stub()
  142. .callsArgWith(2, null, this.user)
  143. })
  144. it('should send 200', function (done) {
  145. this.res.sendStatus = code => {
  146. code.should.equal(200)
  147. done()
  148. }
  149. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  150. })
  151. it('should try to authenticate user', function (done) {
  152. this.res.sendStatus = code => {
  153. this.AuthenticationManager.authenticate.callCount.should.equal(1)
  154. this.AuthenticationManager.authenticate
  155. .calledWith({ _id: this.user._id }, this.req.body.password)
  156. .should.equal(true)
  157. done()
  158. }
  159. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  160. })
  161. it('should delete the user', function (done) {
  162. this.res.sendStatus = code => {
  163. this.UserDeleter.deleteUser.callCount.should.equal(1)
  164. this.UserDeleter.deleteUser.calledWith(this.user._id).should.equal(true)
  165. done()
  166. }
  167. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  168. })
  169. describe('when no password is supplied', function () {
  170. beforeEach(function () {
  171. this.req.body.password = ''
  172. })
  173. it('should return 403', function (done) {
  174. this.res.sendStatus = code => {
  175. code.should.equal(403)
  176. done()
  177. }
  178. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  179. })
  180. })
  181. describe('when authenticate produces an error', function () {
  182. beforeEach(function () {
  183. this.AuthenticationManager.authenticate = sinon
  184. .stub()
  185. .callsArgWith(2, new Error('woops'))
  186. })
  187. it('should call next with an error', function (done) {
  188. this.next = err => {
  189. expect(err).to.not.equal(null)
  190. expect(err).to.be.instanceof(Error)
  191. done()
  192. }
  193. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  194. })
  195. })
  196. describe('when authenticate does not produce a user', function () {
  197. beforeEach(function () {
  198. this.AuthenticationManager.authenticate = sinon
  199. .stub()
  200. .callsArgWith(2, null, null)
  201. })
  202. it('should return 403', function (done) {
  203. this.res.sendStatus = code => {
  204. code.should.equal(403)
  205. done()
  206. }
  207. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  208. })
  209. })
  210. describe('when deleteUser produces an error', function () {
  211. beforeEach(function () {
  212. this.UserDeleter.deleteUser = sinon.stub().yields(new Error('woops'))
  213. })
  214. it('should call next with an error', function (done) {
  215. this.next = err => {
  216. expect(err).to.not.equal(null)
  217. expect(err).to.be.instanceof(Error)
  218. done()
  219. }
  220. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  221. })
  222. })
  223. describe('when deleteUser produces a known error', function () {
  224. beforeEach(function () {
  225. this.UserDeleter.deleteUser = sinon
  226. .stub()
  227. .yields(new Errors.SubscriptionAdminDeletionError())
  228. })
  229. it('should return a HTTP Unprocessable Entity error', function (done) {
  230. this.HttpErrorHandler.unprocessableEntity = sinon.spy(
  231. (req, res, message, info) => {
  232. expect(req).to.exist
  233. expect(res).to.exist
  234. expect(message).to.equal('error while deleting user account')
  235. expect(info).to.deep.equal({
  236. error: 'SubscriptionAdminDeletionError',
  237. })
  238. done()
  239. }
  240. )
  241. this.UserController.tryDeleteUser(this.req, this.res)
  242. })
  243. })
  244. describe('when session.destroy produces an error', function () {
  245. beforeEach(function () {
  246. this.req.session.destroy = sinon
  247. .stub()
  248. .callsArgWith(0, new Error('woops'))
  249. })
  250. it('should call next with an error', function (done) {
  251. this.next = err => {
  252. expect(err).to.not.equal(null)
  253. expect(err).to.be.instanceof(Error)
  254. done()
  255. }
  256. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  257. })
  258. })
  259. })
  260. describe('unsubscribe', function () {
  261. it('should send the user to unsubscribe', function (done) {
  262. this.res.sendStatus = () => {
  263. this.NewsLetterManager.unsubscribe
  264. .calledWith(this.user)
  265. .should.equal(true)
  266. done()
  267. }
  268. this.UserController.unsubscribe(this.req, this.res)
  269. })
  270. })
  271. describe('updateUserSettings', function () {
  272. beforeEach(function () {
  273. this.auditLog = { initiatorId: this.user_id, ipAddress: this.req.ip }
  274. this.newEmail = 'hello@world.com'
  275. this.req.externalAuthenticationSystemUsed = sinon.stub().returns(false)
  276. })
  277. it('should call save', function (done) {
  278. this.req.body = {}
  279. this.res.sendStatus = code => {
  280. this.user.save.called.should.equal(true)
  281. done()
  282. }
  283. this.UserController.updateUserSettings(this.req, this.res)
  284. })
  285. it('should set the first name', function (done) {
  286. this.req.body = { first_name: 'bobby ' }
  287. this.res.sendStatus = code => {
  288. this.user.first_name.should.equal('bobby')
  289. done()
  290. }
  291. this.UserController.updateUserSettings(this.req, this.res)
  292. })
  293. it('should set the role', function (done) {
  294. this.req.body = { role: 'student' }
  295. this.res.sendStatus = code => {
  296. this.user.role.should.equal('student')
  297. done()
  298. }
  299. this.UserController.updateUserSettings(this.req, this.res)
  300. })
  301. it('should set the institution', function (done) {
  302. this.req.body = { institution: 'MIT' }
  303. this.res.sendStatus = code => {
  304. this.user.institution.should.equal('MIT')
  305. done()
  306. }
  307. this.UserController.updateUserSettings(this.req, this.res)
  308. })
  309. it('should set some props on ace', function (done) {
  310. this.req.body = { editorTheme: 'something' }
  311. this.res.sendStatus = code => {
  312. this.user.ace.theme.should.equal('something')
  313. done()
  314. }
  315. this.UserController.updateUserSettings(this.req, this.res)
  316. })
  317. it('should set the overall theme', function (done) {
  318. this.req.body = { overallTheme: 'green-ish' }
  319. this.res.sendStatus = code => {
  320. this.user.ace.overallTheme.should.equal('green-ish')
  321. done()
  322. }
  323. this.UserController.updateUserSettings(this.req, this.res)
  324. })
  325. it('should send an error if the email is 0 len', function (done) {
  326. this.req.body.email = ''
  327. this.res.sendStatus = function (code) {
  328. code.should.equal(400)
  329. done()
  330. }
  331. this.UserController.updateUserSettings(this.req, this.res)
  332. })
  333. it('should send an error if the email does not contain an @', function (done) {
  334. this.req.body.email = 'bob at something dot com'
  335. this.res.sendStatus = function (code) {
  336. code.should.equal(400)
  337. done()
  338. }
  339. this.UserController.updateUserSettings(this.req, this.res)
  340. })
  341. it('should call the user updater with the new email and user _id', function (done) {
  342. this.req.body.email = this.newEmail.toUpperCase()
  343. this.UserUpdater.changeEmailAddress.callsArgWith(3)
  344. this.res.sendStatus = code => {
  345. code.should.equal(200)
  346. this.UserUpdater.changeEmailAddress
  347. .calledWith(this.user_id, this.newEmail, this.auditLog)
  348. .should.equal(true)
  349. done()
  350. }
  351. this.UserController.updateUserSettings(this.req, this.res)
  352. })
  353. it('should update the email on the session', function (done) {
  354. this.req.body.email = this.newEmail.toUpperCase()
  355. this.UserUpdater.changeEmailAddress.callsArgWith(3)
  356. let callcount = 0
  357. this.User.findById = (id, cb) => {
  358. if (++callcount === 2) {
  359. this.user.email = this.newEmail
  360. }
  361. cb(null, this.user)
  362. }
  363. this.res.sendStatus = code => {
  364. code.should.equal(200)
  365. this.AuthenticationController.setInSessionUser
  366. .calledWith(this.req, {
  367. email: this.newEmail,
  368. first_name: undefined,
  369. last_name: undefined,
  370. })
  371. .should.equal(true)
  372. done()
  373. }
  374. this.UserController.updateUserSettings(this.req, this.res)
  375. })
  376. it('should call populateTeamInvites', function (done) {
  377. this.req.body.email = this.newEmail.toUpperCase()
  378. this.UserUpdater.changeEmailAddress.callsArgWith(3)
  379. this.res.sendStatus = code => {
  380. code.should.equal(200)
  381. this.UserHandler.populateTeamInvites
  382. .calledWith(this.user)
  383. .should.equal(true)
  384. done()
  385. }
  386. this.UserController.updateUserSettings(this.req, this.res)
  387. })
  388. describe('when changeEmailAddress yields an error', function () {
  389. it('should pass on an error and not send a success status', function (done) {
  390. this.req.body.email = this.newEmail.toUpperCase()
  391. this.UserUpdater.changeEmailAddress.callsArgWith(3, new OError())
  392. this.HttpErrorHandler.legacyInternal = sinon.spy(
  393. (req, res, message, error) => {
  394. expect(req).to.exist
  395. expect(req).to.exist
  396. message.should.equal('problem_changing_email_address')
  397. expect(error).to.be.instanceof(OError)
  398. done()
  399. }
  400. )
  401. this.UserController.updateUserSettings(this.req, this.res, this.next)
  402. })
  403. it('should call the HTTP conflict error handler when the email already exists', function (done) {
  404. this.HttpErrorHandler.conflict = sinon.spy((req, res, message) => {
  405. expect(req).to.exist
  406. expect(req).to.exist
  407. message.should.equal('email_already_registered')
  408. done()
  409. })
  410. this.req.body.email = this.newEmail.toUpperCase()
  411. this.UserUpdater.changeEmailAddress.callsArgWith(
  412. 3,
  413. new Errors.EmailExistsError()
  414. )
  415. this.UserController.updateUserSettings(this.req, this.res)
  416. })
  417. })
  418. describe('when using an external auth source', function () {
  419. beforeEach(function () {
  420. this.UserUpdater.changeEmailAddress.callsArgWith(2)
  421. this.newEmail = 'someone23@example.com'
  422. this.req.externalAuthenticationSystemUsed = sinon.stub().returns(true)
  423. })
  424. it('should not set a new email', function (done) {
  425. this.req.body.email = this.newEmail
  426. this.res.sendStatus = code => {
  427. code.should.equal(200)
  428. this.UserUpdater.changeEmailAddress
  429. .calledWith(this.user_id, this.newEmail)
  430. .should.equal(false)
  431. done()
  432. }
  433. this.UserController.updateUserSettings(this.req, this.res)
  434. })
  435. })
  436. })
  437. describe('logout', function () {
  438. it('should destroy the session', function (done) {
  439. this.req.session.destroy = sinon.stub().callsArgWith(0)
  440. this.res.redirect = url => {
  441. url.should.equal('/login')
  442. this.req.session.destroy.called.should.equal(true)
  443. done()
  444. }
  445. this.UserController.logout(this.req, this.res)
  446. })
  447. it('should untrack session', function (done) {
  448. this.req.session.destroy = sinon.stub().callsArgWith(0)
  449. this.res.redirect = url => {
  450. url.should.equal('/login')
  451. this.UserSessionsManager.untrackSession.callCount.should.equal(1)
  452. this.UserSessionsManager.untrackSession
  453. .calledWith(sinon.match(this.req.user), this.req.sessionID)
  454. .should.equal(true)
  455. done()
  456. }
  457. this.UserController.logout(this.req, this.res)
  458. })
  459. it('should redirect after logout', function (done) {
  460. this.req.body.redirect = '/institutional-login'
  461. this.req.session.destroy = sinon.stub().callsArgWith(0)
  462. this.res.redirect = url => {
  463. url.should.equal(this.req.body.redirect)
  464. done()
  465. }
  466. this.UserController.logout(this.req, this.res)
  467. })
  468. it('should redirect after logout, but not to evil.com', function (done) {
  469. this.req.body.redirect = 'https://evil.com'
  470. this.req.session.destroy = sinon.stub().callsArgWith(0)
  471. this.res.redirect = url => {
  472. url.should.equal('/login')
  473. done()
  474. }
  475. this.UserController.logout(this.req, this.res)
  476. })
  477. it('should redirect to login after logout when no redirect set', function (done) {
  478. this.req.session.destroy = sinon.stub().callsArgWith(0)
  479. this.res.redirect = url => {
  480. url.should.equal('/login')
  481. done()
  482. }
  483. this.UserController.logout(this.req, this.res)
  484. })
  485. })
  486. describe('register', function () {
  487. beforeEach(function () {
  488. this.UserRegistrationHandler.registerNewUserAndSendActivationEmail = sinon
  489. .stub()
  490. .callsArgWith(1, null, this.user, (this.url = 'mock/url'))
  491. this.req.body.email = this.user.email = this.email = 'email@example.com'
  492. this.UserController.register(this.req, this.res)
  493. })
  494. it('should register the user and send them an email', function () {
  495. this.UserRegistrationHandler.registerNewUserAndSendActivationEmail
  496. .calledWith(this.email)
  497. .should.equal(true)
  498. })
  499. it('should return the user and activation url', function () {
  500. this.res.json
  501. .calledWith({
  502. email: this.email,
  503. setNewPasswordUrl: this.url,
  504. })
  505. .should.equal(true)
  506. })
  507. })
  508. describe('clearSessions', function () {
  509. describe('success', function () {
  510. it('should call revokeAllUserSessions', function (done) {
  511. this.res.sendStatus.callsFake(() => {
  512. this.UserSessionsManager.promises.revokeAllUserSessions.callCount.should.equal(
  513. 1
  514. )
  515. done()
  516. })
  517. this.UserController.clearSessions(this.req, this.res)
  518. })
  519. it('send a 201 response', function (done) {
  520. this.res.sendStatus.callsFake(status => {
  521. status.should.equal(201)
  522. done()
  523. })
  524. this.UserController.clearSessions(this.req, this.res)
  525. })
  526. it('sends a security alert email', function (done) {
  527. this.res.sendStatus.callsFake(status => {
  528. this.EmailHandler.promises.sendEmail.callCount.should.equal(1)
  529. const expectedArg = {
  530. to: this.user.email,
  531. actionDescribed: `active sessions were cleared on your account ${this.user.email}`,
  532. action: 'active sessions cleared',
  533. }
  534. const emailCall = this.EmailHandler.promises.sendEmail.lastCall
  535. expect(emailCall.args[0]).to.equal('securityAlert')
  536. expect(emailCall.args[1]).to.deep.equal(expectedArg)
  537. done()
  538. })
  539. this.UserController.clearSessions(this.req, this.res)
  540. })
  541. })
  542. describe('errors', function () {
  543. describe('when getAllUserSessions produces an error', function () {
  544. it('should return an error', function (done) {
  545. this.UserSessionsManager.promises.getAllUserSessions.rejects(
  546. new Error('woops')
  547. )
  548. this.UserController.clearSessions(this.req, this.res, error => {
  549. expect(error).to.be.instanceof(Error)
  550. done()
  551. })
  552. })
  553. })
  554. describe('when audit log addEntry produces an error', function () {
  555. it('should call next with an error', function (done) {
  556. this.UserAuditLogHandler.promises.addEntry.rejects(new Error('woops'))
  557. this.UserController.clearSessions(this.req, this.res, error => {
  558. expect(error).to.be.instanceof(Error)
  559. done()
  560. })
  561. })
  562. })
  563. describe('when revokeAllUserSessions produces an error', function () {
  564. it('should call next with an error', function (done) {
  565. this.UserSessionsManager.promises.revokeAllUserSessions.rejects(
  566. new Error('woops')
  567. )
  568. this.UserController.clearSessions(this.req, this.res, error => {
  569. expect(error).to.be.instanceof(Error)
  570. done()
  571. })
  572. })
  573. })
  574. describe('when EmailHandler produces an error', function () {
  575. const anError = new Error('oops')
  576. it('send a 201 response but log error', function (done) {
  577. this.EmailHandler.promises.sendEmail.rejects(anError)
  578. this.res.sendStatus.callsFake(status => {
  579. status.should.equal(201)
  580. this.logger.error.callCount.should.equal(1)
  581. const loggerCall = this.logger.error.getCall(0)
  582. expect(loggerCall.args[0]).to.deep.equal({
  583. error: anError,
  584. userId: this.user_id,
  585. })
  586. expect(loggerCall.args[1]).to.contain(
  587. 'could not send security alert email when sessions cleared'
  588. )
  589. done()
  590. })
  591. this.UserController.clearSessions(this.req, this.res)
  592. })
  593. })
  594. })
  595. })
  596. describe('changePassword', function () {
  597. describe('success', function () {
  598. beforeEach(function () {
  599. this.AuthenticationManager.promises.authenticate.resolves(this.user)
  600. this.AuthenticationManager.promises.setUserPassword.resolves()
  601. this.req.body = {
  602. newPassword1: 'newpass',
  603. newPassword2: 'newpass',
  604. }
  605. })
  606. it('should set the new password if they do match', function (done) {
  607. this.res.json.callsFake(() => {
  608. this.AuthenticationManager.promises.setUserPassword.should.have.been.calledWith(
  609. this.user,
  610. 'newpass'
  611. )
  612. done()
  613. })
  614. this.UserController.changePassword(this.req, this.res)
  615. })
  616. it('should log the update', function (done) {
  617. this.res.json.callsFake(() => {
  618. this.UserAuditLogHandler.promises.addEntry.should.have.been.calledWith(
  619. this.user._id,
  620. 'update-password',
  621. this.user._id,
  622. this.req.ip
  623. )
  624. this.AuthenticationManager.promises.setUserPassword.callCount.should.equal(
  625. 1
  626. )
  627. done()
  628. })
  629. this.UserController.changePassword(this.req, this.res)
  630. })
  631. it('should send security alert email', function (done) {
  632. this.res.json.callsFake(() => {
  633. const expectedArg = {
  634. to: this.user.email,
  635. actionDescribed: `your password has been changed on your account ${this.user.email}`,
  636. action: 'password changed',
  637. }
  638. const emailCall = this.EmailHandler.sendEmail.lastCall
  639. expect(emailCall.args[0]).to.equal('securityAlert')
  640. expect(emailCall.args[1]).to.deep.equal(expectedArg)
  641. done()
  642. })
  643. this.UserController.changePassword(this.req, this.res)
  644. })
  645. })
  646. describe('errors', function () {
  647. it('should check the old password is the current one at the moment', function (done) {
  648. this.AuthenticationManager.promises.authenticate.resolves()
  649. this.req.body = { currentPassword: 'oldpasshere' }
  650. this.HttpErrorHandler.badRequest.callsFake(() => {
  651. expect(this.HttpErrorHandler.badRequest).to.have.been.calledWith(
  652. this.req,
  653. this.res,
  654. 'Your old password is wrong'
  655. )
  656. this.AuthenticationManager.promises.authenticate.should.have.been.calledWith(
  657. { _id: this.user._id },
  658. 'oldpasshere'
  659. )
  660. this.AuthenticationManager.promises.setUserPassword.callCount.should.equal(
  661. 0
  662. )
  663. done()
  664. })
  665. this.UserController.changePassword(this.req, this.res)
  666. })
  667. it('it should not set the new password if they do not match', function (done) {
  668. this.AuthenticationManager.promises.authenticate.resolves({})
  669. this.req.body = {
  670. newPassword1: '1',
  671. newPassword2: '2',
  672. }
  673. this.HttpErrorHandler.badRequest.callsFake(() => {
  674. expect(this.HttpErrorHandler.badRequest).to.have.been.calledWith(
  675. this.req,
  676. this.res,
  677. 'password_change_passwords_do_not_match'
  678. )
  679. this.AuthenticationManager.promises.setUserPassword.callCount.should.equal(
  680. 0
  681. )
  682. done()
  683. })
  684. this.UserController.changePassword(this.req, this.res)
  685. })
  686. it('it should not set the new password if it is invalid', function (done) {
  687. // this.AuthenticationManager.validatePassword = sinon
  688. // .stub()
  689. // .returns({ message: 'validation-error' })
  690. const err = new Error('bad')
  691. err.name = 'InvalidPasswordError'
  692. this.AuthenticationManager.promises.setUserPassword.rejects(err)
  693. this.AuthenticationManager.promises.authenticate.resolves({})
  694. this.req.body = {
  695. newPassword1: 'newpass',
  696. newPassword2: 'newpass',
  697. }
  698. this.HttpErrorHandler.badRequest.callsFake(() => {
  699. expect(this.HttpErrorHandler.badRequest).to.have.been.calledWith(
  700. this.req,
  701. this.res,
  702. err.message
  703. )
  704. this.AuthenticationManager.promises.setUserPassword.callCount.should.equal(
  705. 1
  706. )
  707. done()
  708. })
  709. this.UserController.changePassword(this.req, this.res)
  710. })
  711. describe('UserAuditLogHandler error', function () {
  712. it('should return error and not update password', function (done) {
  713. this.UserAuditLogHandler.promises.addEntry.rejects(new Error('oops'))
  714. this.AuthenticationManager.promises.authenticate.resolves(this.user)
  715. this.AuthenticationManager.promises.setUserPassword.resolves()
  716. this.req.body = {
  717. newPassword1: 'newpass',
  718. newPassword2: 'newpass',
  719. }
  720. this.UserController.changePassword(this.req, this.res, error => {
  721. expect(error).to.be.instanceof(Error)
  722. this.AuthenticationManager.promises.setUserPassword.callCount.should.equal(
  723. 1
  724. )
  725. done()
  726. })
  727. })
  728. })
  729. describe('EmailHandler error', function () {
  730. const anError = new Error('oops')
  731. beforeEach(function () {
  732. this.AuthenticationManager.promises.authenticate.resolves(this.user)
  733. this.AuthenticationManager.promises.setUserPassword.resolves()
  734. this.req.body = {
  735. newPassword1: 'newpass',
  736. newPassword2: 'newpass',
  737. }
  738. this.EmailHandler.sendEmail.yields(anError)
  739. })
  740. it('should not return error but should log it', function (done) {
  741. this.res.json.callsFake(result => {
  742. expect(result.message.type).to.equal('success')
  743. this.logger.error.callCount.should.equal(1)
  744. expect(this.logger.error).to.have.been.calledWithExactly(
  745. {
  746. error: anError,
  747. userId: this.user_id,
  748. },
  749. 'could not send security alert email when password changed'
  750. )
  751. done()
  752. })
  753. this.UserController.changePassword(this.req, this.res)
  754. })
  755. })
  756. })
  757. })
  758. describe('ensureAffiliationMiddleware', function () {
  759. describe('without affiliations feature', function () {
  760. beforeEach(async function () {
  761. await this.UserController.promises.ensureAffiliationMiddleware(
  762. this.req,
  763. this.res,
  764. this.next
  765. )
  766. })
  767. it('should not run affiliation check', function () {
  768. expect(this.UserGetter.promises.getUser).to.not.have.been.called
  769. expect(this.UserUpdater.promises.confirmEmail).to.not.have.been.called
  770. expect(this.UserUpdater.promises.addAffiliationForNewUser).to.not.have
  771. .been.called
  772. })
  773. it('should not return an error', function () {
  774. expect(this.next).to.be.calledWith()
  775. })
  776. })
  777. describe('without ensureAffiliation query parameter', function () {
  778. beforeEach(async function () {
  779. this.Features.hasFeature.withArgs('affiliations').returns(true)
  780. await this.UserController.promises.ensureAffiliationMiddleware(
  781. this.req,
  782. this.res,
  783. this.next
  784. )
  785. })
  786. it('should not run middleware', function () {
  787. expect(this.UserGetter.promises.getUser).to.not.have.been.called
  788. expect(this.UserUpdater.promises.confirmEmail).to.not.have.been.called
  789. expect(this.UserUpdater.promises.addAffiliationForNewUser).to.not.have
  790. .been.called
  791. })
  792. it('should not return an error', function () {
  793. expect(this.next).to.be.calledWith()
  794. })
  795. })
  796. describe('no flagged email', function () {
  797. beforeEach(async function () {
  798. const email = 'unit-test@overleaf.com'
  799. this.user.email = email
  800. this.user.emails = [
  801. {
  802. email,
  803. },
  804. ]
  805. this.Features.hasFeature.withArgs('affiliations').returns(true)
  806. this.req.query.ensureAffiliation = true
  807. await this.UserController.promises.ensureAffiliationMiddleware(
  808. this.req,
  809. this.res,
  810. this.next
  811. )
  812. })
  813. it('should get the user', function () {
  814. expect(this.UserGetter.promises.getUser).to.have.been.calledWith(
  815. this.user._id
  816. )
  817. })
  818. it('should not try to add affiliation or update user', function () {
  819. expect(this.UserUpdater.promises.addAffiliationForNewUser).to.not.have
  820. .been.called
  821. })
  822. it('should not return an error', function () {
  823. expect(this.next).to.be.calledWith()
  824. })
  825. })
  826. describe('flagged non-SSO email', function () {
  827. let emailFlagged
  828. beforeEach(async function () {
  829. emailFlagged = 'flagged@overleaf.com'
  830. this.user.email = emailFlagged
  831. this.user.emails = [
  832. {
  833. email: emailFlagged,
  834. affiliationUnchecked: true,
  835. },
  836. ]
  837. this.Features.hasFeature.withArgs('affiliations').returns(true)
  838. this.req.query.ensureAffiliation = true
  839. await this.UserController.promises.ensureAffiliationMiddleware(
  840. this.req,
  841. this.res,
  842. this.next
  843. )
  844. })
  845. it('should unflag the emails but not confirm', function () {
  846. expect(
  847. this.UserUpdater.promises.addAffiliationForNewUser
  848. ).to.have.been.calledWith(this.user._id, emailFlagged)
  849. expect(
  850. this.UserUpdater.promises.confirmEmail
  851. ).to.not.have.been.calledWith(this.user._id, emailFlagged)
  852. })
  853. it('should not return an error', function () {
  854. expect(this.next).to.be.calledWith()
  855. })
  856. })
  857. describe('flagged SSO email', function () {
  858. let emailFlagged
  859. beforeEach(async function () {
  860. emailFlagged = 'flagged@overleaf.com'
  861. this.user.email = emailFlagged
  862. this.user.emails = [
  863. {
  864. email: emailFlagged,
  865. affiliationUnchecked: true,
  866. samlProviderId: '123',
  867. },
  868. ]
  869. this.Features.hasFeature.withArgs('affiliations').returns(true)
  870. this.req.query.ensureAffiliation = true
  871. await this.UserController.promises.ensureAffiliationMiddleware(
  872. this.req,
  873. this.res,
  874. this.next
  875. )
  876. })
  877. it('should add affiliation to v1, unflag and confirm on v2', function () {
  878. expect(this.UserUpdater.promises.addAffiliationForNewUser).to.have.not
  879. .been.called
  880. expect(this.UserUpdater.promises.confirmEmail).to.have.been.calledWith(
  881. this.user._id,
  882. emailFlagged
  883. )
  884. })
  885. it('should not return an error', function () {
  886. expect(this.next).to.be.calledWith()
  887. })
  888. })
  889. describe('when v1 returns an error', function () {
  890. let emailFlagged
  891. beforeEach(async function () {
  892. this.UserUpdater.promises.addAffiliationForNewUser.rejects()
  893. emailFlagged = 'flagged@overleaf.com'
  894. this.user.email = emailFlagged
  895. this.user.emails = [
  896. {
  897. email: emailFlagged,
  898. affiliationUnchecked: true,
  899. },
  900. ]
  901. this.Features.hasFeature.withArgs('affiliations').returns(true)
  902. this.req.query.ensureAffiliation = true
  903. await this.UserController.promises.ensureAffiliationMiddleware(
  904. this.req,
  905. this.res,
  906. this.next
  907. )
  908. })
  909. it('should return the error', function () {
  910. expect(this.next).to.be.calledWith(sinon.match.instanceOf(Error))
  911. })
  912. })
  913. })
  914. })