UserControllerTests.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  1. const sinon = require('sinon')
  2. const chai = require('chai')
  3. const { expect } = chai
  4. const modulePath = '../../../../app/src/Features/User/UserController.js'
  5. const SandboxedModule = require('sandboxed-module')
  6. const OError = require('@overleaf/o-error')
  7. const Errors = require('../../../../app/src/Features/Errors/Errors')
  8. describe('UserController', function() {
  9. beforeEach(function() {
  10. this.user_id = '323123'
  11. this.user = {
  12. _id: this.user_id,
  13. email: 'email@overleaf.com',
  14. save: sinon.stub().callsArgWith(0),
  15. ace: {}
  16. }
  17. this.req = {
  18. user: {},
  19. session: {
  20. destroy() {},
  21. user: {
  22. _id: this.user_id,
  23. email: 'old@something.com'
  24. }
  25. },
  26. sessionID: '123',
  27. body: {},
  28. i18n: {
  29. translate: text => text
  30. },
  31. ip: '0:0:0:0',
  32. query: {}
  33. }
  34. this.UserDeleter = { deleteUser: sinon.stub().yields() }
  35. this.UserGetter = {
  36. getUser: sinon.stub().callsArgWith(1, null, this.user),
  37. promises: { getUser: sinon.stub().resolves(this.user) }
  38. }
  39. this.User = { findById: sinon.stub().callsArgWith(1, null, this.user) }
  40. this.NewsLetterManager = { unsubscribe: sinon.stub().callsArgWith(1) }
  41. this.UserRegistrationHandler = { registerNewUser: sinon.stub() }
  42. this.AuthenticationController = {
  43. establishUserSession: sinon.stub().callsArg(2),
  44. getLoggedInUserId: sinon.stub().returns(this.user._id),
  45. getSessionUser: sinon.stub().returns(this.req.session.user),
  46. setInSessionUser: sinon.stub()
  47. }
  48. this.AuthenticationManager = {
  49. authenticate: sinon.stub(),
  50. validatePassword: sinon.stub(),
  51. promises: {
  52. authenticate: sinon.stub(),
  53. setUserPassword: sinon.stub()
  54. }
  55. }
  56. this.ReferalAllocator = { allocate: sinon.stub() }
  57. this.SubscriptionDomainHandler = { autoAllocate: sinon.stub() }
  58. this.UserUpdater = {
  59. changeEmailAddress: sinon.stub(),
  60. promises: {
  61. confirmEmail: sinon.stub().resolves(),
  62. addAffiliationForNewUser: sinon.stub().resolves()
  63. }
  64. }
  65. this.settings = { siteUrl: 'sharelatex.example.com' }
  66. this.UserHandler = { populateTeamInvites: sinon.stub().callsArgWith(1) }
  67. this.UserSessionsManager = {
  68. trackSession: sinon.stub(),
  69. untrackSession: sinon.stub(),
  70. revokeAllUserSessions: sinon.stub().callsArgWith(2, null),
  71. promises: {
  72. getAllUserSessions: sinon.stub().resolves(),
  73. revokeAllUserSessions: sinon.stub().resolves()
  74. }
  75. }
  76. this.HttpErrorHandler = {
  77. badRequest: sinon.stub(),
  78. conflict: sinon.stub(),
  79. unprocessableEntity: sinon.stub(),
  80. legacyInternal: sinon.stub()
  81. }
  82. this.UserController = SandboxedModule.require(modulePath, {
  83. globals: {
  84. console: console
  85. },
  86. requires: {
  87. './UserGetter': this.UserGetter,
  88. './UserDeleter': this.UserDeleter,
  89. './UserUpdater': this.UserUpdater,
  90. '../../models/User': {
  91. User: this.User
  92. },
  93. '../Newsletter/NewsletterManager': this.NewsLetterManager,
  94. './UserRegistrationHandler': this.UserRegistrationHandler,
  95. '../Authentication/AuthenticationController': this
  96. .AuthenticationController,
  97. '../Authentication/AuthenticationManager': this.AuthenticationManager,
  98. '../../infrastructure/Features': (this.Features = {
  99. hasFeature: sinon.stub()
  100. }),
  101. '../Referal/ReferalAllocator': this.ReferalAllocator,
  102. '../Subscription/SubscriptionDomainHandler': this
  103. .SubscriptionDomainHandler,
  104. './UserAuditLogHandler': (this.UserAuditLogHandler = {
  105. promises: {
  106. addEntry: sinon.stub().resolves()
  107. }
  108. }),
  109. './UserHandler': this.UserHandler,
  110. './UserSessionsManager': this.UserSessionsManager,
  111. '../Errors/HttpErrorHandler': this.HttpErrorHandler,
  112. 'settings-sharelatex': this.settings,
  113. 'logger-sharelatex': (this.logger = {
  114. log() {},
  115. warn() {},
  116. err() {},
  117. error: sinon.stub()
  118. }),
  119. '@overleaf/metrics': {
  120. inc() {}
  121. },
  122. '../Errors/Errors': Errors,
  123. '@overleaf/o-error': OError,
  124. '../Email/EmailHandler': (this.EmailHandler = {
  125. sendEmail: sinon.stub(),
  126. promises: { sendEmail: sinon.stub().resolves() }
  127. })
  128. }
  129. })
  130. this.res = {
  131. send: sinon.stub(),
  132. status: sinon.stub(),
  133. sendStatus: sinon.stub(),
  134. json: sinon.stub()
  135. }
  136. this.res.status.returns(this.res)
  137. this.next = sinon.stub()
  138. this.callback = sinon.stub()
  139. })
  140. describe('tryDeleteUser', function() {
  141. beforeEach(function() {
  142. this.req.body.password = 'wat'
  143. this.req.logout = sinon.stub()
  144. this.req.session.destroy = sinon.stub().callsArgWith(0, null)
  145. this.AuthenticationController.getLoggedInUserId = sinon
  146. .stub()
  147. .returns(this.user._id)
  148. this.AuthenticationManager.authenticate = sinon
  149. .stub()
  150. .callsArgWith(2, null, this.user)
  151. })
  152. it('should send 200', function(done) {
  153. this.res.sendStatus = code => {
  154. code.should.equal(200)
  155. done()
  156. }
  157. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  158. })
  159. it('should try to authenticate user', function(done) {
  160. this.res.sendStatus = code => {
  161. this.AuthenticationManager.authenticate.callCount.should.equal(1)
  162. this.AuthenticationManager.authenticate
  163. .calledWith({ _id: this.user._id }, this.req.body.password)
  164. .should.equal(true)
  165. done()
  166. }
  167. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  168. })
  169. it('should delete the user', function(done) {
  170. this.res.sendStatus = code => {
  171. this.UserDeleter.deleteUser.callCount.should.equal(1)
  172. this.UserDeleter.deleteUser.calledWith(this.user._id).should.equal(true)
  173. done()
  174. }
  175. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  176. })
  177. describe('when no password is supplied', function() {
  178. beforeEach(function() {
  179. this.req.body.password = ''
  180. })
  181. it('should return 403', function(done) {
  182. this.res.sendStatus = code => {
  183. code.should.equal(403)
  184. done()
  185. }
  186. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  187. })
  188. })
  189. describe('when authenticate produces an error', function() {
  190. beforeEach(function() {
  191. this.AuthenticationManager.authenticate = sinon
  192. .stub()
  193. .callsArgWith(2, new Error('woops'))
  194. })
  195. it('should call next with an error', function(done) {
  196. this.next = err => {
  197. expect(err).to.not.equal(null)
  198. expect(err).to.be.instanceof(Error)
  199. done()
  200. }
  201. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  202. })
  203. })
  204. describe('when authenticate does not produce a user', function() {
  205. beforeEach(function() {
  206. this.AuthenticationManager.authenticate = sinon
  207. .stub()
  208. .callsArgWith(2, null, null)
  209. })
  210. it('should return 403', function(done) {
  211. this.res.sendStatus = code => {
  212. code.should.equal(403)
  213. done()
  214. }
  215. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  216. })
  217. })
  218. describe('when deleteUser produces an error', function() {
  219. beforeEach(function() {
  220. this.UserDeleter.deleteUser = sinon.stub().yields(new Error('woops'))
  221. })
  222. it('should call next with an error', function(done) {
  223. this.next = err => {
  224. expect(err).to.not.equal(null)
  225. expect(err).to.be.instanceof(Error)
  226. done()
  227. }
  228. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  229. })
  230. })
  231. describe('when deleteUser produces a known error', function() {
  232. beforeEach(function() {
  233. this.UserDeleter.deleteUser = sinon
  234. .stub()
  235. .yields(new Errors.SubscriptionAdminDeletionError())
  236. })
  237. it('should return a HTTP Unprocessable Entity error', function(done) {
  238. this.HttpErrorHandler.unprocessableEntity = sinon.spy(
  239. (req, res, message, info) => {
  240. expect(req).to.exist
  241. expect(res).to.exist
  242. expect(message).to.equal('error while deleting user account')
  243. expect(info).to.deep.equal({
  244. error: 'SubscriptionAdminDeletionError'
  245. })
  246. done()
  247. }
  248. )
  249. this.UserController.tryDeleteUser(this.req, this.res)
  250. })
  251. })
  252. describe('when session.destroy produces an error', function() {
  253. beforeEach(function() {
  254. this.req.session.destroy = sinon
  255. .stub()
  256. .callsArgWith(0, new Error('woops'))
  257. })
  258. it('should call next with an error', function(done) {
  259. this.next = err => {
  260. expect(err).to.not.equal(null)
  261. expect(err).to.be.instanceof(Error)
  262. done()
  263. }
  264. this.UserController.tryDeleteUser(this.req, this.res, this.next)
  265. })
  266. })
  267. })
  268. describe('unsubscribe', function() {
  269. it('should send the user to unsubscribe', function(done) {
  270. this.res.sendStatus = () => {
  271. this.NewsLetterManager.unsubscribe
  272. .calledWith(this.user)
  273. .should.equal(true)
  274. done()
  275. }
  276. this.UserController.unsubscribe(this.req, this.res)
  277. })
  278. })
  279. describe('updateUserSettings', function() {
  280. beforeEach(function() {
  281. this.auditLog = { initiatorId: this.user_id, ipAddress: this.req.ip }
  282. this.newEmail = 'hello@world.com'
  283. this.req.externalAuthenticationSystemUsed = sinon.stub().returns(false)
  284. })
  285. it('should call save', function(done) {
  286. this.req.body = {}
  287. this.res.sendStatus = code => {
  288. this.user.save.called.should.equal(true)
  289. done()
  290. }
  291. this.UserController.updateUserSettings(this.req, this.res)
  292. })
  293. it('should set the first name', function(done) {
  294. this.req.body = { first_name: 'bobby ' }
  295. this.res.sendStatus = code => {
  296. this.user.first_name.should.equal('bobby')
  297. done()
  298. }
  299. this.UserController.updateUserSettings(this.req, this.res)
  300. })
  301. it('should set the role', function(done) {
  302. this.req.body = { role: 'student' }
  303. this.res.sendStatus = code => {
  304. this.user.role.should.equal('student')
  305. done()
  306. }
  307. this.UserController.updateUserSettings(this.req, this.res)
  308. })
  309. it('should set the institution', function(done) {
  310. this.req.body = { institution: 'MIT' }
  311. this.res.sendStatus = code => {
  312. this.user.institution.should.equal('MIT')
  313. done()
  314. }
  315. this.UserController.updateUserSettings(this.req, this.res)
  316. })
  317. it('should set some props on ace', function(done) {
  318. this.req.body = { editorTheme: 'something' }
  319. this.res.sendStatus = code => {
  320. this.user.ace.theme.should.equal('something')
  321. done()
  322. }
  323. this.UserController.updateUserSettings(this.req, this.res)
  324. })
  325. it('should set the overall theme', function(done) {
  326. this.req.body = { overallTheme: 'green-ish' }
  327. this.res.sendStatus = code => {
  328. this.user.ace.overallTheme.should.equal('green-ish')
  329. done()
  330. }
  331. this.UserController.updateUserSettings(this.req, this.res)
  332. })
  333. it('should send an error if the email is 0 len', function(done) {
  334. this.req.body.email = ''
  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 send an error if the email does not contain an @', function(done) {
  342. this.req.body.email = 'bob at something dot com'
  343. this.res.sendStatus = function(code) {
  344. code.should.equal(400)
  345. done()
  346. }
  347. this.UserController.updateUserSettings(this.req, this.res)
  348. })
  349. it('should call the user updater with the new email and user _id', function(done) {
  350. this.req.body.email = this.newEmail.toUpperCase()
  351. this.UserUpdater.changeEmailAddress.callsArgWith(3)
  352. this.res.sendStatus = code => {
  353. code.should.equal(200)
  354. this.UserUpdater.changeEmailAddress
  355. .calledWith(this.user_id, this.newEmail, this.auditLog)
  356. .should.equal(true)
  357. done()
  358. }
  359. this.UserController.updateUserSettings(this.req, this.res)
  360. })
  361. it('should update the email on the session', function(done) {
  362. this.req.body.email = this.newEmail.toUpperCase()
  363. this.UserUpdater.changeEmailAddress.callsArgWith(3)
  364. let callcount = 0
  365. this.User.findById = (id, cb) => {
  366. if (++callcount === 2) {
  367. this.user.email = this.newEmail
  368. }
  369. cb(null, this.user)
  370. }
  371. this.res.sendStatus = code => {
  372. code.should.equal(200)
  373. this.AuthenticationController.setInSessionUser
  374. .calledWith(this.req, {
  375. email: this.newEmail,
  376. first_name: undefined,
  377. last_name: undefined
  378. })
  379. .should.equal(true)
  380. done()
  381. }
  382. this.UserController.updateUserSettings(this.req, this.res)
  383. })
  384. it('should call populateTeamInvites', function(done) {
  385. this.req.body.email = this.newEmail.toUpperCase()
  386. this.UserUpdater.changeEmailAddress.callsArgWith(3)
  387. this.res.sendStatus = code => {
  388. code.should.equal(200)
  389. this.UserHandler.populateTeamInvites
  390. .calledWith(this.user)
  391. .should.equal(true)
  392. done()
  393. }
  394. this.UserController.updateUserSettings(this.req, this.res)
  395. })
  396. describe('when changeEmailAddress yields an error', function() {
  397. it('should pass on an error and not send a success status', function(done) {
  398. this.req.body.email = this.newEmail.toUpperCase()
  399. this.UserUpdater.changeEmailAddress.callsArgWith(3, new OError())
  400. this.HttpErrorHandler.legacyInternal = sinon.spy(
  401. (req, res, message, error) => {
  402. expect(req).to.exist
  403. expect(req).to.exist
  404. message.should.equal('problem_changing_email_address')
  405. expect(error).to.be.instanceof(OError)
  406. done()
  407. }
  408. )
  409. this.UserController.updateUserSettings(this.req, this.res, this.next)
  410. })
  411. it('should call the HTTP conflict error handler when the email already exists', function(done) {
  412. this.HttpErrorHandler.conflict = sinon.spy((req, res, message) => {
  413. expect(req).to.exist
  414. expect(req).to.exist
  415. message.should.equal('email_already_registered')
  416. done()
  417. })
  418. this.req.body.email = this.newEmail.toUpperCase()
  419. this.UserUpdater.changeEmailAddress.callsArgWith(
  420. 3,
  421. new Errors.EmailExistsError()
  422. )
  423. this.UserController.updateUserSettings(this.req, this.res)
  424. })
  425. })
  426. describe('when using an external auth source', function() {
  427. beforeEach(function() {
  428. this.UserUpdater.changeEmailAddress.callsArgWith(2)
  429. this.newEmail = 'someone23@example.com'
  430. this.req.externalAuthenticationSystemUsed = sinon.stub().returns(true)
  431. })
  432. it('should not set a new email', function(done) {
  433. this.req.body.email = this.newEmail
  434. this.res.sendStatus = code => {
  435. code.should.equal(200)
  436. this.UserUpdater.changeEmailAddress
  437. .calledWith(this.user_id, this.newEmail)
  438. .should.equal(false)
  439. done()
  440. }
  441. this.UserController.updateUserSettings(this.req, this.res)
  442. })
  443. })
  444. })
  445. describe('logout', function() {
  446. it('should destroy the session', function(done) {
  447. this.req.session.destroy = sinon.stub().callsArgWith(0)
  448. this.res.redirect = url => {
  449. url.should.equal('/login')
  450. this.req.session.destroy.called.should.equal(true)
  451. done()
  452. }
  453. this.UserController.logout(this.req, this.res)
  454. })
  455. it('should untrack session', function(done) {
  456. this.req.session.destroy = sinon.stub().callsArgWith(0)
  457. this.res.redirect = url => {
  458. url.should.equal('/login')
  459. this.UserSessionsManager.untrackSession.callCount.should.equal(1)
  460. this.UserSessionsManager.untrackSession
  461. .calledWith(sinon.match(this.req.user), this.req.sessionID)
  462. .should.equal(true)
  463. done()
  464. }
  465. this.UserController.logout(this.req, this.res)
  466. })
  467. it('should redirect after logout', function(done) {
  468. this.req.body.redirect = '/institutional-login'
  469. this.req.session.destroy = sinon.stub().callsArgWith(0)
  470. this.res.redirect = url => {
  471. url.should.equal(this.req.body.redirect)
  472. done()
  473. }
  474. this.UserController.logout(this.req, this.res)
  475. })
  476. it('should redirect to login after logout when no redirect set', function(done) {
  477. this.req.session.destroy = sinon.stub().callsArgWith(0)
  478. this.res.redirect = url => {
  479. url.should.equal('/login')
  480. done()
  481. }
  482. this.UserController.logout(this.req, this.res)
  483. })
  484. })
  485. describe('register', function() {
  486. beforeEach(function() {
  487. this.UserRegistrationHandler.registerNewUserAndSendActivationEmail = sinon
  488. .stub()
  489. .callsArgWith(1, null, this.user, (this.url = 'mock/url'))
  490. this.req.body.email = this.user.email = this.email = 'email@example.com'
  491. this.UserController.register(this.req, this.res)
  492. })
  493. it('should register the user and send them an email', function() {
  494. this.UserRegistrationHandler.registerNewUserAndSendActivationEmail
  495. .calledWith(this.email)
  496. .should.equal(true)
  497. })
  498. it('should return the user and activation url', function() {
  499. this.res.json
  500. .calledWith({
  501. email: this.email,
  502. setNewPasswordUrl: this.url
  503. })
  504. .should.equal(true)
  505. })
  506. })
  507. describe('clearSessions', function() {
  508. describe('success', function() {
  509. it('should call revokeAllUserSessions', function(done) {
  510. this.res.sendStatus.callsFake(() => {
  511. this.UserSessionsManager.promises.revokeAllUserSessions.callCount.should.equal(
  512. 1
  513. )
  514. done()
  515. })
  516. this.UserController.clearSessions(this.req, this.res)
  517. })
  518. it('send a 201 response', function(done) {
  519. this.res.sendStatus.callsFake(status => {
  520. status.should.equal(201)
  521. done()
  522. })
  523. this.UserController.clearSessions(this.req, this.res)
  524. })
  525. it('sends a security alert email', function(done) {
  526. this.res.sendStatus.callsFake(status => {
  527. this.EmailHandler.promises.sendEmail.callCount.should.equal(1)
  528. const expectedArg = {
  529. to: this.user.email,
  530. actionDescribed: `active sessions were cleared on your account ${
  531. this.user.email
  532. }`,
  533. action: 'active sessions cleared'
  534. }
  535. const emailCall = this.EmailHandler.promises.sendEmail.lastCall
  536. expect(emailCall.args[0]).to.equal('securityAlert')
  537. expect(emailCall.args[1]).to.deep.equal(expectedArg)
  538. done()
  539. })
  540. this.UserController.clearSessions(this.req, this.res)
  541. })
  542. })
  543. describe('errors', function() {
  544. describe('when getAllUserSessions produces an error', function() {
  545. it('should return an error', function(done) {
  546. this.UserSessionsManager.promises.getAllUserSessions.rejects(
  547. new Error('woops')
  548. )
  549. this.UserController.clearSessions(this.req, this.res, error => {
  550. expect(error).to.be.instanceof(Error)
  551. done()
  552. })
  553. })
  554. })
  555. describe('when audit log addEntry produces an error', function() {
  556. it('should call next with an error', function(done) {
  557. this.UserAuditLogHandler.promises.addEntry.rejects(new Error('woops'))
  558. this.UserController.clearSessions(this.req, this.res, error => {
  559. expect(error).to.be.instanceof(Error)
  560. done()
  561. })
  562. })
  563. })
  564. describe('when revokeAllUserSessions produces an error', function() {
  565. it('should call next with an error', function(done) {
  566. this.UserSessionsManager.promises.revokeAllUserSessions.rejects(
  567. new Error('woops')
  568. )
  569. this.UserController.clearSessions(this.req, this.res, error => {
  570. expect(error).to.be.instanceof(Error)
  571. done()
  572. })
  573. })
  574. })
  575. describe('when EmailHandler produces an error', function() {
  576. const anError = new Error('oops')
  577. it('send a 201 response but log error', function(done) {
  578. this.EmailHandler.promises.sendEmail.rejects(anError)
  579. this.res.sendStatus.callsFake(status => {
  580. status.should.equal(201)
  581. this.logger.error.callCount.should.equal(1)
  582. const loggerCall = this.logger.error.getCall(0)
  583. expect(loggerCall.args[0]).to.deep.equal({
  584. error: anError,
  585. userId: this.user_id
  586. })
  587. expect(loggerCall.args[1]).to.contain(
  588. 'could not send security alert email when sessions cleared'
  589. )
  590. done()
  591. })
  592. this.UserController.clearSessions(this.req, this.res)
  593. })
  594. })
  595. })
  596. })
  597. describe('changePassword', function() {
  598. describe('success', function() {
  599. beforeEach(function() {
  600. this.AuthenticationManager.promises.authenticate.resolves(this.user)
  601. this.AuthenticationManager.promises.setUserPassword.resolves()
  602. this.req.body = {
  603. newPassword1: 'newpass',
  604. newPassword2: 'newpass'
  605. }
  606. })
  607. it('should set the new password if they do match', function(done) {
  608. this.res.json.callsFake(() => {
  609. this.AuthenticationManager.promises.setUserPassword.should.have.been.calledWith(
  610. this.user,
  611. 'newpass'
  612. )
  613. done()
  614. })
  615. this.UserController.changePassword(this.req, this.res)
  616. })
  617. it('should log the update', function(done) {
  618. this.res.json.callsFake(() => {
  619. this.UserAuditLogHandler.promises.addEntry.should.have.been.calledWith(
  620. this.user._id,
  621. 'update-password',
  622. this.user._id,
  623. this.req.ip
  624. )
  625. this.AuthenticationManager.promises.setUserPassword.callCount.should.equal(
  626. 1
  627. )
  628. done()
  629. })
  630. this.UserController.changePassword(this.req, this.res)
  631. })
  632. it('should send security alert email', function(done) {
  633. this.res.json.callsFake(() => {
  634. const expectedArg = {
  635. to: this.user.email,
  636. actionDescribed: `your password has been changed on your account ${
  637. this.user.email
  638. }`,
  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. })