AuthenticationControllerTests.coffee 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. sinon = require('sinon')
  2. chai = require('chai')
  3. sinonChai = require "sinon-chai"
  4. chai.use sinonChai
  5. should = chai.should()
  6. expect = chai.expect
  7. modulePath = "../../../../app/js/Features/Authentication/AuthenticationController.js"
  8. SandboxedModule = require('sandboxed-module')
  9. events = require "events"
  10. tk = require("timekeeper")
  11. MockRequest = require("../helpers/MockRequest")
  12. MockResponse = require("../helpers/MockResponse")
  13. ObjectId = require("mongojs").ObjectId
  14. describe "AuthenticationController", ->
  15. beforeEach ->
  16. tk.freeze(Date.now())
  17. @UserModel = findOne: sinon.stub()
  18. @AuthenticationController = SandboxedModule.require modulePath, requires:
  19. "./AuthenticationManager": @AuthenticationManager = {}
  20. "../User/UserUpdater" : @UserUpdater = {updateUser:sinon.stub()}
  21. "metrics-sharelatex": @Metrics = { inc: sinon.stub() }
  22. "../Security/LoginRateLimiter": @LoginRateLimiter = { processLoginRequest:sinon.stub(), recordSuccessfulLogin:sinon.stub() }
  23. "../User/UserHandler": @UserHandler = {setupLoginData:sinon.stub()}
  24. "../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() }
  25. "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), err: sinon.stub() }
  26. "settings-sharelatex": { siteUrl: 'http://www.foo.bar' }
  27. "passport": @passport =
  28. authenticate: sinon.stub().returns(sinon.stub())
  29. "../User/UserSessionsManager": @UserSessionsManager =
  30. trackSession: sinon.stub()
  31. untrackSession: sinon.stub()
  32. revokeAllUserSessions: sinon.stub().callsArgWith(1, null)
  33. "../../infrastructure/Modules": @Modules = {hooks: {fire: sinon.stub().callsArgWith(2, null, [])}}
  34. "../SudoMode/SudoModeHandler": @SudoModeHandler = {activateSudoMode: sinon.stub().callsArgWith(1, null)}
  35. "../Notifications/NotificationsBuilder": @NotificationsBuilder =
  36. ipMatcherAffiliation: sinon.stub()
  37. "../V1/V1Api": @V1Api = request: sinon.stub()
  38. "../../models/User": { User: @UserModel }
  39. "../../../../modules/oauth2-server/app/js/Oauth2Server": @Oauth2Server =
  40. Request: sinon.stub()
  41. Response: sinon.stub()
  42. server: authenticate: sinon.stub()
  43. @user =
  44. _id: ObjectId()
  45. email: @email = "USER@example.com"
  46. first_name: "bob"
  47. last_name: "brown"
  48. referal_id: 1234
  49. isAdmin: false
  50. @password = "banana"
  51. @req = new MockRequest()
  52. @res = new MockResponse()
  53. @callback = @next = sinon.stub()
  54. afterEach ->
  55. tk.reset()
  56. describe 'isUserLoggedIn', () ->
  57. beforeEach ->
  58. @stub = sinon.stub(@AuthenticationController, 'getLoggedInUserId')
  59. afterEach ->
  60. @stub.restore()
  61. it 'should do the right thing in all cases', () ->
  62. @AuthenticationController.getLoggedInUserId.returns('some_id')
  63. expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal true
  64. @AuthenticationController.getLoggedInUserId.returns(null)
  65. expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false
  66. @AuthenticationController.getLoggedInUserId.returns(false)
  67. expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false
  68. @AuthenticationController.getLoggedInUserId.returns(undefined)
  69. expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false
  70. describe 'setInSessionUser', () ->
  71. beforeEach ->
  72. @user = {
  73. _id: 'id'
  74. first_name: 'a'
  75. last_name: 'b'
  76. email: 'c'
  77. }
  78. @req.session.passport = {user: @user}
  79. @req.session.user = @user
  80. it 'should update the right properties', () ->
  81. @AuthenticationController.setInSessionUser(@req, {first_name: 'new_first_name', email: 'new_email'})
  82. expectedUser = {
  83. _id: 'id'
  84. first_name: 'new_first_name'
  85. last_name: 'b'
  86. email: 'new_email'
  87. }
  88. expect(@req.session.passport.user).to.deep.equal(expectedUser)
  89. expect(@req.session.user).to.deep.equal(expectedUser)
  90. describe 'passportLogin', ->
  91. beforeEach ->
  92. @info = null
  93. @req.login = sinon.stub().callsArgWith(1, null)
  94. @res.json = sinon.stub()
  95. @req.session = @session = {
  96. passport: {user: @user},
  97. postLoginRedirect: "/path/to/redir/to"
  98. }
  99. @req.session.destroy = sinon.stub().callsArgWith(0, null)
  100. @req.session.save = sinon.stub().callsArgWith(0, null)
  101. @req.sessionStore = {generate: sinon.stub()}
  102. @AuthenticationController.finishLogin = sinon.stub()
  103. @passport.authenticate.callsArgWith(1, null, @user, @info)
  104. @err = new Error('woops')
  105. it 'should call passport.authenticate', () ->
  106. @AuthenticationController.passportLogin @req, @res, @next
  107. @passport.authenticate.callCount.should.equal 1
  108. describe 'when authenticate produces an error', ->
  109. beforeEach ->
  110. @passport.authenticate.callsArgWith(1, @err)
  111. it 'should return next with an error', () ->
  112. @AuthenticationController.passportLogin @req, @res, @next
  113. @next.calledWith(@err).should.equal true
  114. describe 'when authenticate produces a user', ->
  115. beforeEach ->
  116. @req.session.postLoginRedirect = 'some_redirect'
  117. @passport.authenticate.callsArgWith(1, null, @user, @info)
  118. afterEach ->
  119. delete @req.session.postLoginRedirect
  120. it 'should call finishLogin', () ->
  121. @AuthenticationController.passportLogin @req, @res, @next
  122. @AuthenticationController.finishLogin.callCount.should.equal 1
  123. @AuthenticationController.finishLogin.calledWith(@user).should.equal true
  124. describe 'when authenticate does not produce a user', ->
  125. beforeEach ->
  126. @info = {text: 'a', type: 'b'}
  127. @passport.authenticate.callsArgWith(1, null, false, @info)
  128. it 'should not call finishLogin', () ->
  129. @AuthenticationController.passportLogin @req, @res, @next
  130. @AuthenticationController.finishLogin.callCount.should.equal 0
  131. it 'should not send a json response with redirect', () ->
  132. @AuthenticationController.passportLogin @req, @res, @next
  133. @res.json.callCount.should.equal 1
  134. @res.json.calledWith({message: @info}).should.equal true
  135. expect(@res.json.lastCall.args[0].redir?).to.equal false
  136. describe 'afterLoginSessionSetup', ->
  137. beforeEach ->
  138. @req.login = sinon.stub().callsArgWith(1, null)
  139. @req.session = @session = {passport: {user: @user}}
  140. @req.session =
  141. passport: {user: {_id: "one"}}
  142. @req.session.destroy = sinon.stub().callsArgWith(0, null)
  143. @req.session.save = sinon.stub().callsArgWith(0, null)
  144. @req.sessionStore = {generate: sinon.stub()}
  145. @UserSessionsManager.trackSession = sinon.stub()
  146. @call = (callback) =>
  147. @AuthenticationController.afterLoginSessionSetup @req, @user, callback
  148. it 'should not produce an error', (done) ->
  149. @call (err) =>
  150. expect(err).to.equal null
  151. done()
  152. it 'should call req.login', (done) ->
  153. @call (err) =>
  154. @req.login.callCount.should.equal 1
  155. done()
  156. it 'should call req.session.save', (done) ->
  157. @call (err) =>
  158. @req.session.save.callCount.should.equal 1
  159. done()
  160. it 'should call UserSessionsManager.trackSession', (done) ->
  161. @call (err) =>
  162. @UserSessionsManager.trackSession.callCount.should.equal 1
  163. done()
  164. describe 'when req.session.save produces an error', ->
  165. beforeEach ->
  166. @req.session.save = sinon.stub().callsArgWith(0, new Error('woops'))
  167. it 'should produce an error', (done) ->
  168. @call (err) =>
  169. expect(err).to.not.be.oneOf [null, undefined]
  170. expect(err).to.be.instanceof Error
  171. done()
  172. it 'should not call UserSessionsManager.trackSession', (done) ->
  173. @call (err) =>
  174. @UserSessionsManager.trackSession.callCount.should.equal 0
  175. done()
  176. describe 'getSessionUser', ->
  177. it 'should get the user object from session', ->
  178. @req.session =
  179. passport:
  180. user: {_id: 'one'}
  181. user = @AuthenticationController.getSessionUser(@req)
  182. expect(user).to.deep.equal {_id: 'one'}
  183. it 'should work with legacy sessions', ->
  184. @req.session =
  185. user: {_id: 'one'}
  186. user = @AuthenticationController.getSessionUser(@req)
  187. expect(user).to.deep.equal {_id: 'one'}
  188. describe "doPassportLogin", ->
  189. beforeEach ->
  190. @AuthenticationController._recordFailedLogin = sinon.stub()
  191. @AuthenticationController._recordSuccessfulLogin = sinon.stub()
  192. @Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [])
  193. # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  194. @req.body =
  195. email: @email
  196. password: @password
  197. session:
  198. postLoginRedirect: "/path/to/redir/to"
  199. @cb = sinon.stub()
  200. describe "when the preDoPassportLogin hooks produce an info object", ->
  201. beforeEach ->
  202. @Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [null, {redir: '/somewhere'}, null])
  203. it "should stop early and call done with this info object", (done) ->
  204. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  205. @cb.callCount.should.equal 1
  206. @cb.calledWith(null, false, {redir: '/somewhere'}).should.equal true
  207. @LoginRateLimiter.processLoginRequest.callCount.should.equal 0
  208. done()
  209. describe "when the users rate limit", ->
  210. beforeEach ->
  211. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  212. it "should block the request if the limit has been exceeded", (done)->
  213. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  214. @cb.callCount.should.equal 1
  215. @cb.calledWith(null, null).should.equal true
  216. done()
  217. describe 'when the user is authenticated', ->
  218. beforeEach ->
  219. @cb = sinon.stub()
  220. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  221. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  222. @req.sessionID = Math.random()
  223. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  224. it "should attempt to authorise the user", ->
  225. @AuthenticationManager.authenticate
  226. .calledWith(email: @email.toLowerCase(), @password)
  227. .should.equal true
  228. it "should establish the user's session", ->
  229. @cb.calledWith(null, @user).should.equal true
  230. describe '_loginAsyncHandlers', ->
  231. beforeEach ->
  232. @UserHandler.setupLoginData = sinon.stub()
  233. @LoginRateLimiter.recordSuccessfulLogin = sinon.stub()
  234. @AuthenticationController._recordSuccessfulLogin = sinon.stub()
  235. @AnalyticsManager.recordEvent = sinon.stub()
  236. @AnalyticsManager.identifyUser = sinon.stub()
  237. @AuthenticationController._loginAsyncHandlers(@req, @user)
  238. it "should call identifyUser", ->
  239. @AnalyticsManager.identifyUser.calledWith(@user._id, @req.sessionID).should.equal true
  240. it "should setup the user data in the background", ->
  241. @UserHandler.setupLoginData.calledWith(@user).should.equal true
  242. it "should set res.session.justLoggedIn", ->
  243. @req.session.justLoggedIn.should.equal true
  244. it "should record the successful login", ->
  245. @AuthenticationController._recordSuccessfulLogin
  246. .calledWith(@user._id)
  247. .should.equal true
  248. it "should tell the rate limiter that there was a success for that email", ->
  249. @LoginRateLimiter.recordSuccessfulLogin.calledWith(@user.email).should.equal true
  250. it "should log the successful login", ->
  251. @logger.log
  252. .calledWith(email: @user.email, user_id: @user._id.toString(), "successful log in")
  253. .should.equal true
  254. it "should track the login event", ->
  255. @AnalyticsManager.recordEvent
  256. .calledWith(@user._id, "user-logged-in")
  257. .should.equal true
  258. describe 'when the user is not authenticated', ->
  259. beforeEach ->
  260. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  261. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null)
  262. @cb = sinon.stub()
  263. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  264. it "should not establish the login", ->
  265. @cb.callCount.should.equal 1
  266. @cb.calledWith(null, false)
  267. # @res.body.should.exist
  268. expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type']
  269. # message:
  270. # text: 'Your email or password were incorrect. Please try again',
  271. # type: 'error'
  272. it "should not setup the user data in the background", ->
  273. @UserHandler.setupLoginData.called.should.equal false
  274. it "should record a failed login", ->
  275. @AuthenticationController._recordFailedLogin.called.should.equal true
  276. it "should log the failed login", ->
  277. @logger.log
  278. .calledWith(email: @email.toLowerCase(), "failed log in")
  279. .should.equal true
  280. describe "getLoggedInUserId", ->
  281. beforeEach ->
  282. @req =
  283. session :{}
  284. it "should return the user id from the session", ()->
  285. @user_id = "2134"
  286. @req.session.user =
  287. _id:@user_id
  288. result = @AuthenticationController.getLoggedInUserId @req
  289. expect(result).to.equal @user_id
  290. it 'should return user for passport session', () ->
  291. @user_id = "2134"
  292. @req.session = {
  293. passport: {
  294. user: {
  295. _id:@user_id
  296. }
  297. }
  298. }
  299. result = @AuthenticationController.getLoggedInUserId @req
  300. expect(result).to.equal @user_id
  301. it "should return null if there is no user on the session", ()->
  302. result = @AuthenticationController.getLoggedInUserId @req
  303. expect(result).to.equal null
  304. it "should return null if there is no session", ()->
  305. @req = {}
  306. result = @AuthenticationController.getLoggedInUserId @req
  307. expect(result).to.equal null
  308. it "should return null if there is no req", ()->
  309. @req = {}
  310. result = @AuthenticationController.getLoggedInUserId @req
  311. expect(result).to.equal null
  312. describe "requireLogin", ->
  313. beforeEach ->
  314. @user =
  315. _id: "user-id-123"
  316. email: "user@sharelatex.com"
  317. @middleware = @AuthenticationController.requireLogin()
  318. describe "when the user is logged in", ->
  319. beforeEach ->
  320. @req.session =
  321. user: @user = {
  322. _id: "user-id-123"
  323. email: "user@sharelatex.com"
  324. }
  325. @middleware(@req, @res, @next)
  326. it "should call the next method in the chain", ->
  327. @next.called.should.equal true
  328. describe "when the user is not logged in", ->
  329. beforeEach ->
  330. @req.session = {}
  331. @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  332. @req.query = {}
  333. @middleware(@req, @res, @next)
  334. it "should redirect to the register or login page", ->
  335. @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true
  336. describe "requireOauth", ->
  337. beforeEach ->
  338. @res.sendStatus = sinon.stub()
  339. @res.send = sinon.stub()
  340. @res.status = sinon.stub().returns(@res)
  341. @middleware = @AuthenticationController.requireOauth()
  342. describe "when Oauth2Server authenticates", ->
  343. beforeEach ->
  344. @token =
  345. accessToken: "token"
  346. user: "user"
  347. @Oauth2Server.server.authenticate.yields null, @token
  348. @middleware(@req, @res, @next)
  349. it "should set oauth_token on request", ->
  350. @req.oauth_token.should.equal @token
  351. it "should set oauth on request", ->
  352. @req.oauth.access_token.should.equal @token.accessToken
  353. it "should set oauth_user on request", ->
  354. @req.oauth_user.should.equal "user"
  355. it "should call next", ->
  356. @next.should.have.been.calledOnce
  357. describe "when Oauth2Server does not authenticate", ->
  358. beforeEach ->
  359. @Oauth2Server.server.authenticate.yields code: 401
  360. describe "when token not provided", ->
  361. beforeEach ->
  362. @middleware(@req, @res, @next)
  363. it "should return 401 error", ->
  364. @res.sendStatus.should.have.been.calledWith 401
  365. describe "when token provided", ->
  366. beforeEach ->
  367. @V1Api.request = sinon.stub().yields("error", {}, {})
  368. @req.token = "foo"
  369. @middleware(@req, @res, @next)
  370. it "should make request to v1 api with token", ->
  371. @V1Api.request.should.have.been.calledWith {
  372. expectedStatusCodes: [401]
  373. json: token: "foo"
  374. method: "POST"
  375. uri: "/api/v1/sharelatex/oauth_authorize"
  376. }
  377. describe "when v1 api returns error", ->
  378. beforeEach ->
  379. @V1Api.request = sinon.stub().yields("error", {}, {})
  380. @req.token = "foo"
  381. @middleware(@req, @res, @next)
  382. it "should return status", ->
  383. @next.should.have.been.calledWith "error"
  384. describe "when v1 api status code is not 200", ->
  385. beforeEach ->
  386. @V1Api.request = sinon.stub().yields(null, {statusCode: 401}, {})
  387. @req.token = "foo"
  388. @middleware(@req, @res, @next)
  389. it "should return status", ->
  390. @res.status.should.have.been.calledWith 401
  391. describe "when v1 api returns authorized profile and access token", ->
  392. beforeEach ->
  393. @oauth_authorize =
  394. access_token: "access_token"
  395. user_profile: id: "overleaf-id"
  396. @V1Api.request = sinon.stub().yields(null, {statusCode: 200}, @oauth_authorize)
  397. @req.token = "foo"
  398. describe "in all cases", ->
  399. beforeEach ->
  400. @middleware(@req, @res, @next)
  401. it "should find user", ->
  402. @UserModel.findOne.should.have.been.calledWithMatch { "overleaf.id": "overleaf-id" }
  403. describe "when user find returns error", ->
  404. beforeEach ->
  405. @UserModel.findOne = sinon.stub().yields("error")
  406. @middleware(@req, @res, @next)
  407. it "should return error", ->
  408. @next.should.have.been.calledWith "error"
  409. describe "when user is not found", ->
  410. beforeEach ->
  411. @UserModel.findOne = sinon.stub().yields(null, null)
  412. @middleware(@req, @res, @next)
  413. it "should return unauthorized", ->
  414. @res.status.should.have.been.calledWith 401
  415. describe "when user is found", ->
  416. beforeEach ->
  417. @UserModel.findOne = sinon.stub().yields(null, "user")
  418. @middleware(@req, @res, @next)
  419. it "should add user to request", ->
  420. @req.oauth_user.should.equal "user"
  421. it "should add access_token to request", ->
  422. @req.oauth.access_token.should.equal "access_token"
  423. describe "requireGlobalLogin", ->
  424. beforeEach ->
  425. @req.headers = {}
  426. @AuthenticationController.httpAuth = sinon.stub()
  427. @setRedirect = sinon.spy(@AuthenticationController, 'setRedirectInSession')
  428. afterEach ->
  429. @setRedirect.restore()
  430. describe "with white listed url", ->
  431. beforeEach ->
  432. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  433. @req._parsedUrl.pathname = "/login"
  434. @AuthenticationController.requireGlobalLogin @req, @res, @next
  435. it "should call next() directly", ->
  436. @next.called.should.equal true
  437. describe "with white listed url and a query string", ->
  438. beforeEach ->
  439. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  440. @req._parsedUrl.pathname = "/login"
  441. @req.url = "/login?query=something"
  442. @AuthenticationController.requireGlobalLogin @req, @res, @next
  443. it "should call next() directly", ->
  444. @next.called.should.equal true
  445. describe "with http auth", ->
  446. beforeEach ->
  447. @req.headers["authorization"] = "Mock Basic Auth"
  448. @AuthenticationController.requireGlobalLogin @req, @res, @next
  449. it "should pass the request onto httpAuth", ->
  450. @AuthenticationController.httpAuth
  451. .calledWith(@req, @res, @next)
  452. .should.equal true
  453. describe "with a user session", ->
  454. beforeEach ->
  455. @req.session =
  456. user: {"mock": "user", "_id": "some_id"}
  457. @AuthenticationController.requireGlobalLogin @req, @res, @next
  458. it "should call next() directly", ->
  459. @next.called.should.equal true
  460. describe "with no login credentials", ->
  461. beforeEach ->
  462. @req.session = {}
  463. @AuthenticationController.requireGlobalLogin @req, @res, @next
  464. it 'should have called setRedirectInSession', ->
  465. @setRedirect.callCount.should.equal 1
  466. it "should redirect to the /login page", ->
  467. @res.redirectedTo.should.equal "/login"
  468. describe "_redirectToLoginOrRegisterPage", ->
  469. beforeEach ->
  470. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false })
  471. @req.session = {}
  472. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  473. @AuthenticationController._redirectToLoginPage = sinon.stub()
  474. @req.query = {}
  475. describe "they have come directly to the url", ->
  476. beforeEach ->
  477. @req.query = {}
  478. @middleware(@req, @res, @next)
  479. it "should redirect to the login page", ->
  480. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false
  481. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true
  482. describe "they have come via a templates link", ->
  483. beforeEach ->
  484. @req.query.zipUrl = "something"
  485. @middleware(@req, @res, @next)
  486. it "should redirect to the register page", ->
  487. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  488. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  489. describe "they have been invited to a project", ->
  490. beforeEach ->
  491. @req.query.project_name = "something"
  492. @middleware(@req, @res, @next)
  493. it "should redirect to the register page", ->
  494. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  495. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  496. describe "_redirectToRegisterPage", ->
  497. beforeEach ->
  498. @req.path = "/target/url"
  499. @req.query =
  500. extra_query: "foo"
  501. @AuthenticationController._redirectToRegisterPage(@req, @res)
  502. it "should redirect to the register page with a query string attached", ->
  503. @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo'
  504. @res.redirectedTo.should.equal "/register?extra_query=foo"
  505. it "should log out a message", ->
  506. @logger.log
  507. .calledWith(url: @url, "user not logged in so redirecting to register page")
  508. .should.equal true
  509. describe "_redirectToLoginPage", ->
  510. beforeEach ->
  511. @req.path = "/target/url"
  512. @req.query =
  513. extra_query: "foo"
  514. @AuthenticationController._redirectToLoginPage(@req, @res)
  515. it "should redirect to the register page with a query string attached", ->
  516. @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo'
  517. @res.redirectedTo.should.equal "/login?extra_query=foo"
  518. describe "_recordSuccessfulLogin", ->
  519. beforeEach ->
  520. @UserUpdater.updateUser = sinon.stub().callsArg(2)
  521. @AuthenticationController._recordSuccessfulLogin(@user._id, @callback)
  522. it "should increment the user.login.success metric", ->
  523. @Metrics.inc
  524. .calledWith("user.login.success")
  525. .should.equal true
  526. it "should update the user's login count and last logged in date", ->
  527. @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined
  528. @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1
  529. it "should call the callback", ->
  530. @callback.called.should.equal true
  531. describe "_recordFailedLogin", ->
  532. beforeEach ->
  533. @AuthenticationController._recordFailedLogin(@callback)
  534. it "should increment the user.login.failed metric", ->
  535. @Metrics.inc
  536. .calledWith("user.login.failed")
  537. .should.equal true
  538. it "should call the callback", ->
  539. @callback.called.should.equal true
  540. describe 'setRedirectInSession', ->
  541. beforeEach ->
  542. @req = {session: {}}
  543. @req.path = "/somewhere"
  544. @req.query = {one: "1"}
  545. it 'should set redirect property on session', ->
  546. @AuthenticationController.setRedirectInSession(@req)
  547. expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1"
  548. it 'should set the supplied value', ->
  549. @AuthenticationController.setRedirectInSession(@req, '/somewhere/specific')
  550. expect(@req.session.postLoginRedirect).to.equal "/somewhere/specific"
  551. it 'should not allow open redirects', ->
  552. @AuthenticationController.setRedirectInSession(@req, 'https://evil.com')
  553. expect(@req.session.postLoginRedirect).to.be.undefined
  554. describe 'with a png', ->
  555. beforeEach ->
  556. @req = {session: {}}
  557. it 'should not set the redirect', ->
  558. @AuthenticationController.setRedirectInSession(@req, '/something.png')
  559. expect(@req.session.postLoginRedirect).to.equal undefined
  560. describe 'with a js path', ->
  561. beforeEach ->
  562. @req = {session: {}}
  563. it 'should not set the redirect', ->
  564. @AuthenticationController.setRedirectInSession(@req, '/js/something.js')
  565. expect(@req.session.postLoginRedirect).to.equal undefined
  566. describe '_getRedirectFromSession', ->
  567. it 'should get redirect property from session', ->
  568. @req = session: { postLoginRedirect: '/a?b=c' }
  569. expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c"
  570. it 'should not allow open redirects', ->
  571. @req = session: { postLoginRedirect: 'https://evil.com' }
  572. expect(@AuthenticationController._getRedirectFromSession(@req)).to.be.null
  573. it 'handle null values', ->
  574. @req = session: {}
  575. expect(@AuthenticationController._getRedirectFromSession(@req)).to.be.null
  576. describe '_getSafeRedirectPath', ->
  577. it 'sanitize redirect path to prevent open redirects', ->
  578. expect(
  579. @AuthenticationController._getSafeRedirectPath('https://evil.com')
  580. ).to.be.undefined
  581. expect(
  582. @AuthenticationController._getSafeRedirectPath('//evil.com')
  583. ).to.be.undefined
  584. expect(
  585. @AuthenticationController._getSafeRedirectPath('//ol.com/evil')
  586. ).to.equal '/evil'
  587. expect(
  588. @AuthenticationController._getSafeRedirectPath('////evil.com')
  589. ).to.be.undefined
  590. expect(
  591. @AuthenticationController._getSafeRedirectPath('%2F%2Fevil.com')
  592. ).to.equal '/%2F%2Fevil.com'
  593. expect(
  594. @AuthenticationController._getSafeRedirectPath('.evil.com')
  595. ).to.equal '/.evil.com'
  596. describe '_clearRedirectFromSession', ->
  597. beforeEach ->
  598. @req = {session: {postLoginRedirect: "/a?b=c"}}
  599. it 'should remove the redirect property from session', ->
  600. @AuthenticationController._clearRedirectFromSession(@req)
  601. expect(@req.session.postLoginRedirect).to.equal undefined
  602. describe 'finishLogin', ->
  603. # - get redirect
  604. # - async handlers
  605. # - afterLoginSessionSetup
  606. # - clear redirect
  607. # - issue redir, two ways
  608. beforeEach ->
  609. @AuthenticationController._getRedirectFromSession = sinon.stub().returns '/some/page'
  610. @AuthenticationController._loginAsyncHandlers = sinon.stub()
  611. @AuthenticationController.afterLoginSessionSetup = sinon.stub().callsArgWith(2, null)
  612. @AuthenticationController._clearRedirectFromSession = sinon.stub()
  613. @AuthenticationController._redirectToReconfirmPage = sinon.stub()
  614. @req.headers = {accept: 'application/json, whatever'}
  615. @res.json = sinon.stub()
  616. @res.redirect = sinon.stub()
  617. it 'should extract the redirect from the session', () ->
  618. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  619. expect(@AuthenticationController._getRedirectFromSession.callCount).to.equal 1
  620. expect(@AuthenticationController._getRedirectFromSession.calledWith(@req)).to.equal true
  621. it 'should call the async handlers', () ->
  622. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  623. expect(@AuthenticationController._loginAsyncHandlers.callCount).to.equal 1
  624. expect(@AuthenticationController._loginAsyncHandlers.calledWith(@req, @user)).to.equal true
  625. it 'should call afterLoginSessionSetup', () ->
  626. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  627. expect(@AuthenticationController.afterLoginSessionSetup.callCount).to.equal 1
  628. expect(@AuthenticationController.afterLoginSessionSetup.calledWith(@req, @user)).to.equal true
  629. it 'should clear redirect from session', () ->
  630. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  631. expect(@AuthenticationController._clearRedirectFromSession.callCount).to.equal 1
  632. expect(@AuthenticationController._clearRedirectFromSession.calledWith(@req)).to.equal true
  633. it 'should issue a json response with a redirect', () ->
  634. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  635. expect(@res.json.callCount).to.equal 1
  636. expect(@res.redirect.callCount).to.equal 0
  637. expect(@res.json.calledWith({ redir: '/some/page' })).to.equal true
  638. describe 'with a non-json request', ->
  639. beforeEach ->
  640. @req.headers = {}
  641. @res.json = sinon.stub()
  642. @res.redirect = sinon.stub()
  643. it 'should issue a plain redirect', () ->
  644. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  645. expect(@res.json.callCount).to.equal 0
  646. expect(@res.redirect.callCount).to.equal 1
  647. expect(@res.redirect.calledWith('/some/page')).to.equal true
  648. describe "when user is flagged to reconfirm", ->
  649. beforeEach ->
  650. @req.session = {}
  651. @user.must_reconfirm = true
  652. it "should redirect to reconfirm page", () ->
  653. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  654. expect(@AuthenticationController._redirectToReconfirmPage.calledWith(@req)).to.equal true