AuthenticationControllerTests.coffee 22 KB

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