AuthenticationControllerTests.coffee 25 KB

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