AuthenticationControllerTests.coffee 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  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. @AuthenticationController = SandboxedModule.require modulePath, requires:
  16. "./AuthenticationManager": @AuthenticationManager = {}
  17. "../User/UserUpdater" : @UserUpdater = {}
  18. "metrics-sharelatex": @Metrics = { inc: sinon.stub() }
  19. "../Security/LoginRateLimiter": @LoginRateLimiter = { processLoginRequest:sinon.stub(), recordSuccessfulLogin:sinon.stub() }
  20. "../User/UserHandler": @UserHandler = {setupLoginData:sinon.stub()}
  21. "../Analytics/AnalyticsManager": @AnalyticsManager = { recordEvent: sinon.stub() }
  22. "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub(), err: sinon.stub() }
  23. "settings-sharelatex": {}
  24. "passport": @passport =
  25. authenticate: sinon.stub().returns(sinon.stub())
  26. "../User/UserSessionsManager": @UserSessionsManager =
  27. trackSession: sinon.stub()
  28. untrackSession: sinon.stub()
  29. revokeAllUserSessions: sinon.stub().callsArgWith(1, null)
  30. "../../infrastructure/Modules": @Modules = {hooks: {fire: sinon.stub().callsArgWith(2, null, [])}}
  31. @user =
  32. _id: ObjectId()
  33. email: @email = "USER@example.com"
  34. first_name: "bob"
  35. last_name: "brown"
  36. referal_id: 1234
  37. isAdmin: false
  38. @password = "banana"
  39. @req = new MockRequest()
  40. @res = new MockResponse()
  41. @callback = @next = sinon.stub()
  42. afterEach ->
  43. tk.reset()
  44. describe 'isUserLoggedIn', () ->
  45. beforeEach ->
  46. @stub = sinon.stub(@AuthenticationController, 'getLoggedInUserId')
  47. afterEach ->
  48. @stub.restore()
  49. it 'should do the right thing in all cases', () ->
  50. @AuthenticationController.getLoggedInUserId.returns('some_id')
  51. expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal true
  52. @AuthenticationController.getLoggedInUserId.returns(null)
  53. expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false
  54. @AuthenticationController.getLoggedInUserId.returns(false)
  55. expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false
  56. @AuthenticationController.getLoggedInUserId.returns(undefined)
  57. expect(@AuthenticationController.isUserLoggedIn(@req)).to.equal false
  58. describe 'setInSessionUser', () ->
  59. beforeEach ->
  60. @user = {
  61. _id: 'id'
  62. first_name: 'a'
  63. last_name: 'b'
  64. email: 'c'
  65. }
  66. @req.session.passport = {user: @user}
  67. @req.session.user = @user
  68. it 'should update the right properties', () ->
  69. @AuthenticationController.setInSessionUser(@req, {first_name: 'new_first_name', email: 'new_email'})
  70. expectedUser = {
  71. _id: 'id'
  72. first_name: 'new_first_name'
  73. last_name: 'b'
  74. email: 'new_email'
  75. }
  76. expect(@req.session.passport.user).to.deep.equal(expectedUser)
  77. expect(@req.session.user).to.deep.equal(expectedUser)
  78. describe 'passportLogin', ->
  79. beforeEach ->
  80. @info = null
  81. @req.login = sinon.stub().callsArgWith(1, null)
  82. @res.json = sinon.stub()
  83. @req.session = @session = {
  84. passport: {user: @user},
  85. postLoginRedirect: "/path/to/redir/to"
  86. }
  87. @req.session.destroy = sinon.stub().callsArgWith(0, null)
  88. @req.session.save = sinon.stub().callsArgWith(0, null)
  89. @req.sessionStore = {generate: sinon.stub()}
  90. @AuthenticationController.finishLogin = sinon.stub()
  91. @passport.authenticate.callsArgWith(1, null, @user, @info)
  92. @err = new Error('woops')
  93. it 'should call passport.authenticate', () ->
  94. @AuthenticationController.passportLogin @req, @res, @next
  95. @passport.authenticate.callCount.should.equal 1
  96. describe 'when authenticate produces an error', ->
  97. beforeEach ->
  98. @passport.authenticate.callsArgWith(1, @err)
  99. it 'should return next with an error', () ->
  100. @AuthenticationController.passportLogin @req, @res, @next
  101. @next.calledWith(@err).should.equal true
  102. describe 'when authenticate produces a user', ->
  103. beforeEach ->
  104. @req.session.postLoginRedirect = 'some_redirect'
  105. @passport.authenticate.callsArgWith(1, null, @user, @info)
  106. afterEach ->
  107. delete @req.session.postLoginRedirect
  108. it 'should call finishLogin', () ->
  109. @AuthenticationController.passportLogin @req, @res, @next
  110. @AuthenticationController.finishLogin.callCount.should.equal 1
  111. @AuthenticationController.finishLogin.calledWith(@user).should.equal true
  112. describe 'when authenticate does not produce a user', ->
  113. beforeEach ->
  114. @info = {text: 'a', type: 'b'}
  115. @passport.authenticate.callsArgWith(1, null, false, @info)
  116. it 'should not call finishLogin', () ->
  117. @AuthenticationController.passportLogin @req, @res, @next
  118. @AuthenticationController.finishLogin.callCount.should.equal 0
  119. it 'should not send a json response with redirect', () ->
  120. @AuthenticationController.passportLogin @req, @res, @next
  121. @res.json.callCount.should.equal 1
  122. @res.json.calledWith({message: @info}).should.equal true
  123. expect(@res.json.lastCall.args[0].redir?).to.equal false
  124. describe 'afterLoginSessionSetup', ->
  125. beforeEach ->
  126. @req.login = sinon.stub().callsArgWith(1, null)
  127. @req.session = @session = {passport: {user: @user}}
  128. @req.session =
  129. passport: {user: {_id: "one"}}
  130. @req.session.destroy = sinon.stub().callsArgWith(0, null)
  131. @req.session.save = sinon.stub().callsArgWith(0, null)
  132. @req.sessionStore = {generate: sinon.stub()}
  133. @UserSessionsManager.trackSession = sinon.stub()
  134. @call = (callback) =>
  135. @AuthenticationController.afterLoginSessionSetup @req, @user, callback
  136. it 'should not produce an error', (done) ->
  137. @call (err) =>
  138. expect(err).to.equal null
  139. done()
  140. it 'should call req.login', (done) ->
  141. @call (err) =>
  142. @req.login.callCount.should.equal 1
  143. done()
  144. it 'should call req.session.save', (done) ->
  145. @call (err) =>
  146. @req.session.save.callCount.should.equal 1
  147. done()
  148. it 'should call UserSessionsManager.trackSession', (done) ->
  149. @call (err) =>
  150. @UserSessionsManager.trackSession.callCount.should.equal 1
  151. done()
  152. describe 'when req.session.save produces an error', ->
  153. beforeEach ->
  154. @req.session.save = sinon.stub().callsArgWith(0, new Error('woops'))
  155. it 'should produce an error', (done) ->
  156. @call (err) =>
  157. expect(err).to.not.be.oneOf [null, undefined]
  158. expect(err).to.be.instanceof Error
  159. done()
  160. it 'should not call UserSessionsManager.trackSession', (done) ->
  161. @call (err) =>
  162. @UserSessionsManager.trackSession.callCount.should.equal 0
  163. done()
  164. describe 'getSessionUser', ->
  165. it 'should get the user object from session', ->
  166. @req.session =
  167. passport:
  168. user: {_id: 'one'}
  169. user = @AuthenticationController.getSessionUser(@req)
  170. expect(user).to.deep.equal {_id: 'one'}
  171. it 'should work with legacy sessions', ->
  172. @req.session =
  173. user: {_id: 'one'}
  174. user = @AuthenticationController.getSessionUser(@req)
  175. expect(user).to.deep.equal {_id: 'one'}
  176. describe "doPassportLogin", ->
  177. beforeEach ->
  178. @AuthenticationController._recordFailedLogin = sinon.stub()
  179. @AuthenticationController._recordSuccessfulLogin = sinon.stub()
  180. @Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [])
  181. # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  182. @req.body =
  183. email: @email
  184. password: @password
  185. session:
  186. postLoginRedirect: "/path/to/redir/to"
  187. @cb = sinon.stub()
  188. describe "when the preDoPassportLogin hooks produce an info object", ->
  189. beforeEach ->
  190. @Modules.hooks.fire = sinon.stub().callsArgWith(3, null, [null, {redir: '/somewhere'}, null])
  191. it "should stop early and call done with this info object", (done) ->
  192. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  193. @cb.callCount.should.equal 1
  194. @cb.calledWith(null, false, {redir: '/somewhere'}).should.equal true
  195. @LoginRateLimiter.processLoginRequest.callCount.should.equal 0
  196. done()
  197. describe "when the users rate limit", ->
  198. beforeEach ->
  199. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  200. it "should block the request if the limit has been exceeded", (done)->
  201. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  202. @cb.callCount.should.equal 1
  203. @cb.calledWith(null, null).should.equal true
  204. done()
  205. describe 'when the user is authenticated', ->
  206. beforeEach ->
  207. @cb = sinon.stub()
  208. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  209. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  210. @req.sessionID = Math.random()
  211. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  212. it "should attempt to authorise the user", ->
  213. @AuthenticationManager.authenticate
  214. .calledWith(email: @email.toLowerCase(), @password)
  215. .should.equal true
  216. it "should establish the user's session", ->
  217. @cb.calledWith(null, @user).should.equal true
  218. describe '_loginAsyncHandlers', ->
  219. beforeEach ->
  220. @UserHandler.setupLoginData = sinon.stub()
  221. @LoginRateLimiter.recordSuccessfulLogin = sinon.stub()
  222. @AuthenticationController._recordSuccessfulLogin = sinon.stub()
  223. @AnalyticsManager.recordEvent = sinon.stub()
  224. @AnalyticsManager.identifyUser = sinon.stub()
  225. @AuthenticationController._loginAsyncHandlers(@req, @user)
  226. it "should call identifyUser", ->
  227. @AnalyticsManager.identifyUser.calledWith(@user._id, @req.sessionID).should.equal true
  228. it "should setup the user data in the background", ->
  229. @UserHandler.setupLoginData.calledWith(@user).should.equal true
  230. it "should set res.session.justLoggedIn", ->
  231. @req.session.justLoggedIn.should.equal true
  232. it "should record the successful login", ->
  233. @AuthenticationController._recordSuccessfulLogin
  234. .calledWith(@user._id)
  235. .should.equal true
  236. it "should tell the rate limiter that there was a success for that email", ->
  237. @LoginRateLimiter.recordSuccessfulLogin.calledWith(@user.email).should.equal true
  238. it "should log the successful login", ->
  239. @logger.log
  240. .calledWith(email: @user.email, user_id: @user._id.toString(), "successful log in")
  241. .should.equal true
  242. it "should track the login event", ->
  243. @AnalyticsManager.recordEvent
  244. .calledWith(@user._id, "user-logged-in")
  245. .should.equal true
  246. describe 'when the user is not authenticated', ->
  247. beforeEach ->
  248. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  249. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null)
  250. @cb = sinon.stub()
  251. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  252. it "should not establish the login", ->
  253. @cb.callCount.should.equal 1
  254. @cb.calledWith(null, false)
  255. # @res.body.should.exist
  256. expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type']
  257. # message:
  258. # text: 'Your email or password were incorrect. Please try again',
  259. # type: 'error'
  260. it "should not setup the user data in the background", ->
  261. @UserHandler.setupLoginData.called.should.equal false
  262. it "should record a failed login", ->
  263. @AuthenticationController._recordFailedLogin.called.should.equal true
  264. it "should log the failed login", ->
  265. @logger.log
  266. .calledWith(email: @email.toLowerCase(), "failed log in")
  267. .should.equal true
  268. describe "getLoggedInUserId", ->
  269. beforeEach ->
  270. @req =
  271. session :{}
  272. it "should return the user id from the session", ()->
  273. @user_id = "2134"
  274. @req.session.user =
  275. _id:@user_id
  276. result = @AuthenticationController.getLoggedInUserId @req
  277. expect(result).to.equal @user_id
  278. it 'should return user for passport session', () ->
  279. @user_id = "2134"
  280. @req.session = {
  281. passport: {
  282. user: {
  283. _id:@user_id
  284. }
  285. }
  286. }
  287. result = @AuthenticationController.getLoggedInUserId @req
  288. expect(result).to.equal @user_id
  289. it "should return null if there is no user on the session", ()->
  290. result = @AuthenticationController.getLoggedInUserId @req
  291. expect(result).to.equal null
  292. it "should return null if there is no session", ()->
  293. @req = {}
  294. result = @AuthenticationController.getLoggedInUserId @req
  295. expect(result).to.equal null
  296. it "should return null if there is no req", ()->
  297. @req = {}
  298. result = @AuthenticationController.getLoggedInUserId @req
  299. expect(result).to.equal null
  300. describe "requireLogin", ->
  301. beforeEach ->
  302. @user =
  303. _id: "user-id-123"
  304. email: "user@sharelatex.com"
  305. @middleware = @AuthenticationController.requireLogin()
  306. describe "when the user is logged in", ->
  307. beforeEach ->
  308. @req.session =
  309. user: @user = {
  310. _id: "user-id-123"
  311. email: "user@sharelatex.com"
  312. }
  313. @middleware(@req, @res, @next)
  314. it "should call the next method in the chain", ->
  315. @next.called.should.equal true
  316. describe "when the user is not logged in", ->
  317. beforeEach ->
  318. @req.session = {}
  319. @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  320. @req.query = {}
  321. @middleware(@req, @res, @next)
  322. it "should redirect to the register or login page", ->
  323. @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true
  324. describe "requireGlobalLogin", ->
  325. beforeEach ->
  326. @req.headers = {}
  327. @AuthenticationController.httpAuth = sinon.stub()
  328. @_setRedirect = sinon.spy(@AuthenticationController, '_setRedirectInSession')
  329. afterEach ->
  330. @_setRedirect.restore()
  331. describe "with white listed url", ->
  332. beforeEach ->
  333. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  334. @req._parsedUrl.pathname = "/login"
  335. @AuthenticationController.requireGlobalLogin @req, @res, @next
  336. it "should call next() directly", ->
  337. @next.called.should.equal true
  338. describe "with white listed url and a query string", ->
  339. beforeEach ->
  340. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  341. @req._parsedUrl.pathname = "/login"
  342. @req.url = "/login?query=something"
  343. @AuthenticationController.requireGlobalLogin @req, @res, @next
  344. it "should call next() directly", ->
  345. @next.called.should.equal true
  346. describe "with http auth", ->
  347. beforeEach ->
  348. @req.headers["authorization"] = "Mock Basic Auth"
  349. @AuthenticationController.requireGlobalLogin @req, @res, @next
  350. it "should pass the request onto httpAuth", ->
  351. @AuthenticationController.httpAuth
  352. .calledWith(@req, @res, @next)
  353. .should.equal true
  354. describe "with a user session", ->
  355. beforeEach ->
  356. @req.session =
  357. user: {"mock": "user", "_id": "some_id"}
  358. @AuthenticationController.requireGlobalLogin @req, @res, @next
  359. it "should call next() directly", ->
  360. @next.called.should.equal true
  361. describe "with no login credentials", ->
  362. beforeEach ->
  363. @req.session = {}
  364. @AuthenticationController.requireGlobalLogin @req, @res, @next
  365. it 'should have called setRedirectInSession', ->
  366. @_setRedirect.callCount.should.equal 1
  367. it "should redirect to the /login page", ->
  368. @res.redirectedTo.should.equal "/login"
  369. describe "_redirectToLoginOrRegisterPage", ->
  370. beforeEach ->
  371. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false })
  372. @req.session = {}
  373. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  374. @AuthenticationController._redirectToLoginPage = sinon.stub()
  375. @req.query = {}
  376. describe "they have come directly to the url", ->
  377. beforeEach ->
  378. @req.query = {}
  379. @middleware(@req, @res, @next)
  380. it "should redirect to the login page", ->
  381. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false
  382. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true
  383. describe "they have come via a templates link", ->
  384. beforeEach ->
  385. @req.query.zipUrl = "something"
  386. @middleware(@req, @res, @next)
  387. it "should redirect to the register page", ->
  388. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  389. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  390. describe "they have been invited to a project", ->
  391. beforeEach ->
  392. @req.query.project_name = "something"
  393. @middleware(@req, @res, @next)
  394. it "should redirect to the register page", ->
  395. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  396. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  397. describe "_redirectToRegisterPage", ->
  398. beforeEach ->
  399. @req.path = "/target/url"
  400. @req.query =
  401. extra_query: "foo"
  402. @AuthenticationController._redirectToRegisterPage(@req, @res)
  403. it "should redirect to the register page with a query string attached", ->
  404. @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo'
  405. @res.redirectedTo.should.equal "/register?extra_query=foo"
  406. it "should log out a message", ->
  407. @logger.log
  408. .calledWith(url: @url, "user not logged in so redirecting to register page")
  409. .should.equal true
  410. describe "_redirectToLoginPage", ->
  411. beforeEach ->
  412. @req.path = "/target/url"
  413. @req.query =
  414. extra_query: "foo"
  415. @AuthenticationController._redirectToLoginPage(@req, @res)
  416. it "should redirect to the register page with a query string attached", ->
  417. @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo'
  418. @res.redirectedTo.should.equal "/login?extra_query=foo"
  419. describe "_recordSuccessfulLogin", ->
  420. beforeEach ->
  421. @UserUpdater.updateUser = sinon.stub().callsArg(2)
  422. @AuthenticationController._recordSuccessfulLogin(@user._id, @callback)
  423. it "should increment the user.login.success metric", ->
  424. @Metrics.inc
  425. .calledWith("user.login.success")
  426. .should.equal true
  427. it "should update the user's login count and last logged in date", ->
  428. @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined
  429. @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1
  430. it "should call the callback", ->
  431. @callback.called.should.equal true
  432. describe "_recordFailedLogin", ->
  433. beforeEach ->
  434. @AuthenticationController._recordFailedLogin(@callback)
  435. it "should increment the user.login.failed metric", ->
  436. @Metrics.inc
  437. .calledWith("user.login.failed")
  438. .should.equal true
  439. it "should call the callback", ->
  440. @callback.called.should.equal true
  441. describe '_setRedirectInSession', ->
  442. beforeEach ->
  443. @req = {session: {}}
  444. @req.path = "/somewhere"
  445. @req.query = {one: "1"}
  446. it 'should set redirect property on session', ->
  447. @AuthenticationController._setRedirectInSession(@req)
  448. expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1"
  449. it 'should set the supplied value', ->
  450. @AuthenticationController._setRedirectInSession(@req, '/somewhere/specific')
  451. expect(@req.session.postLoginRedirect).to.equal "/somewhere/specific"
  452. describe 'with a png', ->
  453. beforeEach ->
  454. @req = {session: {}}
  455. it 'should not set the redirect', ->
  456. @AuthenticationController._setRedirectInSession(@req, '/something.png')
  457. expect(@req.session.postLoginRedirect).to.equal undefined
  458. describe 'with a js path', ->
  459. beforeEach ->
  460. @req = {session: {}}
  461. it 'should not set the redirect', ->
  462. @AuthenticationController._setRedirectInSession(@req, '/js/something.js')
  463. expect(@req.session.postLoginRedirect).to.equal undefined
  464. describe '_getRedirectFromSession', ->
  465. beforeEach ->
  466. @req = {session: {postLoginRedirect: "/a?b=c"}}
  467. it 'should get redirect property from session', ->
  468. expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c"
  469. describe '_clearRedirectFromSession', ->
  470. beforeEach ->
  471. @req = {session: {postLoginRedirect: "/a?b=c"}}
  472. it 'should remove the redirect property from session', ->
  473. @AuthenticationController._clearRedirectFromSession(@req)
  474. expect(@req.session.postLoginRedirect).to.equal undefined
  475. describe 'finishLogin', ->
  476. # - get redirect
  477. # - async handlers
  478. # - afterLoginSessionSetup
  479. # - clear redirect
  480. # - issue redir, two ways
  481. beforeEach ->
  482. @AuthenticationController._getRedirectFromSession = sinon.stub().returns '/some/page'
  483. @AuthenticationController._loginAsyncHandlers = sinon.stub()
  484. @AuthenticationController.afterLoginSessionSetup = sinon.stub().callsArgWith(2, null)
  485. @AuthenticationController._clearRedirectFromSession = sinon.stub()
  486. @req.headers = {accept: 'application/json, whatever'}
  487. @res.json = sinon.stub()
  488. @res.redirect = sinon.stub()
  489. it 'should extract the redirect from the session', () ->
  490. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  491. expect(@AuthenticationController._getRedirectFromSession.callCount).to.equal 1
  492. expect(@AuthenticationController._getRedirectFromSession.calledWith(@req)).to.equal true
  493. it 'should call the async handlers', () ->
  494. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  495. expect(@AuthenticationController._loginAsyncHandlers.callCount).to.equal 1
  496. expect(@AuthenticationController._loginAsyncHandlers.calledWith(@req, @user)).to.equal true
  497. it 'should call afterLoginSessionSetup', () ->
  498. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  499. expect(@AuthenticationController.afterLoginSessionSetup.callCount).to.equal 1
  500. expect(@AuthenticationController.afterLoginSessionSetup.calledWith(@req, @user)).to.equal true
  501. it 'should clear redirect from session', () ->
  502. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  503. expect(@AuthenticationController._clearRedirectFromSession.callCount).to.equal 1
  504. expect(@AuthenticationController._clearRedirectFromSession.calledWith(@req)).to.equal true
  505. it 'should issue a json response with a redirect', () ->
  506. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  507. expect(@res.json.callCount).to.equal 1
  508. expect(@res.redirect.callCount).to.equal 0
  509. expect(@res.json.calledWith({ redir: '/some/page' })).to.equal true
  510. describe 'with a non-json request', ->
  511. beforeEach ->
  512. @req.headers = {}
  513. @res.json = sinon.stub()
  514. @res.redirect = sinon.stub()
  515. it 'should issue a plain redirect', () ->
  516. @AuthenticationController.finishLogin(@user, @req, @res, @next)
  517. expect(@res.json.callCount).to.equal 0
  518. expect(@res.redirect.callCount).to.equal 1
  519. expect(@res.redirect.calledWith('/some/page')).to.equal true