AuthenticationControllerTests.js 36 KB

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