AuthenticationControllerTests.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107
  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. describe('when req.session.save produces an error', function() {
  277. beforeEach(function() {
  278. this.req.session.save = sinon.stub().callsArgWith(0, new Error('woops'))
  279. })
  280. it('should produce an error', function(done) {
  281. this.call(err => {
  282. expect(err).to.not.be.oneOf([null, undefined])
  283. expect(err).to.be.instanceof(Error)
  284. done()
  285. })
  286. })
  287. it('should not call UserSessionsManager.trackSession', function(done) {
  288. this.call(err => {
  289. expect(err).to.exist
  290. this.UserSessionsManager.trackSession.callCount.should.equal(0)
  291. done()
  292. })
  293. })
  294. })
  295. })
  296. describe('doPassportLogin', function() {
  297. beforeEach(function() {
  298. this.AuthenticationController._recordFailedLogin = sinon.stub()
  299. this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
  300. this.Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [])
  301. // @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  302. this.req.body = {
  303. email: this.email,
  304. password: this.password,
  305. session: {
  306. postLoginRedirect: '/path/to/redir/to'
  307. }
  308. }
  309. this.cb = sinon.stub()
  310. })
  311. describe('when the preDoPassportLogin hooks produce an info object', function() {
  312. beforeEach(function() {
  313. this.Modules.hooks.fire = sinon
  314. .stub()
  315. .callsArgWith(3, null, [null, { redir: '/somewhere' }, null])
  316. })
  317. it('should stop early and call done with this info object', function(done) {
  318. this.AuthenticationController.doPassportLogin(
  319. this.req,
  320. this.req.body.email,
  321. this.req.body.password,
  322. this.cb
  323. )
  324. this.cb.callCount.should.equal(1)
  325. this.cb
  326. .calledWith(null, false, { redir: '/somewhere' })
  327. .should.equal(true)
  328. this.LoginRateLimiter.processLoginRequest.callCount.should.equal(0)
  329. done()
  330. })
  331. })
  332. describe('when the users rate limit', function() {
  333. beforeEach(function() {
  334. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  335. })
  336. it('should block the request if the limit has been exceeded', function(done) {
  337. this.AuthenticationController.doPassportLogin(
  338. this.req,
  339. this.req.body.email,
  340. this.req.body.password,
  341. this.cb
  342. )
  343. this.cb.callCount.should.equal(1)
  344. this.cb.calledWith(null, null).should.equal(true)
  345. done()
  346. })
  347. })
  348. describe('when the user is authenticated', function() {
  349. beforeEach(function() {
  350. this.cb = sinon.stub()
  351. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  352. this.AuthenticationManager.authenticate = sinon
  353. .stub()
  354. .callsArgWith(2, null, this.user)
  355. this.req.sessionID = Math.random()
  356. this.AuthenticationController.doPassportLogin(
  357. this.req,
  358. this.req.body.email,
  359. this.req.body.password,
  360. this.cb
  361. )
  362. })
  363. it('should attempt to authorise the user', function() {
  364. this.AuthenticationManager.authenticate
  365. .calledWith({ email: this.email.toLowerCase() }, this.password)
  366. .should.equal(true)
  367. })
  368. it("should establish the user's session", function() {
  369. this.cb.calledWith(null, this.user).should.equal(true)
  370. })
  371. })
  372. describe('_loginAsyncHandlers', function() {
  373. beforeEach(function() {
  374. this.UserHandler.setupLoginData = sinon.stub()
  375. this.LoginRateLimiter.recordSuccessfulLogin = sinon.stub()
  376. this.AuthenticationController._recordSuccessfulLogin = sinon.stub()
  377. this.AnalyticsManager.recordEvent = sinon.stub()
  378. this.AnalyticsManager.identifyUser = sinon.stub()
  379. this.AuthenticationController._loginAsyncHandlers(this.req, this.user)
  380. })
  381. it('should call identifyUser', function() {
  382. this.AnalyticsManager.identifyUser
  383. .calledWith(this.user._id, this.req.sessionID)
  384. .should.equal(true)
  385. })
  386. it('should setup the user data in the background', function() {
  387. this.UserHandler.setupLoginData.calledWith(this.user).should.equal(true)
  388. })
  389. it('should set res.session.justLoggedIn', function() {
  390. this.req.session.justLoggedIn.should.equal(true)
  391. })
  392. it('should record the successful login', function() {
  393. this.AuthenticationController._recordSuccessfulLogin
  394. .calledWith(this.user._id)
  395. .should.equal(true)
  396. })
  397. it('should tell the rate limiter that there was a success for that email', function() {
  398. this.LoginRateLimiter.recordSuccessfulLogin
  399. .calledWith(this.user.email)
  400. .should.equal(true)
  401. })
  402. it('should log the successful login', function() {
  403. this.logger.log
  404. .calledWith(
  405. { email: this.user.email, user_id: this.user._id.toString() },
  406. 'successful log in'
  407. )
  408. .should.equal(true)
  409. })
  410. it('should track the login event', function() {
  411. this.AnalyticsManager.recordEvent
  412. .calledWith(this.user._id, 'user-logged-in')
  413. .should.equal(true)
  414. })
  415. })
  416. describe('when the user is not authenticated', function() {
  417. beforeEach(function() {
  418. this.LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  419. this.AuthenticationManager.authenticate = sinon
  420. .stub()
  421. .callsArgWith(2, null, null)
  422. this.cb = sinon.stub()
  423. this.AuthenticationController.doPassportLogin(
  424. this.req,
  425. this.req.body.email,
  426. this.req.body.password,
  427. this.cb
  428. )
  429. })
  430. it('should not establish the login', function() {
  431. this.cb.callCount.should.equal(1)
  432. this.cb.calledWith(null, false)
  433. // @res.body.should.exist
  434. expect(this.cb.lastCall.args[2]).to.contain.all.keys(['text', 'type'])
  435. })
  436. // message:
  437. // text: 'Your email or password were incorrect. Please try again',
  438. // type: 'error'
  439. it('should not setup the user data in the background', function() {
  440. this.UserHandler.setupLoginData.called.should.equal(false)
  441. })
  442. it('should record a failed login', function() {
  443. this.AuthenticationController._recordFailedLogin.called.should.equal(
  444. true
  445. )
  446. })
  447. it('should log the failed login', function() {
  448. this.logger.log
  449. .calledWith({ email: this.email.toLowerCase() }, 'failed log in')
  450. .should.equal(true)
  451. })
  452. })
  453. })
  454. describe('getLoggedInUserId', function() {
  455. beforeEach(function() {
  456. this.req = { session: {} }
  457. })
  458. it('should return the user id from the session', function() {
  459. this.user_id = '2134'
  460. this.req.session.user = { _id: this.user_id }
  461. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  462. expect(result).to.equal(this.user_id)
  463. })
  464. it('should return user for passport session', function() {
  465. this.user_id = '2134'
  466. this.req.session = {
  467. passport: {
  468. user: {
  469. _id: this.user_id
  470. }
  471. }
  472. }
  473. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  474. expect(result).to.equal(this.user_id)
  475. })
  476. it('should return null if there is no user on the session', function() {
  477. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  478. expect(result).to.equal(null)
  479. })
  480. it('should return null if there is no session', function() {
  481. this.req = {}
  482. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  483. expect(result).to.equal(null)
  484. })
  485. it('should return null if there is no req', function() {
  486. this.req = {}
  487. const result = this.AuthenticationController.getLoggedInUserId(this.req)
  488. expect(result).to.equal(null)
  489. })
  490. })
  491. describe('requireLogin', function() {
  492. beforeEach(function() {
  493. this.user = {
  494. _id: 'user-id-123',
  495. email: 'user@sharelatex.com'
  496. }
  497. this.middleware = this.AuthenticationController.requireLogin()
  498. })
  499. describe('when the user is logged in', function() {
  500. beforeEach(function() {
  501. this.req.session = {
  502. user: (this.user = {
  503. _id: 'user-id-123',
  504. email: 'user@sharelatex.com'
  505. })
  506. }
  507. this.middleware(this.req, this.res, this.next)
  508. })
  509. it('should call the next method in the chain', function() {
  510. this.next.called.should.equal(true)
  511. })
  512. })
  513. describe('when the user is not logged in', function() {
  514. beforeEach(function() {
  515. this.req.session = {}
  516. this.AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  517. this.req.query = {}
  518. this.middleware(this.req, this.res, this.next)
  519. })
  520. it('should redirect to the register or login page', function() {
  521. this.AuthenticationController._redirectToLoginOrRegisterPage
  522. .calledWith(this.req, this.res)
  523. .should.equal(true)
  524. })
  525. })
  526. })
  527. describe('requireOauth', function() {
  528. beforeEach(function() {
  529. this.res.send = sinon.stub()
  530. this.res.status = sinon.stub().returns(this.res)
  531. this.res.sendStatus = sinon.stub()
  532. this.middleware = this.AuthenticationController.requireOauth()
  533. })
  534. describe('when Oauth2Server authenticates', function() {
  535. beforeEach(function() {
  536. this.token = {
  537. accessToken: 'token',
  538. user: 'user'
  539. }
  540. this.Oauth2Server.server.authenticate.yields(null, this.token)
  541. this.middleware(this.req, this.res, this.next)
  542. })
  543. it('should set oauth_token on request', function() {
  544. this.req.oauth_token.should.equal(this.token)
  545. })
  546. it('should set oauth on request', function() {
  547. this.req.oauth.access_token.should.equal(this.token.accessToken)
  548. })
  549. it('should set oauth_user on request', function() {
  550. this.req.oauth_user.should.equal('user')
  551. })
  552. it('should call next', function() {
  553. this.next.should.have.been.calledOnce
  554. })
  555. })
  556. describe('when Oauth2Server returns 401 error', function() {
  557. beforeEach(function() {
  558. this.Oauth2Server.server.authenticate.yields({ code: 401 })
  559. this.middleware(this.req, this.res, this.next)
  560. })
  561. it('should return 401 error', function() {
  562. this.res.status.should.have.been.calledWith(401)
  563. })
  564. it('should not call next', function() {
  565. this.next.should.have.not.been.calledOnce
  566. })
  567. })
  568. })
  569. describe('requireGlobalLogin', function() {
  570. beforeEach(function() {
  571. this.req.headers = {}
  572. this.AuthenticationController.httpAuth = sinon.stub()
  573. this.setRedirect = sinon.spy(
  574. this.AuthenticationController,
  575. 'setRedirectInSession'
  576. )
  577. })
  578. afterEach(function() {
  579. this.setRedirect.restore()
  580. })
  581. describe('with white listed url', function() {
  582. beforeEach(function() {
  583. this.AuthenticationController.addEndpointToLoginWhitelist('/login')
  584. this.req._parsedUrl.pathname = '/login'
  585. this.AuthenticationController.requireGlobalLogin(
  586. this.req,
  587. this.res,
  588. this.next
  589. )
  590. })
  591. it('should call next() directly', function() {
  592. this.next.called.should.equal(true)
  593. })
  594. })
  595. describe('with white listed url and a query string', function() {
  596. beforeEach(function() {
  597. this.AuthenticationController.addEndpointToLoginWhitelist('/login')
  598. this.req._parsedUrl.pathname = '/login'
  599. this.req.url = '/login?query=something'
  600. this.AuthenticationController.requireGlobalLogin(
  601. this.req,
  602. this.res,
  603. this.next
  604. )
  605. })
  606. it('should call next() directly', function() {
  607. this.next.called.should.equal(true)
  608. })
  609. })
  610. describe('with http auth', function() {
  611. beforeEach(function() {
  612. this.req.headers['authorization'] = 'Mock Basic Auth'
  613. this.AuthenticationController.requireGlobalLogin(
  614. this.req,
  615. this.res,
  616. this.next
  617. )
  618. })
  619. it('should pass the request onto httpAuth', function() {
  620. this.AuthenticationController.httpAuth
  621. .calledWith(this.req, this.res, this.next)
  622. .should.equal(true)
  623. })
  624. })
  625. describe('with a user session', function() {
  626. beforeEach(function() {
  627. this.req.session = { user: { mock: 'user', _id: 'some_id' } }
  628. this.AuthenticationController.requireGlobalLogin(
  629. this.req,
  630. this.res,
  631. this.next
  632. )
  633. })
  634. it('should call next() directly', function() {
  635. this.next.called.should.equal(true)
  636. })
  637. })
  638. describe('with no login credentials', function() {
  639. beforeEach(function() {
  640. this.req.session = {}
  641. this.AuthenticationController.requireGlobalLogin(
  642. this.req,
  643. this.res,
  644. this.next
  645. )
  646. })
  647. it('should have called setRedirectInSession', function() {
  648. this.setRedirect.callCount.should.equal(1)
  649. })
  650. it('should redirect to the /login page', function() {
  651. this.res.redirectedTo.should.equal('/login')
  652. })
  653. })
  654. })
  655. describe('_redirectToLoginOrRegisterPage', function() {
  656. beforeEach(function() {
  657. this.middleware = this.AuthenticationController.requireLogin(
  658. (this.options = { load_from_db: false })
  659. )
  660. this.req.session = {}
  661. this.AuthenticationController._redirectToRegisterPage = sinon.stub()
  662. this.AuthenticationController._redirectToLoginPage = sinon.stub()
  663. this.req.query = {}
  664. })
  665. describe('they have come directly to the url', function() {
  666. beforeEach(function() {
  667. this.req.query = {}
  668. this.middleware(this.req, this.res, this.next)
  669. })
  670. it('should redirect to the login page', function() {
  671. this.AuthenticationController._redirectToRegisterPage
  672. .calledWith(this.req, this.res)
  673. .should.equal(false)
  674. this.AuthenticationController._redirectToLoginPage
  675. .calledWith(this.req, this.res)
  676. .should.equal(true)
  677. })
  678. })
  679. describe('they have come via a templates link', function() {
  680. beforeEach(function() {
  681. this.req.query.zipUrl = 'something'
  682. this.middleware(this.req, this.res, this.next)
  683. })
  684. it('should redirect to the register page', function() {
  685. this.AuthenticationController._redirectToRegisterPage
  686. .calledWith(this.req, this.res)
  687. .should.equal(true)
  688. this.AuthenticationController._redirectToLoginPage
  689. .calledWith(this.req, this.res)
  690. .should.equal(false)
  691. })
  692. })
  693. describe('they have been invited to a project', function() {
  694. beforeEach(function() {
  695. this.req.query.project_name = 'something'
  696. this.middleware(this.req, this.res, this.next)
  697. })
  698. it('should redirect to the register page', function() {
  699. this.AuthenticationController._redirectToRegisterPage
  700. .calledWith(this.req, this.res)
  701. .should.equal(true)
  702. this.AuthenticationController._redirectToLoginPage
  703. .calledWith(this.req, this.res)
  704. .should.equal(false)
  705. })
  706. })
  707. })
  708. describe('_redirectToRegisterPage', function() {
  709. beforeEach(function() {
  710. this.req.path = '/target/url'
  711. this.req.query = { extra_query: 'foo' }
  712. this.AuthenticationController._redirectToRegisterPage(this.req, this.res)
  713. })
  714. it('should redirect to the register page with a query string attached', function() {
  715. this.req.session.postLoginRedirect.should.equal(
  716. '/target/url?extra_query=foo'
  717. )
  718. this.res.redirectedTo.should.equal('/register?extra_query=foo')
  719. })
  720. it('should log out a message', function() {
  721. this.logger.log
  722. .calledWith(
  723. { url: this.url },
  724. 'user not logged in so redirecting to register page'
  725. )
  726. .should.equal(true)
  727. })
  728. })
  729. describe('_redirectToLoginPage', function() {
  730. beforeEach(function() {
  731. this.req.path = '/target/url'
  732. this.req.query = { extra_query: 'foo' }
  733. this.AuthenticationController._redirectToLoginPage(this.req, this.res)
  734. })
  735. it('should redirect to the register page with a query string attached', function() {
  736. this.req.session.postLoginRedirect.should.equal(
  737. '/target/url?extra_query=foo'
  738. )
  739. this.res.redirectedTo.should.equal('/login?extra_query=foo')
  740. })
  741. })
  742. describe('_recordSuccessfulLogin', function() {
  743. beforeEach(function() {
  744. this.UserUpdater.updateUser = sinon.stub().callsArg(2)
  745. this.AuthenticationController._recordSuccessfulLogin(
  746. this.user._id,
  747. this.callback
  748. )
  749. })
  750. it('should increment the user.login.success metric', function() {
  751. this.Metrics.inc.calledWith('user.login.success').should.equal(true)
  752. })
  753. it("should update the user's login count and last logged in date", function() {
  754. this.UserUpdater.updateUser.args[0][1]['$set'][
  755. 'lastLoggedIn'
  756. ].should.not.equal(undefined)
  757. this.UserUpdater.updateUser.args[0][1]['$inc']['loginCount'].should.equal(
  758. 1
  759. )
  760. })
  761. it('should call the callback', function() {
  762. this.callback.called.should.equal(true)
  763. })
  764. })
  765. describe('_recordFailedLogin', function() {
  766. beforeEach(function() {
  767. this.AuthenticationController._recordFailedLogin(this.callback)
  768. })
  769. it('should increment the user.login.failed metric', function() {
  770. this.Metrics.inc.calledWith('user.login.failed').should.equal(true)
  771. })
  772. it('should call the callback', function() {
  773. this.callback.called.should.equal(true)
  774. })
  775. })
  776. describe('setRedirectInSession', function() {
  777. beforeEach(function() {
  778. this.req = { session: {} }
  779. this.req.path = '/somewhere'
  780. this.req.query = { one: '1' }
  781. })
  782. it('should set redirect property on session', function() {
  783. this.AuthenticationController.setRedirectInSession(this.req)
  784. expect(this.req.session.postLoginRedirect).to.equal('/somewhere?one=1')
  785. })
  786. it('should set the supplied value', function() {
  787. this.AuthenticationController.setRedirectInSession(
  788. this.req,
  789. '/somewhere/specific'
  790. )
  791. expect(this.req.session.postLoginRedirect).to.equal('/somewhere/specific')
  792. })
  793. it('should not allow open redirects', function() {
  794. this.AuthenticationController.setRedirectInSession(
  795. this.req,
  796. 'https://evil.com'
  797. )
  798. expect(this.req.session.postLoginRedirect).to.be.undefined
  799. })
  800. describe('with a png', function() {
  801. beforeEach(function() {
  802. this.req = { session: {} }
  803. })
  804. it('should not set the redirect', function() {
  805. this.AuthenticationController.setRedirectInSession(
  806. this.req,
  807. '/something.png'
  808. )
  809. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  810. })
  811. })
  812. describe('with a js path', function() {
  813. beforeEach(function() {
  814. this.req = { session: {} }
  815. })
  816. it('should not set the redirect', function() {
  817. this.AuthenticationController.setRedirectInSession(
  818. this.req,
  819. '/js/something.js'
  820. )
  821. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  822. })
  823. })
  824. })
  825. describe('_getRedirectFromSession', function() {
  826. it('should get redirect property from session', function() {
  827. this.req = { session: { postLoginRedirect: '/a?b=c' } }
  828. expect(
  829. this.AuthenticationController._getRedirectFromSession(this.req)
  830. ).to.equal('/a?b=c')
  831. })
  832. it('should not allow open redirects', function() {
  833. this.req = { session: { postLoginRedirect: 'https://evil.com' } }
  834. expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
  835. .be.null
  836. })
  837. it('handle null values', function() {
  838. this.req = { session: {} }
  839. expect(this.AuthenticationController._getRedirectFromSession(this.req)).to
  840. .be.null
  841. })
  842. })
  843. describe('_clearRedirectFromSession', function() {
  844. beforeEach(function() {
  845. this.req = { session: { postLoginRedirect: '/a?b=c' } }
  846. })
  847. it('should remove the redirect property from session', function() {
  848. this.AuthenticationController._clearRedirectFromSession(this.req)
  849. expect(this.req.session.postLoginRedirect).to.equal(undefined)
  850. })
  851. })
  852. describe('finishLogin', function() {
  853. // - get redirect
  854. // - async handlers
  855. // - afterLoginSessionSetup
  856. // - clear redirect
  857. // - issue redir, two ways
  858. beforeEach(function() {
  859. this.AuthenticationController._getRedirectFromSession = sinon
  860. .stub()
  861. .returns('/some/page')
  862. this.AuthenticationController._loginAsyncHandlers = sinon.stub()
  863. this.AuthenticationController.afterLoginSessionSetup = sinon
  864. .stub()
  865. .callsArgWith(2, null)
  866. this.AuthenticationController._clearRedirectFromSession = sinon.stub()
  867. this.AuthenticationController._redirectToReconfirmPage = sinon.stub()
  868. this.req.headers = { accept: 'application/json, whatever' }
  869. this.res.json = sinon.stub()
  870. this.res.redirect = sinon.stub()
  871. })
  872. it('should extract the redirect from the session', function() {
  873. this.AuthenticationController.finishLogin(
  874. this.user,
  875. this.req,
  876. this.res,
  877. this.next
  878. )
  879. expect(
  880. this.AuthenticationController._getRedirectFromSession.callCount
  881. ).to.equal(1)
  882. expect(
  883. this.AuthenticationController._getRedirectFromSession.calledWith(
  884. this.req
  885. )
  886. ).to.equal(true)
  887. })
  888. it('should call the async handlers', function() {
  889. this.AuthenticationController.finishLogin(
  890. this.user,
  891. this.req,
  892. this.res,
  893. this.next
  894. )
  895. expect(
  896. this.AuthenticationController._loginAsyncHandlers.callCount
  897. ).to.equal(1)
  898. expect(
  899. this.AuthenticationController._loginAsyncHandlers.calledWith(
  900. this.req,
  901. this.user
  902. )
  903. ).to.equal(true)
  904. })
  905. it('should call afterLoginSessionSetup', function() {
  906. this.AuthenticationController.finishLogin(
  907. this.user,
  908. this.req,
  909. this.res,
  910. this.next
  911. )
  912. expect(
  913. this.AuthenticationController.afterLoginSessionSetup.callCount
  914. ).to.equal(1)
  915. expect(
  916. this.AuthenticationController.afterLoginSessionSetup.calledWith(
  917. this.req,
  918. this.user
  919. )
  920. ).to.equal(true)
  921. })
  922. it('should clear redirect from session', function() {
  923. this.AuthenticationController.finishLogin(
  924. this.user,
  925. this.req,
  926. this.res,
  927. this.next
  928. )
  929. expect(
  930. this.AuthenticationController._clearRedirectFromSession.callCount
  931. ).to.equal(1)
  932. expect(
  933. this.AuthenticationController._clearRedirectFromSession.calledWith(
  934. this.req
  935. )
  936. ).to.equal(true)
  937. })
  938. it('should issue a json response with a redirect', function() {
  939. this.AuthenticationController.finishLogin(
  940. this.user,
  941. this.req,
  942. this.res,
  943. this.next
  944. )
  945. expect(this.res.json.callCount).to.equal(1)
  946. expect(this.res.redirect.callCount).to.equal(0)
  947. expect(this.res.json.calledWith({ redir: '/some/page' })).to.equal(true)
  948. })
  949. describe('with a non-json request', function() {
  950. beforeEach(function() {
  951. this.req.headers = {}
  952. this.res.json = sinon.stub()
  953. this.res.redirect = sinon.stub()
  954. })
  955. it('should issue a plain redirect', function() {
  956. this.AuthenticationController.finishLogin(
  957. this.user,
  958. this.req,
  959. this.res,
  960. this.next
  961. )
  962. expect(this.res.json.callCount).to.equal(0)
  963. expect(this.res.redirect.callCount).to.equal(1)
  964. expect(this.res.redirect.calledWith('/some/page')).to.equal(true)
  965. })
  966. })
  967. describe('when user is flagged to reconfirm', function() {
  968. beforeEach(function() {
  969. this.req.session = {}
  970. this.user.must_reconfirm = true
  971. })
  972. it('should redirect to reconfirm page', function() {
  973. this.AuthenticationController.finishLogin(
  974. this.user,
  975. this.req,
  976. this.res,
  977. this.next
  978. )
  979. expect(
  980. this.AuthenticationController._redirectToReconfirmPage.calledWith(
  981. this.req
  982. )
  983. ).to.equal(true)
  984. })
  985. })
  986. })
  987. })