AuthenticationControllerTests.coffee 28 KB

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