AuthenticationControllerTests.js 35 KB

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