UserControllerTests.js 32 KB

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