UserControllerTests.js 33 KB

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