UserControllerTests.js 34 KB

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