AuthenticationControllerTests.coffee 19 KB

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