AuthenticationControllerTests.coffee 23 KB

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