AuthenticationControllerTests.coffee 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  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. @res.sendStatus = sinon.stub()
  342. @middleware = @AuthenticationController.requireOauth()
  343. describe "when Oauth2Server authenticates", ->
  344. beforeEach ->
  345. @token =
  346. accessToken: "token"
  347. user: "user"
  348. @Oauth2Server.server.authenticate.yields null, @token
  349. @middleware(@req, @res, @next)
  350. it "should set oauth_token on request", ->
  351. @req.oauth_token.should.equal @token
  352. it "should set oauth on request", ->
  353. @req.oauth.access_token.should.equal @token.accessToken
  354. it "should set oauth_user on request", ->
  355. @req.oauth_user.should.equal "user"
  356. it "should call next", ->
  357. @next.should.have.been.calledOnce
  358. describe "when Oauth2Server does not authenticate", ->
  359. beforeEach ->
  360. @Oauth2Server.server.authenticate.yields code: 401
  361. describe "when token not provided", ->
  362. beforeEach ->
  363. @middleware(@req, @res, @next)
  364. it "should return 401 error", ->
  365. @res.sendStatus.should.have.been.calledWith 401
  366. describe "when token provided", ->
  367. beforeEach ->
  368. @V1Api.request = sinon.stub().yields("error", {}, {})
  369. @req.token = "foo"
  370. @middleware(@req, @res, @next)
  371. it "should make request to v1 api with token", ->
  372. @V1Api.request.should.have.been.calledWith {
  373. expectedStatusCodes: [401]
  374. json: token: "foo"
  375. method: "POST"
  376. uri: "/api/v1/sharelatex/oauth_authorize"
  377. }
  378. describe "when v1 api returns error", ->
  379. beforeEach ->
  380. @V1Api.request = sinon.stub().yields("error", {}, {})
  381. @req.token = "foo"
  382. @middleware(@req, @res, @next)
  383. it "should return status", ->
  384. @next.should.have.been.calledWith "error"
  385. describe "when v1 api status code is not 200", ->
  386. beforeEach ->
  387. @V1Api.request = sinon.stub().yields(null, {statusCode: 401}, {})
  388. @req.token = "foo"
  389. @middleware(@req, @res, @next)
  390. it "should return status", ->
  391. @res.status.should.have.been.calledWith 401
  392. describe "when v1 api returns authorized profile and access token", ->
  393. beforeEach ->
  394. @oauth_authorize =
  395. access_token: "access_token"
  396. user_profile: id: "overleaf-id"
  397. @V1Api.request = sinon.stub().yields(null, {statusCode: 200}, @oauth_authorize)
  398. @req.token = "foo"
  399. describe "in all cases", ->
  400. beforeEach ->
  401. @middleware(@req, @res, @next)
  402. it "should find user", ->
  403. @UserModel.findOne.should.have.been.calledWithMatch { "overleaf.id": "overleaf-id" }
  404. describe "when user find returns error", ->
  405. beforeEach ->
  406. @UserModel.findOne = sinon.stub().yields("error")
  407. @middleware(@req, @res, @next)
  408. it "should return error", ->
  409. @next.should.have.been.calledWith "error"
  410. describe "when user is not found", ->
  411. beforeEach ->
  412. @UserModel.findOne = sinon.stub().yields(null, null)
  413. @middleware(@req, @res, @next)
  414. it "should return unauthorized", ->
  415. @res.status.should.have.been.calledWith 401
  416. describe "when user is found", ->
  417. beforeEach ->
  418. @UserModel.findOne = sinon.stub().yields(null, "user")
  419. @middleware(@req, @res, @next)
  420. it "should add user to request", ->
  421. @req.oauth_user.should.equal "user"
  422. it "should add access_token to request", ->
  423. @req.oauth.access_token.should.equal "access_token"
  424. describe "requireGlobalLogin", ->
  425. beforeEach ->
  426. @req.headers = {}
  427. @AuthenticationController.httpAuth = sinon.stub()
  428. @setRedirect = sinon.spy(@AuthenticationController, 'setRedirectInSession')
  429. afterEach ->
  430. @setRedirect.restore()
  431. describe "with white listed url", ->
  432. beforeEach ->
  433. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  434. @req._parsedUrl.pathname = "/login"
  435. @AuthenticationController.requireGlobalLogin @req, @res, @next
  436. it "should call next() directly", ->
  437. @next.called.should.equal true
  438. describe "with white listed url and a query string", ->
  439. beforeEach ->
  440. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  441. @req._parsedUrl.pathname = "/login"
  442. @req.url = "/login?query=something"
  443. @AuthenticationController.requireGlobalLogin @req, @res, @next
  444. it "should call next() directly", ->
  445. @next.called.should.equal true
  446. describe "with http auth", ->
  447. beforeEach ->
  448. @req.headers["authorization"] = "Mock Basic Auth"
  449. @AuthenticationController.requireGlobalLogin @req, @res, @next
  450. it "should pass the request onto httpAuth", ->
  451. @AuthenticationController.httpAuth
  452. .calledWith(@req, @res, @next)
  453. .should.equal true
  454. describe "with a user session", ->
  455. beforeEach ->
  456. @req.session =
  457. user: {"mock": "user", "_id": "some_id"}
  458. @AuthenticationController.requireGlobalLogin @req, @res, @next
  459. it "should call next() directly", ->
  460. @next.called.should.equal true
  461. describe "with no login credentials", ->
  462. beforeEach ->
  463. @req.session = {}
  464. @AuthenticationController.requireGlobalLogin @req, @res, @next
  465. it 'should have called setRedirectInSession', ->
  466. @setRedirect.callCount.should.equal 1
  467. it "should redirect to the /login page", ->
  468. @res.redirectedTo.should.equal "/login"
  469. describe "_redirectToLoginOrRegisterPage", ->
  470. beforeEach ->
  471. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false })
  472. @req.session = {}
  473. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  474. @AuthenticationController._redirectToLoginPage = sinon.stub()
  475. @req.query = {}
  476. describe "they have come directly to the url", ->
  477. beforeEach ->
  478. @req.query = {}
  479. @middleware(@req, @res, @next)
  480. it "should redirect to the login page", ->
  481. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false
  482. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true
  483. describe "they have come via a templates link", ->
  484. beforeEach ->
  485. @req.query.zipUrl = "something"
  486. @middleware(@req, @res, @next)
  487. it "should redirect to the register page", ->
  488. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  489. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  490. describe "they have been invited to a project", ->
  491. beforeEach ->
  492. @req.query.project_name = "something"
  493. @middleware(@req, @res, @next)
  494. it "should redirect to the register page", ->
  495. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  496. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  497. describe "_redirectToRegisterPage", ->
  498. beforeEach ->
  499. @req.path = "/target/url"
  500. @req.query =
  501. extra_query: "foo"
  502. @AuthenticationController._redirectToRegisterPage(@req, @res)
  503. it "should redirect to the register page with a query string attached", ->
  504. @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo'
  505. @res.redirectedTo.should.equal "/register?extra_query=foo"
  506. it "should log out a message", ->
  507. @logger.log
  508. .calledWith(url: @url, "user not logged in so redirecting to register page")
  509. .should.equal true
  510. describe "_redirectToLoginPage", ->
  511. beforeEach ->
  512. @req.path = "/target/url"
  513. @req.query =
  514. extra_query: "foo"
  515. @AuthenticationController._redirectToLoginPage(@req, @res)
  516. it "should redirect to the register page with a query string attached", ->
  517. @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo'
  518. @res.redirectedTo.should.equal "/login?extra_query=foo"
  519. describe "_recordSuccessfulLogin", ->
  520. beforeEach ->
  521. @UserUpdater.updateUser = sinon.stub().callsArg(2)
  522. @AuthenticationController._recordSuccessfulLogin(@user._id, @callback)
  523. it "should increment the user.login.success metric", ->
  524. @Metrics.inc
  525. .calledWith("user.login.success")
  526. .should.equal true
  527. it "should update the user's login count and last logged in date", ->
  528. @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined
  529. @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1
  530. it "should call the callback", ->
  531. @callback.called.should.equal true
  532. describe "_recordFailedLogin", ->
  533. beforeEach ->
  534. @AuthenticationController._recordFailedLogin(@callback)
  535. it "should increment the user.login.failed metric", ->
  536. @Metrics.inc
  537. .calledWith("user.login.failed")
  538. .should.equal true
  539. it "should call the callback", ->
  540. @callback.called.should.equal true
  541. describe 'setRedirectInSession', ->
  542. beforeEach ->
  543. @req = {session: {}}
  544. @req.path = "/somewhere"
  545. @req.query = {one: "1"}
  546. it 'should set redirect property on session', ->
  547. @AuthenticationController.setRedirectInSession(@req)
  548. expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1"
  549. it 'should set the supplied value', ->
  550. @AuthenticationController.setRedirectInSession(@req, '/somewhere/specific')
  551. expect(@req.session.postLoginRedirect).to.equal "/somewhere/specific"
  552. it 'should not allow open redirects', ->
  553. @AuthenticationController.setRedirectInSession(@req, 'https://evil.com')
  554. expect(@req.session.postLoginRedirect).to.be.undefined
  555. describe 'with a png', ->
  556. beforeEach ->
  557. @req = {session: {}}
  558. it 'should not set the redirect', ->
  559. @AuthenticationController.setRedirectInSession(@req, '/something.png')
  560. expect(@req.session.postLoginRedirect).to.equal undefined
  561. describe 'with a js path', ->
  562. beforeEach ->
  563. @req = {session: {}}
  564. it 'should not set the redirect', ->
  565. @AuthenticationController.setRedirectInSession(@req, '/js/something.js')
  566. expect(@req.session.postLoginRedirect).to.equal undefined
  567. describe '_getRedirectFromSession', ->
  568. it 'should get redirect property from session', ->
  569. @req = session: { postLoginRedirect: '/a?b=c' }
  570. expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c"
  571. it 'should not allow open redirects', ->
  572. @req = session: { postLoginRedirect: 'https://evil.com' }
  573. expect(@AuthenticationController._getRedirectFromSession(@req)).to.be.null
  574. it 'handle null values', ->
  575. @req = session: {}
  576. expect(@AuthenticationController._getRedirectFromSession(@req)).to.be.null
  577. describe '_getSafeRedirectPath', ->
  578. it 'sanitize redirect path to prevent open redirects', ->
  579. expect(
  580. @AuthenticationController._getSafeRedirectPath('https://evil.com')
  581. ).to.be.undefined
  582. expect(
  583. @AuthenticationController._getSafeRedirectPath('//evil.com')
  584. ).to.be.undefined
  585. expect(
  586. @AuthenticationController._getSafeRedirectPath('//ol.com/evil')
  587. ).to.equal '/evil'
  588. expect(
  589. @AuthenticationController._getSafeRedirectPath('////evil.com')
  590. ).to.be.undefined
  591. expect(
  592. @AuthenticationController._getSafeRedirectPath('%2F%2Fevil.com')
  593. ).to.equal '/%2F%2Fevil.com'
  594. expect(
  595. @AuthenticationController._getSafeRedirectPath('.evil.com')
  596. ).to.equal '/.evil.com'
  597. describe '_clearRedirectFromSession', ->
  598. beforeEach ->
  599. @req = {session: {postLoginRedirect: "/a?b=c"}}
  600. it 'should remove the redirect property from session', ->
  601. @AuthenticationController._clearRedirectFromSession(@req)
  602. expect(@req.session.postLoginRedirect).to.equal undefined
  603. describe 'finishLogin', ->
  604. # - get redirect
  605. # - async handlers
  606. # - afterLoginSessionSetup
  607. # - clear redirect
  608. # - issue redir, two ways
  609. beforeEach ->
  610. @AuthenticationController._getRedirectFromSession = sinon.stub().returns '/some/page'
  611. @AuthenticationController._loginAsyncHandlers = sinon.stub()
  612. @AuthenticationController.afterLoginSessionSetup = sinon.stub().callsArgWith(2, null)
  613. @AuthenticationController._clearRedirectFromSession = sinon.stub()
  614. @AuthenticationController._redirectToReconfirmPage = sinon.stub()
  615. @req.headers = {accept: 'application/json, whatever'}
  616. @res.json = sinon.stub()
  617. @res.redirect = sinon.stub()
  618. it 'should extract the redirect from the session', () ->
  619. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  620. expect(@AuthenticationController._getRedirectFromSession.callCount).to.equal 1
  621. expect(@AuthenticationController._getRedirectFromSession.calledWith(@req)).to.equal true
  622. it 'should call the async handlers', () ->
  623. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  624. expect(@AuthenticationController._loginAsyncHandlers.callCount).to.equal 1
  625. expect(@AuthenticationController._loginAsyncHandlers.calledWith(@req, @user)).to.equal true
  626. it 'should call afterLoginSessionSetup', () ->
  627. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  628. expect(@AuthenticationController.afterLoginSessionSetup.callCount).to.equal 1
  629. expect(@AuthenticationController.afterLoginSessionSetup.calledWith(@req, @user)).to.equal true
  630. it 'should clear redirect from session', () ->
  631. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  632. expect(@AuthenticationController._clearRedirectFromSession.callCount).to.equal 1
  633. expect(@AuthenticationController._clearRedirectFromSession.calledWith(@req)).to.equal true
  634. it 'should issue a json response with a redirect', () ->
  635. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  636. expect(@res.json.callCount).to.equal 1
  637. expect(@res.redirect.callCount).to.equal 0
  638. expect(@res.json.calledWith({ redir: '/some/page' })).to.equal true
  639. describe 'with a non-json request', ->
  640. beforeEach ->
  641. @req.headers = {}
  642. @res.json = sinon.stub()
  643. @res.redirect = sinon.stub()
  644. it 'should issue a plain redirect', () ->
  645. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  646. expect(@res.json.callCount).to.equal 0
  647. expect(@res.redirect.callCount).to.equal 1
  648. expect(@res.redirect.calledWith('/some/page')).to.equal true
  649. describe "when user is flagged to reconfirm", ->
  650. beforeEach ->
  651. @req.session = {}
  652. @user.must_reconfirm = true
  653. it "should redirect to reconfirm page", () ->
  654. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  655. expect(@AuthenticationController._redirectToReconfirmPage.calledWith(@req)).to.equal true