AuthenticationControllerTests.coffee 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. @AuthenticationController = SandboxedModule.require modulePath, requires:
  15. "./AuthenticationManager": @AuthenticationManager = {}
  16. "../User/UserGetter" : @UserGetter = {}
  17. "../User/UserUpdater" : @UserUpdater = {}
  18. "../../infrastructure/Metrics": @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. @user =
  31. _id: ObjectId()
  32. email: @email = "USER@example.com"
  33. first_name: "bob"
  34. last_name: "brown"
  35. referal_id: 1234
  36. isAdmin: false
  37. @password = "banana"
  38. @req = new MockRequest()
  39. @res = new MockResponse()
  40. @callback = @next = sinon.stub()
  41. tk.freeze(Date.now())
  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. @passport.authenticate.callsArgWith(1, null, @user, @info)
  91. it 'should call passport.authenticate', () ->
  92. @AuthenticationController.passportLogin @req, @res, @next
  93. @passport.authenticate.callCount.should.equal 1
  94. describe 'when authenticate produces an error', ->
  95. beforeEach ->
  96. @err = new Error('woops')
  97. @passport.authenticate.callsArgWith(1, @err)
  98. it 'should return next with an error', () ->
  99. @AuthenticationController.passportLogin @req, @res, @next
  100. @next.calledWith(@err).should.equal true
  101. describe 'when authenticate produces a user', ->
  102. beforeEach ->
  103. @req.session.postLoginRedirect = 'some_redirect'
  104. @passport.authenticate.callsArgWith(1, null, @user, @info)
  105. afterEach ->
  106. delete @req.session.postLoginRedirect
  107. it 'should call req.login', () ->
  108. @AuthenticationController.passportLogin @req, @res, @next
  109. @req.login.callCount.should.equal 1
  110. @req.login.calledWith(@user).should.equal true
  111. it 'should send a json response with redirect', () ->
  112. @AuthenticationController.passportLogin @req, @res, @next
  113. @res.json.callCount.should.equal 1
  114. @res.json.calledWith({redir: 'some_redirect'}).should.equal true
  115. describe 'when session.save produces an error', () ->
  116. beforeEach ->
  117. @req.session.save = sinon.stub().callsArgWith(0, new Error('woops'))
  118. it 'should return next with an error', () ->
  119. @AuthenticationController.passportLogin @req, @res, @next
  120. @next.calledWith(@err).should.equal true
  121. it 'should not return json', () ->
  122. @AuthenticationController.passportLogin @req, @res, @next
  123. @res.json.callCount.should.equal 0
  124. describe 'when authenticate does not produce a user', ->
  125. beforeEach ->
  126. @info = {text: 'a', type: 'b'}
  127. @passport.authenticate.callsArgWith(1, null, false, @info)
  128. it 'should not call req.login', () ->
  129. @AuthenticationController.passportLogin @req, @res, @next
  130. @req.login.callCount.should.equal 0
  131. it 'should send a json response with redirect', () ->
  132. @AuthenticationController.passportLogin @req, @res, @next
  133. @res.json.callCount.should.equal 1
  134. @res.json.calledWith({message: @info}).should.equal true
  135. describe 'afterLoginSessionSetup', ->
  136. beforeEach ->
  137. @req.login = sinon.stub().callsArgWith(1, null)
  138. @req.session = @session = {passport: {user: @user}}
  139. @req.session =
  140. passport: {user: {_id: "one"}}
  141. @req.session.destroy = sinon.stub().callsArgWith(0, null)
  142. @req.session.save = sinon.stub().callsArgWith(0, null)
  143. @req.sessionStore = {generate: sinon.stub()}
  144. @UserSessionsManager.trackSession = sinon.stub()
  145. @call = (callback) =>
  146. @AuthenticationController.afterLoginSessionSetup @req, @user, callback
  147. it 'should not produce an error', (done) ->
  148. @call (err) =>
  149. expect(err).to.equal null
  150. done()
  151. it 'should call req.login', (done) ->
  152. @call (err) =>
  153. @req.login.callCount.should.equal 1
  154. done()
  155. it 'should call req.session.save', (done) ->
  156. @call (err) =>
  157. @req.session.save.callCount.should.equal 1
  158. done()
  159. it 'should call UserSessionsManager.trackSession', (done) ->
  160. @call (err) =>
  161. @UserSessionsManager.trackSession.callCount.should.equal 1
  162. done()
  163. describe 'when req.session.save produces an error', ->
  164. beforeEach ->
  165. @req.session.save = sinon.stub().callsArgWith(0, new Error('woops'))
  166. it 'should produce an error', (done) ->
  167. @call (err) =>
  168. expect(err).to.not.be.oneOf [null, undefined]
  169. expect(err).to.be.instanceof Error
  170. done()
  171. it 'should not call UserSessionsManager.trackSession', (done) ->
  172. @call (err) =>
  173. @UserSessionsManager.trackSession.callCount.should.equal 0
  174. done()
  175. describe 'getSessionUser', ->
  176. it 'should get the user object from session', ->
  177. @req.session =
  178. passport:
  179. user: {_id: 'one'}
  180. user = @AuthenticationController.getSessionUser(@req)
  181. expect(user).to.deep.equal {_id: 'one'}
  182. it 'should work with legacy sessions', ->
  183. @req.session =
  184. user: {_id: 'one'}
  185. user = @AuthenticationController.getSessionUser(@req)
  186. expect(user).to.deep.equal {_id: 'one'}
  187. describe "doPassportLogin", ->
  188. beforeEach ->
  189. @AuthenticationController._recordFailedLogin = sinon.stub()
  190. @AuthenticationController._recordSuccessfulLogin = sinon.stub()
  191. # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  192. @req.body =
  193. email: @email
  194. password: @password
  195. session:
  196. postLoginRedirect: "/path/to/redir/to"
  197. @cb = sinon.stub()
  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. @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 setup the user data in the background", ->
  217. @UserHandler.setupLoginData.calledWith(@user).should.equal true
  218. it "should establish the user's session", ->
  219. @cb.calledWith(null, @user).should.equal true
  220. it "should set res.session.justLoggedIn", ->
  221. @req.session.justLoggedIn.should.equal true
  222. it "should redirect the user to the specified location", ->
  223. expect(@req._redir).to.deep.equal @redir
  224. it "should record the successful login", ->
  225. @AuthenticationController._recordSuccessfulLogin
  226. .calledWith(@user._id)
  227. .should.equal true
  228. it "should tell the rate limiter that there was a success for that email", ->
  229. @LoginRateLimiter.recordSuccessfulLogin.calledWith(@email.toLowerCase()).should.equal true
  230. it "should log the successful login", ->
  231. @logger.log
  232. .calledWith(email: @email.toLowerCase(), user_id: @user._id.toString(), "successful log in")
  233. .should.equal true
  234. it "should track the login event", ->
  235. @AnalyticsManager.recordEvent
  236. .calledWith(@user._id, "user-logged-in")
  237. .should.equal true
  238. describe 'when the user is not authenticated', ->
  239. beforeEach ->
  240. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  241. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null)
  242. @cb = sinon.stub()
  243. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  244. it "should not establish the login", ->
  245. @cb.callCount.should.equal 1
  246. @cb.calledWith(null, false)
  247. # @res.body.should.exist
  248. expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type']
  249. # message:
  250. # text: 'Your email or password were incorrect. Please try again',
  251. # type: 'error'
  252. it "should not setup the user data in the background", ->
  253. @UserHandler.setupLoginData.called.should.equal false
  254. it "should record a failed login", ->
  255. @AuthenticationController._recordFailedLogin.called.should.equal true
  256. it "should log the failed login", ->
  257. @logger.log
  258. .calledWith(email: @email.toLowerCase(), "failed log in")
  259. .should.equal true
  260. describe "getLoggedInUserId", ->
  261. beforeEach ->
  262. @req =
  263. session :{}
  264. it "should return the user id from the session", ()->
  265. @user_id = "2134"
  266. @req.session.user =
  267. _id:@user_id
  268. result = @AuthenticationController.getLoggedInUserId @req
  269. expect(result).to.equal @user_id
  270. it 'should return user for passport session', () ->
  271. @user_id = "2134"
  272. @req.session = {
  273. passport: {
  274. user: {
  275. _id:@user_id
  276. }
  277. }
  278. }
  279. result = @AuthenticationController.getLoggedInUserId @req
  280. expect(result).to.equal @user_id
  281. it "should return null if there is no user on the session", ()->
  282. result = @AuthenticationController.getLoggedInUserId @req
  283. expect(result).to.equal null
  284. it "should return null if there is no session", ()->
  285. @req = {}
  286. result = @AuthenticationController.getLoggedInUserId @req
  287. expect(result).to.equal null
  288. it "should return null if there is no req", ()->
  289. @req = {}
  290. result = @AuthenticationController.getLoggedInUserId @req
  291. expect(result).to.equal null
  292. describe "requireLogin", ->
  293. beforeEach ->
  294. @user =
  295. _id: "user-id-123"
  296. email: "user@sharelatex.com"
  297. @middleware = @AuthenticationController.requireLogin()
  298. describe "when the user is logged in", ->
  299. beforeEach ->
  300. @req.session =
  301. user: @user = {
  302. _id: "user-id-123"
  303. email: "user@sharelatex.com"
  304. }
  305. @middleware(@req, @res, @next)
  306. it "should call the next method in the chain", ->
  307. @next.called.should.equal true
  308. describe "when the user is not logged in", ->
  309. beforeEach ->
  310. @req.session = {}
  311. @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  312. @req.query = {}
  313. @middleware(@req, @res, @next)
  314. it "should redirect to the register or login page", ->
  315. @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true
  316. describe "requireGlobalLogin", ->
  317. beforeEach ->
  318. @req.headers = {}
  319. @AuthenticationController.httpAuth = sinon.stub()
  320. describe "with white listed url", ->
  321. beforeEach ->
  322. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  323. @req._parsedUrl.pathname = "/login"
  324. @AuthenticationController.requireGlobalLogin @req, @res, @next
  325. it "should call next() directly", ->
  326. @next.called.should.equal true
  327. describe "with white listed url and a query string", ->
  328. beforeEach ->
  329. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  330. @req._parsedUrl.pathname = "/login"
  331. @req.url = "/login?query=something"
  332. @AuthenticationController.requireGlobalLogin @req, @res, @next
  333. it "should call next() directly", ->
  334. @next.called.should.equal true
  335. describe "with http auth", ->
  336. beforeEach ->
  337. @req.headers["authorization"] = "Mock Basic Auth"
  338. @AuthenticationController.requireGlobalLogin @req, @res, @next
  339. it "should pass the request onto httpAuth", ->
  340. @AuthenticationController.httpAuth
  341. .calledWith(@req, @res, @next)
  342. .should.equal true
  343. describe "with a user session", ->
  344. beforeEach ->
  345. @req.session =
  346. user: {"mock": "user", "_id": "some_id"}
  347. @AuthenticationController.requireGlobalLogin @req, @res, @next
  348. it "should call next() directly", ->
  349. @next.called.should.equal true
  350. describe "with no login credentials", ->
  351. beforeEach ->
  352. @req.session = {}
  353. @AuthenticationController.requireGlobalLogin @req, @res, @next
  354. it "should redirect to the /login page", ->
  355. @res.redirectedTo.should.equal "/login"
  356. describe "_redirectToLoginOrRegisterPage", ->
  357. beforeEach ->
  358. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false })
  359. @req.session = {}
  360. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  361. @AuthenticationController._redirectToLoginPage = sinon.stub()
  362. @req.query = {}
  363. describe "they have come directly to the url", ->
  364. beforeEach ->
  365. @req.query = {}
  366. @middleware(@req, @res, @next)
  367. it "should redirect to the login page", ->
  368. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false
  369. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true
  370. describe "they have come via a templates link", ->
  371. beforeEach ->
  372. @req.query.zipUrl = "something"
  373. @middleware(@req, @res, @next)
  374. it "should redirect to the register page", ->
  375. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  376. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  377. describe "they have been invited to a project", ->
  378. beforeEach ->
  379. @req.query.project_name = "something"
  380. @middleware(@req, @res, @next)
  381. it "should redirect to the register page", ->
  382. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  383. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  384. describe "_redirectToRegisterPage", ->
  385. beforeEach ->
  386. @req.path = "/target/url"
  387. @req.query =
  388. extra_query: "foo"
  389. @AuthenticationController._redirectToRegisterPage(@req, @res)
  390. it "should redirect to the register page with a query string attached", ->
  391. @req.session.postLoginRedirect.should.equal '/target/url?extra_query=foo'
  392. @res.redirectedTo.should.equal "/register?extra_query=foo"
  393. it "should log out a message", ->
  394. @logger.log
  395. .calledWith(url: @url, "user not logged in so redirecting to register page")
  396. .should.equal true
  397. describe "_redirectToLoginPage", ->
  398. beforeEach ->
  399. @req.path = "/target/url"
  400. @req.query =
  401. extra_query: "foo"
  402. @AuthenticationController._redirectToLoginPage(@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 "/login?extra_query=foo"
  406. describe "_recordSuccessfulLogin", ->
  407. beforeEach ->
  408. @UserUpdater.updateUser = sinon.stub().callsArg(2)
  409. @AuthenticationController._recordSuccessfulLogin(@user._id, @callback)
  410. it "should increment the user.login.success metric", ->
  411. @Metrics.inc
  412. .calledWith("user.login.success")
  413. .should.equal true
  414. it "should update the user's login count and last logged in date", ->
  415. @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined
  416. @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1
  417. it "should call the callback", ->
  418. @callback.called.should.equal true
  419. describe "_recordFailedLogin", ->
  420. beforeEach ->
  421. @AuthenticationController._recordFailedLogin(@callback)
  422. it "should increment the user.login.failed metric", ->
  423. @Metrics.inc
  424. .calledWith("user.login.failed")
  425. .should.equal true
  426. it "should call the callback", ->
  427. @callback.called.should.equal true
  428. describe '_setRedirectInSession', ->
  429. beforeEach ->
  430. @req = {session: {}}
  431. @req.path = "/somewhere"
  432. @req.query = {one: "1"}
  433. it 'should set redirect property on session', ->
  434. @AuthenticationController._setRedirectInSession(@req)
  435. expect(@req.session.postLoginRedirect).to.equal "/somewhere?one=1"
  436. describe '_getRedirectFromSession', ->
  437. beforeEach ->
  438. @req = {session: {postLoginRedirect: "/a?b=c"}}
  439. it 'should get redirect property from session', ->
  440. expect(@AuthenticationController._getRedirectFromSession(@req)).to.equal "/a?b=c"
  441. describe '_clearRedirectFromSession', ->
  442. beforeEach ->
  443. @req = {session: {postLoginRedirect: "/a?b=c"}}
  444. it 'should remove the redirect property from session', ->
  445. @AuthenticationController._clearRedirectFromSession(@req)
  446. expect(@req.session.postLoginRedirect).to.equal undefined