AuthenticationControllerTests.js 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  1. const sinon = require('sinon')
  2. const chai = require('chai')
  3. const { expect } = chai
  4. const modulePath =
  5. '../../../../app/src/Features/Authentication/AuthenticationController.js'
  6. const SandboxedModule = require('sandboxed-module')
  7. const tk = require('timekeeper')
  8. const MockRequest = require('../helpers/MockRequest')
  9. const MockResponse = require('../helpers/MockResponse')
  10. const { ObjectId } = require('mongodb')
  11. describe('AuthenticationController', function() {
  12. beforeEach(function() {
  13. tk.freeze(Date.now())
  14. this.UserModel = { findOne: sinon.stub() }
  15. this.httpAuthUsers = {
  16. 'valid-test-user': Math.random()
  17. .toString(16)
  18. .slice(2)
  19. }
  20. this.AuthenticationController = SandboxedModule.require(modulePath, {
  21. globals: {
  22. console: console
  23. },
  24. requires: {
  25. '../Helpers/AsyncFormHelper': (this.AsyncFormHelper = {
  26. redirect: sinon.stub()
  27. }),
  28. '../../infrastructure/RequestContentTypeDetection': {
  29. acceptsJson: (this.acceptsJson = sinon.stub().returns(false))
  30. },
  31. './AuthenticationManager': (this.AuthenticationManager = {}),
  32. '../User/UserUpdater': (this.UserUpdater = {
  33. updateUser: sinon.stub()
  34. }),
  35. '@overleaf/metrics': (this.Metrics = { inc: sinon.stub() }),
  36. '../Security/LoginRateLimiter': (this.LoginRateLimiter = {
  37. processLoginRequest: sinon.stub(),
  38. recordSuccessfulLogin: sinon.stub()
  39. }),
  40. '../User/UserHandler': (this.UserHandler = {
  41. setupLoginData: sinon.stub()
  42. }),
  43. '../Analytics/AnalyticsManager': (this.AnalyticsManager = {
  44. recordEvent: sinon.stub(),
  45. identifyUser: sinon.stub()
  46. }),
  47. '../../infrastructure/SessionStoreManager': (this.SessionStoreManager = {}),
  48. 'logger-sharelatex': (this.logger = {
  49. log: sinon.stub(),
  50. warn: sinon.stub(),
  51. error: sinon.stub(),
  52. err: sinon.stub()
  53. }),
  54. 'settings-sharelatex': (this.Settings = {
  55. siteUrl: 'http://www.foo.bar',
  56. httpAuthUsers: this.httpAuthUsers
  57. }),
  58. passport: (this.passport = {
  59. authenticate: sinon.stub().returns(sinon.stub())
  60. }),
  61. '../User/UserSessionsManager': (this.UserSessionsManager = {
  62. trackSession: sinon.stub(),
  63. untrackSession: sinon.stub(),
  64. revokeAllUserSessions: sinon.stub().callsArgWith(1, null)
  65. }),
  66. '../../infrastructure/Modules': (this.Modules = {
  67. hooks: { fire: sinon.stub().yields(null, []) }
  68. }),
  69. '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {
  70. ipMatcherAffiliation: sinon.stub().returns({ create: sinon.stub() })
  71. }),
  72. '../../models/User': { User: this.UserModel },
  73. '../../../../modules/oauth2-server/app/src/Oauth2Server': (this.Oauth2Server = {
  74. Request: sinon.stub(),
  75. Response: sinon.stub(),
  76. server: {
  77. authenticate: sinon.stub()
  78. }
  79. }),
  80. '../Helpers/UrlHelper': (this.UrlHelper = {
  81. getSafeRedirectPath: sinon.stub()
  82. })
  83. }
  84. })
  85. this.UrlHelper.getSafeRedirectPath
  86. .withArgs('https://evil.com')
  87. .returns(undefined)
  88. this.UrlHelper.getSafeRedirectPath.returnsArg(0)
  89. this.user = {
  90. _id: ObjectId(),
  91. email: (this.email = 'USER@example.com'),
  92. first_name: 'bob',
  93. last_name: 'brown',
  94. referal_id: 1234,
  95. isAdmin: false
  96. }
  97. this.password = 'banana'
  98. this.req = new MockRequest()
  99. this.res = new MockResponse()
  100. this.callback = sinon.stub()
  101. this.next = sinon.stub()
  102. })
  103. afterEach(function() {
  104. tk.reset()
  105. })
  106. describe('validateAdmin', function() {
  107. beforeEach(function() {
  108. this.Settings.adminDomains = ['good.example.com']
  109. this.goodAdmin = {
  110. email: 'alice@good.example.com',
  111. isAdmin: true
  112. }
  113. this.badAdmin = {
  114. email: 'beatrice@bad.example.com',
  115. isAdmin: true
  116. }
  117. this.normalUser = {
  118. email: 'claire@whatever.example.com',
  119. isAdmin: false
  120. }
  121. })
  122. it('should skip when adminDomains are not configured', function(done) {
  123. this.Settings.adminDomains = []
  124. this.AuthenticationController.getSessionUser = sinon
  125. .stub()
  126. .returns(this.normalUser)
  127. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  128. this.AuthenticationController.getSessionUser.called.should.equal(false)
  129. expect(err).to.not.exist
  130. done()
  131. })
  132. })
  133. it('should skip non-admin user', function(done) {
  134. this.AuthenticationController.getSessionUser = sinon
  135. .stub()
  136. .returns(this.normalUser)
  137. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  138. this.AuthenticationController.getSessionUser.called.should.equal(true)
  139. expect(err).to.not.exist
  140. done()
  141. })
  142. })
  143. it('should permit an admin with the right doman', function(done) {
  144. this.AuthenticationController.getSessionUser = sinon
  145. .stub()
  146. .returns(this.goodAdmin)
  147. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  148. this.AuthenticationController.getSessionUser.called.should.equal(true)
  149. expect(err).to.not.exist
  150. done()
  151. })
  152. })
  153. it('should block an admin with a missing email', function(done) {
  154. this.AuthenticationController.getSessionUser = sinon
  155. .stub()
  156. .returns({ isAdmin: true })
  157. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  158. this.AuthenticationController.getSessionUser.called.should.equal(true)
  159. expect(err).to.exist
  160. done()
  161. })
  162. })
  163. it('should block an admin with a bad domain', function(done) {
  164. this.AuthenticationController.getSessionUser = sinon
  165. .stub()
  166. .returns(this.badAdmin)
  167. this.AuthenticationController.validateAdmin(this.req, this.res, err => {
  168. this.AuthenticationController.getSessionUser.called.should.equal(true)
  169. expect(err).to.exist
  170. done()
  171. })
  172. })
  173. })
  174. describe('isUserLoggedIn', function() {
  175. beforeEach(function() {
  176. this.stub = sinon.stub(this.AuthenticationController, 'getLoggedInUserId')
  177. })
  178. afterEach(function() {
  179. this.stub.restore()
  180. })
  181. it('should do the right thing in all cases', function() {
  182. this.AuthenticationController.getLoggedInUserId.returns('some_id')
  183. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  184. true
  185. )
  186. this.AuthenticationController.getLoggedInUserId.returns(null)
  187. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  188. false
  189. )
  190. this.AuthenticationController.getLoggedInUserId.returns(false)
  191. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  192. false
  193. )
  194. this.AuthenticationController.getLoggedInUserId.returns(undefined)
  195. expect(this.AuthenticationController.isUserLoggedIn(this.req)).to.equal(
  196. false
  197. )
  198. })
  199. })
  200. describe('setInSessionUser', function() {
  201. beforeEach(function() {
  202. this.user = {
  203. _id: 'id',
  204. first_name: 'a',
  205. last_name: 'b',
  206. email: 'c'
  207. }
  208. this.AuthenticationController.getSessionUser = sinon
  209. .stub()
  210. .returns(this.user)
  211. })
  212. it('should update the right properties', function() {
  213. this.AuthenticationController.setInSessionUser(this.req, {
  214. first_name: 'new_first_name',
  215. email: 'new_email'
  216. })
  217. const expectedUser = {
  218. _id: 'id',
  219. first_name: 'new_first_name',
  220. last_name: 'b',
  221. email: 'new_email'
  222. }
  223. expect(this.user).to.deep.equal(expectedUser)
  224. expect(this.user).to.deep.equal(expectedUser)
  225. })
  226. })
  227. describe('passportLogin', function() {
  228. beforeEach(function() {
  229. this.info = null
  230. this.req.login = sinon.stub().callsArgWith(1, null)
  231. this.res.json = sinon.stub()
  232. this.req.session = {
  233. passport: { user: this.user },
  234. postLoginRedirect: '/path/to/redir/to'
  235. }
  236. this.req.session.destroy = sinon.stub().callsArgWith(0, null)
  237. this.req.session.save = sinon.stub().callsArgWith(0, null)
  238. this.req.sessionStore = { generate: sinon.stub() }
  239. this.AuthenticationController.finishLogin = sinon.stub()
  240. this.passport.authenticate.callsArgWith(1, null, this.user, this.info)
  241. this.err = new Error('woops')
  242. })
  243. it('should call passport.authenticate', function() {
  244. this.AuthenticationController.passportLogin(this.req, this.res, this.next)
  245. this.passport.authenticate.callCount.should.equal(1)
  246. })
  247. describe('when authenticate produces an error', function() {
  248. beforeEach(function() {
  249. this.passport.authenticate.callsArgWith(1, this.err)
  250. })
  251. it('should return next with an error', function() {
  252. this.AuthenticationController.passportLogin(
  253. this.req,
  254. this.res,
  255. this.next
  256. )
  257. this.next.calledWith(this.err).should.equal(true)
  258. })
  259. })
  260. describe('when authenticate produces a user', function() {
  261. beforeEach(function() {
  262. this.req.session.postLoginRedirect = 'some_redirect'
  263. this.passport.authenticate.callsArgWith(1, null, this.user, this.info)
  264. })
  265. afterEach(function() {
  266. delete this.req.session.postLoginRedirect
  267. })
  268. it('should call finishLogin', function() {
  269. this.AuthenticationController.passportLogin(
  270. this.req,
  271. this.res,
  272. this.next
  273. )
  274. this.AuthenticationController.finishLogin.callCount.should.equal(1)
  275. this.AuthenticationController.finishLogin
  276. .calledWith(this.user)
  277. .should.equal(true)
  278. })
  279. })
  280. describe('when authenticate does not produce a user', function() {
  281. beforeEach(function() {
  282. this.info = { text: 'a', type: 'b' }
  283. this.passport.authenticate.callsArgWith(1, null, false, this.info)
  284. })
  285. it('should not call finishLogin', function() {
  286. this.AuthenticationController.passportLogin(
  287. this.req,
  288. this.res,
  289. this.next
  290. )
  291. this.AuthenticationController.finishLogin.callCount.should.equal(0)
  292. })
  293. it('should not send a json response with redirect', function() {
  294. this.AuthenticationController.passportLogin(
  295. this.req,
  296. this.res,
  297. this.next
  298. )
  299. this.res.json.callCount.should.equal(1)
  300. this.res.json.calledWith({ message: this.info }).should.equal(true)
  301. expect(this.res.json.lastCall.args[0].redir != null).to.equal(false)
  302. })
  303. })
  304. })
  305. describe('doPassportLogin', function() {
  306. beforeEach(function() {
  307. this.AuthenticationController._recordFailedLogin = sinon.stub()
  308. this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
  309. this.Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [])
  310. // @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  311. this.req.body = {
  312. email: this.email,
  313. password: this.password,
  314. session: {
  315. postLoginRedirect: '/path/to/redir/to'
  316. }
  317. }
  318. this.cb = sinon.stub()
  319. })
  320. describe('when the preDoPassportLogin hooks produce an info object', function() {
  321. beforeEach(function() {
  322. this.Modules.hooks.fire = sinon
  323. .stub()
  324. .callsArgWith(3, null, [null, { redir: '/somewhere' }, null])
  325. })
  326. it('should stop early and call done with this info object', function(done) {
  327. this.AuthenticationController.doPassportLogin(
  328. this.req,
  329. this.req.body.email,
  330. this.req.body.password,
  331. this.cb
  332. )
  333. this.cb.callCount.should.equal(1)
  334. this.cb
  335. .calledWith(null, false, { redir: '/somewhere' })
  336. .should.equal(true)
  337. this.LoginRateLimiter.processLoginRequest.callCount.should.equal(0)
  338. done()
  339. })
  340. })
  341. describe('when the users rate limit', function() {
  342. beforeEach(function() {
  343. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  344. })
  345. it('should block the request if the limit has been exceeded', function(done) {
  346. this.AuthenticationController.doPassportLogin(
  347. this.req,
  348. this.req.body.email,
  349. this.req.body.password,
  350. this.cb
  351. )
  352. this.cb.callCount.should.equal(1)
  353. this.cb.calledWith(null, null).should.equal(true)
  354. done()
  355. })
  356. })
  357. describe('when the user is authenticated', function() {
  358. beforeEach(function() {
  359. this.cb = sinon.stub()
  360. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  361. this.AuthenticationManager.authenticate = sinon
  362. .stub()
  363. .callsArgWith(2, null, this.user)
  364. this.req.sessionID = Math.random()
  365. this.AuthenticationController.doPassportLogin(
  366. this.req,
  367. this.req.body.email,
  368. this.req.body.password,
  369. this.cb
  370. )
  371. })
  372. it('should attempt to authorise the user', function() {
  373. this.AuthenticationManager.authenticate
  374. .calledWith({ email: this.email.toLowerCase() }, this.password)
  375. .should.equal(true)
  376. })
  377. it("should establish the user's session", function() {
  378. this.cb.calledWith(null, this.user).should.equal(true)
  379. })
  380. })
  381. describe('when the user is not authenticated', function() {
  382. beforeEach(function() {
  383. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  384. this.AuthenticationManager.authenticate = sinon
  385. .stub()
  386. .callsArgWith(2, null, null)
  387. this.cb = sinon.stub()
  388. this.AuthenticationController.doPassportLogin(
  389. this.req,
  390. this.req.body.email,
  391. this.req.body.password,
  392. this.cb
  393. )
  394. })
  395. it('should not establish the login', function() {
  396. this.cb.callCount.should.equal(1)
  397. this.cb.calledWith(null, false)
  398. // @res.body.should.exist
  399. expect(this.cb.lastCall.args[2]).to.contain.all.keys(['text', 'type'])
  400. })
  401. // message:
  402. // text: 'Your email or password were incorrect. Please try again',
  403. // type: 'error'
  404. it('should not setup the user data in the background', function() {
  405. this.UserHandler.setupLoginData.called.should.equal(false)
  406. })
  407. it('should record a failed login', function() {
  408. this.AuthenticationController._recordFailedLogin.called.should.equal(
  409. true
  410. )
  411. })
  412. it('should log the failed login', function() {
  413. this.logger.log
  414. .calledWith({ email: this.email.toLowerCase() }, 'failed log in')
  415. .should.equal(true)
  416. })
  417. })
  418. })
  419. describe('getLoggedInUserId', function() {
  420. beforeEach(function() {
  421. this.req = { session: {} }
  422. })
  423. it('should return the user id from the session', function() {
  424. this.user_id = '2134'
  425. this.req.session.user = { _id: this.user_id }
  426. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  427. expect(result).to.equal(this.user_id)
  428. })
  429. it('should return user for passport session', function() {
  430. this.user_id = '2134'
  431. this.req.session = {
  432. passport: {
  433. user: {
  434. _id: this.user_id
  435. }
  436. }
  437. }
  438. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  439. expect(result).to.equal(this.user_id)
  440. })
  441. it('should return null if there is no user on the session', function() {
  442. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  443. expect(result).to.equal(null)
  444. })
  445. it('should return null if there is no session', function() {
  446. this.req = {}
  447. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  448. expect(result).to.equal(null)
  449. })
  450. it('should return null if there is no req', function() {
  451. this.req = {}
  452. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  453. expect(result).to.equal(null)
  454. })
  455. })
  456. describe('requireLogin', function() {
  457. beforeEach(function() {
  458. this.user = {
  459. _id: 'user-id-123',
  460. email: 'user@sharelatex.com'
  461. }
  462. this.middleware = this.AuthenticationController.requireLogin()
  463. })
  464. describe('when the user is logged in', function() {
  465. beforeEach(function() {
  466. this.req.session = {
  467. user: (this.user = {
  468. _id: 'user-id-123',
  469. email: 'user@sharelatex.com'
  470. })
  471. }
  472. this.middleware(this.req, this.res, this.next)
  473. })
  474. it('should call the next method in the chain', function() {
  475. this.next.called.should.equal(true)
  476. })
  477. })
  478. describe('when the user is not logged in', function() {
  479. beforeEach(function() {
  480. this.req.session = {}
  481. this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  482. this.req.query = {}
  483. this.middleware(this.req, this.res, this.next)
  484. })
  485. it('should redirect to the register or login page', function() {
  486. this.AuthenticationController._redirectToLoginOrRegisterPage
  487. .calledWith(this.req, this.res)
  488. .should.equal(true)
  489. })
  490. })
  491. })
  492. describe('validateUserSession', function() {
  493. beforeEach(function() {
  494. this.user = {
  495. _id: 'user-id-123',
  496. email: 'user@sharelatex.com'
  497. }
  498. this.middleware = this.AuthenticationController.validateUserSession()
  499. })
  500. describe('when the user has a session token', function() {
  501. beforeEach(function() {
  502. this.req.user = this.user
  503. this.SessionStoreManager.hasValidationToken = sinon.stub().returns(true)
  504. this.middleware(this.req, this.res, this.next)
  505. })
  506. it('should call the next method in the chain', function() {
  507. this.next.called.should.equal(true)
  508. })
  509. })
  510. describe('when the user does not have a session token', function() {
  511. beforeEach(function() {
  512. this.req.session = {
  513. user: this.user,
  514. regenerate: sinon.stub().yields()
  515. }
  516. this.req.user = this.user
  517. this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  518. this.req.query = {}
  519. this.SessionStoreManager.hasValidationToken = sinon
  520. .stub()
  521. .returns(false)
  522. this.middleware(this.req, this.res, this.next)
  523. })
  524. it('should destroy the current session', function() {
  525. this.req.session.regenerate.called.should.equal(true)
  526. })
  527. it('should redirect to the register or login page', function() {
  528. this.AuthenticationController._redirectToLoginOrRegisterPage
  529. .calledWith(this.req, this.res)
  530. .should.equal(true)
  531. })
  532. })
  533. })
  534. describe('requireOauth', function() {
  535. beforeEach(function() {
  536. this.res.send = sinon.stub()
  537. this.res.status = sinon.stub().returns(this.res)
  538. this.res.sendStatus = sinon.stub()
  539. this.middleware = this.AuthenticationController.requireOauth()
  540. })
  541. describe('when Oauth2Server authenticates', function() {
  542. beforeEach(function() {
  543. this.token = {
  544. accessToken: 'token',
  545. user: 'user'
  546. }
  547. this.Oauth2Server.server.authenticate.yields(null, this.token)
  548. this.middleware(this.req, this.res, this.next)
  549. })
  550. it('should set oauth_token on request', function() {
  551. this.req.oauth_token.should.equal(this.token)
  552. })
  553. it('should set oauth on request', function() {
  554. this.req.oauth.access_token.should.equal(this.token.accessToken)
  555. })
  556. it('should set oauth_user on request', function() {
  557. this.req.oauth_user.should.equal('user')
  558. })
  559. it('should call next', function() {
  560. this.next.should.have.been.calledOnce
  561. })
  562. })
  563. describe('when Oauth2Server returns 401 error', function() {
  564. beforeEach(function() {
  565. this.Oauth2Server.server.authenticate.yields({ code: 401 })
  566. this.middleware(this.req, this.res, this.next)
  567. })
  568. it('should return 401 error', function() {
  569. this.res.status.should.have.been.calledWith(401)
  570. })
  571. it('should not call next', function() {
  572. this.next.should.have.not.been.calledOnce
  573. })
  574. })
  575. })
  576. describe('requireGlobalLogin', function() {
  577. beforeEach(function() {
  578. this.req.headers = {}
  579. this.AuthenticationController.httpAuth = sinon.stub()
  580. this.setRedirect = sinon.spy(
  581. this.AuthenticationController,
  582. 'setRedirectInSession'
  583. )
  584. })
  585. afterEach(function() {
  586. this.setRedirect.restore()
  587. })
  588. describe('with white listed url', function() {
  589. beforeEach(function() {
  590. this.AuthenticationController.addEndpointToLoginWhitelist('/login')
  591. this.req._parsedUrl.pathname = '/login'
  592. this.AuthenticationController.requireGlobalLogin(
  593. this.req,
  594. this.res,
  595. this.next
  596. )
  597. })
  598. it('should call next() directly', function() {
  599. this.next.called.should.equal(true)
  600. })
  601. })
  602. describe('with white listed url and a query string', function() {
  603. beforeEach(function() {
  604. this.AuthenticationController.addEndpointToLoginWhitelist('/login')
  605. this.req._parsedUrl.pathname = '/login'
  606. this.req.url = '/login?query=something'
  607. this.AuthenticationController.requireGlobalLogin(
  608. this.req,
  609. this.res,
  610. this.next
  611. )
  612. })
  613. it('should call next() directly', function() {
  614. this.next.called.should.equal(true)
  615. })
  616. })
  617. describe('with http auth', function() {
  618. beforeEach(function() {
  619. this.req.headers.authorization = 'Mock Basic Auth'
  620. this.AuthenticationController.requireGlobalLogin(
  621. this.req,
  622. this.res,
  623. this.next
  624. )
  625. })
  626. it('should pass the request onto httpAuth', function() {
  627. this.AuthenticationController.httpAuth
  628. .calledWith(this.req, this.res, this.next)
  629. .should.equal(true)
  630. })
  631. })
  632. describe('with a user session', function() {
  633. beforeEach(function() {
  634. this.req.session = { user: { mock: 'user', _id: 'some_id' } }
  635. this.AuthenticationController.requireGlobalLogin(
  636. this.req,
  637. this.res,
  638. this.next
  639. )
  640. })
  641. it('should call next() directly', function() {
  642. this.next.called.should.equal(true)
  643. })
  644. })
  645. describe('with no login credentials', function() {
  646. beforeEach(function() {
  647. this.req.session = {}
  648. this.AuthenticationController.requireGlobalLogin(
  649. this.req,
  650. this.res,
  651. this.next
  652. )
  653. })
  654. it('should have called setRedirectInSession', function() {
  655. this.setRedirect.callCount.should.equal(1)
  656. })
  657. it('should redirect to the /login page', function() {
  658. this.res.redirectedTo.should.equal('/login')
  659. })
  660. })
  661. })
  662. describe('httpAuth', function() {
  663. describe('with http auth', function() {
  664. it('should error with incorrect user', function(done) {
  665. this.req.headers = {
  666. authorization: `Basic ${Buffer.from('user:nope').toString('base64')}`
  667. }
  668. this.req.end = status => {
  669. expect(status).to.equal('Unauthorized')
  670. done()
  671. }
  672. this.AuthenticationController.httpAuth(this.req, this.req)
  673. })
  674. it('should error with incorrect password', function(done) {
  675. this.req.headers = {
  676. authorization: `Basic ${Buffer.from('valid-test-user:nope').toString(
  677. 'base64'
  678. )}`
  679. }
  680. this.req.end = status => {
  681. expect(status).to.equal('Unauthorized')
  682. done()
  683. }
  684. this.AuthenticationController.httpAuth(this.req, this.req)
  685. })
  686. it('should fail with empty pass', function(done) {
  687. this.req.headers = {
  688. authorization: `Basic ${Buffer.from(`invalid-test-user:`).toString(
  689. 'base64'
  690. )}`
  691. }
  692. this.req.end = status => {
  693. expect(status).to.equal('Unauthorized')
  694. done()
  695. }
  696. this.AuthenticationController.httpAuth(this.req, this.req)
  697. })
  698. it('should succeed with correct user/pass', function(done) {
  699. this.req.headers = {
  700. authorization: `Basic ${Buffer.from(
  701. `valid-test-user:${this.httpAuthUsers['valid-test-user']}`
  702. ).toString('base64')}`
  703. }
  704. this.AuthenticationController.httpAuth(this.req, this.res, done)
  705. })
  706. })
  707. })
  708. describe('_redirectToLoginOrRegisterPage', function() {
  709. beforeEach(function() {
  710. this.middleware = this.AuthenticationController.requireLogin(
  711. (this.options = { load_from_db: false })
  712. )
  713. this.req.session = {}
  714. this.AuthenticationController._redirectToRegisterPage = sinon.stub()
  715. this.AuthenticationController._redirectToLoginPage = sinon.stub()
  716. this.req.query = {}
  717. })
  718. describe('they have come directly to the url', function() {
  719. beforeEach(function() {
  720. this.req.query = {}
  721. this.middleware(this.req, this.res, this.next)
  722. })
  723. it('should redirect to the login page', function() {
  724. this.AuthenticationController._redirectToRegisterPage
  725. .calledWith(this.req, this.res)
  726. .should.equal(false)
  727. this.AuthenticationController._redirectToLoginPage
  728. .calledWith(this.req, this.res)
  729. .should.equal(true)
  730. })
  731. })
  732. describe('they have come via a templates link', function() {
  733. beforeEach(function() {
  734. this.req.query.zipUrl = 'something'
  735. this.middleware(this.req, this.res, this.next)
  736. })
  737. it('should redirect to the register page', function() {
  738. this.AuthenticationController._redirectToRegisterPage
  739. .calledWith(this.req, this.res)
  740. .should.equal(true)
  741. this.AuthenticationController._redirectToLoginPage
  742. .calledWith(this.req, this.res)
  743. .should.equal(false)
  744. })
  745. })
  746. describe('they have been invited to a project', function() {
  747. beforeEach(function() {
  748. this.req.query.project_name = 'something'
  749. this.middleware(this.req, this.res, this.next)
  750. })
  751. it('should redirect to the register page', function() {
  752. this.AuthenticationController._redirectToRegisterPage
  753. .calledWith(this.req, this.res)
  754. .should.equal(true)
  755. this.AuthenticationController._redirectToLoginPage
  756. .calledWith(this.req, this.res)
  757. .should.equal(false)
  758. })
  759. })
  760. })
  761. describe('_redirectToRegisterPage', function() {
  762. beforeEach(function() {
  763. this.req.path = '/target/url'
  764. this.req.query = { extra_query: 'foo' }
  765. this.AuthenticationController._redirectToRegisterPage(this.req, this.res)
  766. })
  767. it('should redirect to the register page with a query string attached', function() {
  768. this.req.session.postLoginRedirect.should.equal(
  769. '/target/url?extra_query=foo'
  770. )
  771. this.res.redirectedTo.should.equal('/register?extra_query=foo')
  772. })
  773. it('should log out a message', function() {
  774. this.logger.log
  775. .calledWith(
  776. { url: this.url },
  777. 'user not logged in so redirecting to register page'
  778. )
  779. .should.equal(true)
  780. })
  781. })
  782. describe('_redirectToLoginPage', function() {
  783. beforeEach(function() {
  784. this.req.path = '/target/url'
  785. this.req.query = { extra_query: 'foo' }
  786. this.AuthenticationController._redirectToLoginPage(this.req, this.res)
  787. })
  788. it('should redirect to the register page with a query string attached', function() {
  789. this.req.session.postLoginRedirect.should.equal(
  790. '/target/url?extra_query=foo'
  791. )
  792. this.res.redirectedTo.should.equal('/login?extra_query=foo')
  793. })
  794. })
  795. describe('_recordSuccessfulLogin', function() {
  796. beforeEach(function() {
  797. this.UserUpdater.updateUser = sinon.stub().callsArg(2)
  798. this.AuthenticationController._recordSuccessfulLogin(
  799. this.user._id,
  800. this.callback
  801. )
  802. })
  803. it('should increment the user.login.success metric', function() {
  804. this.Metrics.inc.calledWith('user.login.success').should.equal(true)
  805. })
  806. it("should update the user's login count and last logged in date", function() {
  807. this.UserUpdater.updateUser.args[0][1].$set.lastLoggedIn.should.not.equal(
  808. undefined
  809. )
  810. this.UserUpdater.updateUser.args[0][1].$inc.loginCount.should.equal(1)
  811. })
  812. it('should call the callback', function() {
  813. this.callback.called.should.equal(true)
  814. })
  815. })
  816. describe('_recordFailedLogin', function() {
  817. beforeEach(function() {
  818. this.AuthenticationController._recordFailedLogin(this.callback)
  819. })
  820. it('should increment the user.login.failed metric', function() {
  821. this.Metrics.inc.calledWith('user.login.failed').should.equal(true)
  822. })
  823. it('should call the callback', function() {
  824. this.callback.called.should.equal(true)
  825. })
  826. })
  827. describe('setRedirectInSession', function() {
  828. beforeEach(function() {
  829. this.req = { session: {} }
  830. this.req.path = '/somewhere'
  831. this.req.query = { one: '1' }
  832. })
  833. it('should set redirect property on session', function() {
  834. this.AuthenticationController.setRedirectInSession(this.req)
  835. expect(this.req.session.postLoginRedirect).to.equal('/somewhere?one=1')
  836. })
  837. it('should set the supplied value', function() {
  838. this.AuthenticationController.setRedirectInSession(
  839. this.req,
  840. '/somewhere/specific'
  841. )
  842. expect(this.req.session.postLoginRedirect).to.equal('/somewhere/specific')
  843. })
  844. it('should not allow open redirects', function() {
  845. this.AuthenticationController.setRedirectInSession(
  846. this.req,
  847. 'https://evil.com'
  848. )
  849. expect(this.req.session.postLoginRedirect).to.be.undefined
  850. })
  851. describe('with a png', function() {
  852. beforeEach(function() {
  853. this.req = { session: {} }
  854. })
  855. it('should not set the redirect', function() {
  856. this.AuthenticationController.setRedirectInSession(
  857. this.req,
  858. '/something.png'
  859. )
  860. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  861. })
  862. })
  863. describe('with a js path', function() {
  864. beforeEach(function() {
  865. this.req = { session: {} }
  866. })
  867. it('should not set the redirect', function() {
  868. this.AuthenticationController.setRedirectInSession(
  869. this.req,
  870. '/js/something.js'
  871. )
  872. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  873. })
  874. })
  875. })
  876. describe('_getRedirectFromSession', function() {
  877. it('should get redirect property from session', function() {
  878. this.req = { session: { postLoginRedirect: '/a?b=c' } }
  879. expect(
  880. this.AuthenticationController._getRedirectFromSession(this.req)
  881. ).to.equal('/a?b=c')
  882. })
  883. it('should not allow open redirects', function() {
  884. this.req = { session: { postLoginRedirect: 'https://evil.com' } }
  885. expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
  886. .be.null
  887. })
  888. it('handle null values', function() {
  889. this.req = { session: {} }
  890. expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
  891. .be.null
  892. })
  893. })
  894. describe('_clearRedirectFromSession', function() {
  895. beforeEach(function() {
  896. this.req = { session: { postLoginRedirect: '/a?b=c' } }
  897. })
  898. it('should remove the redirect property from session', function() {
  899. this.AuthenticationController._clearRedirectFromSession(this.req)
  900. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  901. })
  902. })
  903. describe('finishLogin', function() {
  904. // - get redirect
  905. // - async handlers
  906. // - afterLoginSessionSetup
  907. // - clear redirect
  908. // - issue redir, two ways
  909. beforeEach(function() {
  910. this.AuthenticationController._getRedirectFromSession = sinon
  911. .stub()
  912. .returns('/some/page')
  913. this.req.sessionID = 'thisisacryptographicallysecurerandomid'
  914. this.req.session = {
  915. passport: { user: { _id: 'one' } }
  916. }
  917. this.req.session.destroy = sinon.stub().callsArgWith(0, null)
  918. this.req.session.save = sinon.stub().callsArgWith(0, null)
  919. this.req.sessionStore = { generate: sinon.stub() }
  920. this.req.login = sinon.stub().yields(null)
  921. this.AuthenticationController._clearRedirectFromSession = sinon.stub()
  922. this.AuthenticationController._redirectToReconfirmPage = sinon.stub()
  923. this.UserSessionsManager.trackSession = sinon.stub()
  924. this.UserHandler.setupLoginData = sinon.stub()
  925. this.LoginRateLimiter.recordSuccessfulLogin = sinon.stub()
  926. this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
  927. this.AnalyticsManager.recordEvent = sinon.stub()
  928. this.AnalyticsManager.identifyUser = sinon.stub()
  929. this.acceptsJson.returns(true)
  930. this.res.json = sinon.stub()
  931. this.res.redirect = sinon.stub()
  932. })
  933. it('should extract the redirect from the session', function() {
  934. this.AuthenticationController.finishLogin(
  935. this.user,
  936. this.req,
  937. this.res,
  938. this.next
  939. )
  940. expect(
  941. this.AuthenticationController._getRedirectFromSession.callCount
  942. ).to.equal(1)
  943. expect(
  944. this.AuthenticationController._getRedirectFromSession.calledWith(
  945. this.req
  946. )
  947. ).to.equal(true)
  948. })
  949. it('should clear redirect from session', function() {
  950. this.AuthenticationController.finishLogin(
  951. this.user,
  952. this.req,
  953. this.res,
  954. this.next
  955. )
  956. expect(
  957. this.AuthenticationController._clearRedirectFromSession.callCount
  958. ).to.equal(1)
  959. expect(
  960. this.AuthenticationController._clearRedirectFromSession.calledWith(
  961. this.req
  962. )
  963. ).to.equal(true)
  964. })
  965. it('should issue a json response with a redirect', function() {
  966. this.AuthenticationController.finishLogin(
  967. this.user,
  968. this.req,
  969. this.res,
  970. this.next
  971. )
  972. expect(
  973. this.AsyncFormHelper.redirect.calledWith(
  974. this.req,
  975. this.res,
  976. '/some/page'
  977. )
  978. ).to.equal(true)
  979. })
  980. describe('with a non-json request', function() {
  981. beforeEach(function() {
  982. this.acceptsJson.returns(false)
  983. this.res.json = sinon.stub()
  984. this.res.redirect = sinon.stub()
  985. })
  986. it('should issue a plain redirect', function() {
  987. this.AuthenticationController.finishLogin(
  988. this.user,
  989. this.req,
  990. this.res,
  991. this.next
  992. )
  993. expect(
  994. this.AsyncFormHelper.redirect.calledWith(
  995. this.req,
  996. this.res,
  997. '/some/page'
  998. )
  999. ).to.equal(true)
  1000. })
  1001. })
  1002. describe('when user is flagged to reconfirm', function() {
  1003. beforeEach(function() {
  1004. this.req.session = {}
  1005. this.user.must_reconfirm = true
  1006. })
  1007. it('should redirect to reconfirm page', function() {
  1008. this.AuthenticationController.finishLogin(
  1009. this.user,
  1010. this.req,
  1011. this.res,
  1012. this.next
  1013. )
  1014. expect(
  1015. this.AuthenticationController._redirectToReconfirmPage.calledWith(
  1016. this.req
  1017. )
  1018. ).to.equal(true)
  1019. })
  1020. })
  1021. describe('preFinishLogin hook', function() {
  1022. it('call hook and proceed', function() {
  1023. this.Modules.hooks.fire = sinon.stub().yields(null, [])
  1024. this.AuthenticationController.finishLogin(
  1025. this.user,
  1026. this.req,
  1027. this.res,
  1028. this.next
  1029. )
  1030. sinon.assert.calledWith(
  1031. this.Modules.hooks.fire,
  1032. 'preFinishLogin',
  1033. this.req,
  1034. this.res,
  1035. this.user
  1036. )
  1037. expect(this.AsyncFormHelper.redirect.called).to.equal(true)
  1038. })
  1039. it('stop if hook has redirected', function(done) {
  1040. this.Modules.hooks.fire = sinon
  1041. .stub()
  1042. .yields(null, [{ doNotFinish: true }])
  1043. this.AuthenticationController.finishLogin(
  1044. this.user,
  1045. this.req,
  1046. this.res,
  1047. this.next
  1048. )
  1049. expect(this.next.callCount).to.equal(0)
  1050. expect(this.res.json.callCount).to.equal(0)
  1051. done()
  1052. })
  1053. it('call next with hook errors', function(done) {
  1054. this.Modules.hooks.fire = sinon.stub().yields(new Error())
  1055. this.AuthenticationController.finishLogin(
  1056. this.user,
  1057. this.req,
  1058. this.res,
  1059. error => {
  1060. expect(error).to.exist
  1061. expect(this.res.json.callCount).to.equal(0)
  1062. done()
  1063. }
  1064. )
  1065. })
  1066. })
  1067. describe('_afterLoginSessionSetup', function() {
  1068. beforeEach(function() {})
  1069. it('should call req.login', function() {
  1070. this.AuthenticationController.finishLogin(
  1071. this.user,
  1072. this.req,
  1073. this.res,
  1074. this.next
  1075. )
  1076. this.req.login.callCount.should.equal(1)
  1077. })
  1078. it('should call req.session.save', function() {
  1079. this.AuthenticationController.finishLogin(
  1080. this.user,
  1081. this.req,
  1082. this.res,
  1083. this.next
  1084. )
  1085. this.req.session.save.callCount.should.equal(1)
  1086. })
  1087. it('should call UserSessionsManager.trackSession', function() {
  1088. this.AuthenticationController.finishLogin(
  1089. this.user,
  1090. this.req,
  1091. this.res,
  1092. this.next
  1093. )
  1094. this.UserSessionsManager.trackSession.callCount.should.equal(1)
  1095. })
  1096. describe('when req.session.save produces an error', function() {
  1097. beforeEach(function() {
  1098. this.req.session.save = sinon
  1099. .stub()
  1100. .callsArgWith(0, new Error('woops'))
  1101. })
  1102. it('should produce an error', function(done) {
  1103. this.AuthenticationController.finishLogin(
  1104. this.user,
  1105. this.req,
  1106. this.res,
  1107. err => {
  1108. expect(err).to.not.be.oneOf([null, undefined])
  1109. expect(err).to.be.instanceof(Error)
  1110. done()
  1111. }
  1112. )
  1113. })
  1114. it('should not call UserSessionsManager.trackSession', function(done) {
  1115. this.AuthenticationController.finishLogin(
  1116. this.user,
  1117. this.req,
  1118. this.res,
  1119. err => {
  1120. expect(err).to.exist
  1121. this.UserSessionsManager.trackSession.callCount.should.equal(0)
  1122. done()
  1123. }
  1124. )
  1125. })
  1126. })
  1127. })
  1128. describe('_loginAsyncHandlers', function() {
  1129. beforeEach(function() {
  1130. this.AuthenticationController.finishLogin(
  1131. this.user,
  1132. this.req,
  1133. this.res,
  1134. this.next
  1135. )
  1136. })
  1137. it('should call identifyUser', function() {
  1138. this.AnalyticsManager.identifyUser
  1139. .calledWith(this.user._id, this.req.sessionID)
  1140. .should.equal(true)
  1141. })
  1142. it('should setup the user data in the background', function() {
  1143. this.UserHandler.setupLoginData.calledWith(this.user).should.equal(true)
  1144. })
  1145. it('should set res.session.justLoggedIn', function() {
  1146. this.req.session.justLoggedIn.should.equal(true)
  1147. })
  1148. it('should record the successful login', function() {
  1149. this.AuthenticationController._recordSuccessfulLogin
  1150. .calledWith(this.user._id)
  1151. .should.equal(true)
  1152. })
  1153. it('should tell the rate limiter that there was a success for that email', function() {
  1154. this.LoginRateLimiter.recordSuccessfulLogin
  1155. .calledWith(this.user.email)
  1156. .should.equal(true)
  1157. })
  1158. it('should log the successful login', function() {
  1159. this.logger.log
  1160. .calledWith(
  1161. { email: this.user.email, user_id: this.user._id.toString() },
  1162. 'successful log in'
  1163. )
  1164. .should.equal(true)
  1165. })
  1166. it('should track the login event', function() {
  1167. this.AnalyticsManager.recordEvent
  1168. .calledWith(this.user._id, 'user-logged-in')
  1169. .should.equal(true)
  1170. })
  1171. })
  1172. })
  1173. })