AuthenticationControllerTests.coffee 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 = {passport: {user: @user}}
  84. @req.session.destroy = sinon.stub()
  85. @req.session.save = sinon.stub().callsArgWith(0, null)
  86. @req.sessionStore = {generate: sinon.stub()}
  87. @passport.authenticate.callsArgWith(1, null, @user, @info)
  88. it 'should call passport.authenticate', () ->
  89. @AuthenticationController.passportLogin @req, @res, @next
  90. @passport.authenticate.callCount.should.equal 1
  91. describe 'when authenticate produces an error', ->
  92. beforeEach ->
  93. @err = new Error('woops')
  94. @passport.authenticate.callsArgWith(1, @err)
  95. it 'should return next with an error', () ->
  96. @AuthenticationController.passportLogin @req, @res, @next
  97. @next.calledWith(@err).should.equal true
  98. describe 'when authenticate produces a user', ->
  99. beforeEach ->
  100. @req._redir = 'some_redirect'
  101. @passport.authenticate.callsArgWith(1, null, @user, @info)
  102. afterEach ->
  103. delete @req._redir
  104. it 'should call req.login', () ->
  105. @AuthenticationController.passportLogin @req, @res, @next
  106. @req.login.callCount.should.equal 1
  107. @req.login.calledWith(@user).should.equal true
  108. it 'should send a json response with redirect', () ->
  109. @AuthenticationController.passportLogin @req, @res, @next
  110. @res.json.callCount.should.equal 1
  111. @res.json.calledWith({redir: @req._redir}).should.equal true
  112. describe 'when session.save produces an error', () ->
  113. beforeEach ->
  114. @req.session.save = sinon.stub().callsArgWith(0, new Error('woops'))
  115. it 'should return next with an error', () ->
  116. @AuthenticationController.passportLogin @req, @res, @next
  117. @next.calledWith(@err).should.equal true
  118. it 'should not return json', () ->
  119. @AuthenticationController.passportLogin @req, @res, @next
  120. @res.json.callCount.should.equal 0
  121. describe 'when authenticate does not produce a user', ->
  122. beforeEach ->
  123. @info = {text: 'a', type: 'b'}
  124. @passport.authenticate.callsArgWith(1, null, false, @info)
  125. it 'should not call req.login', () ->
  126. @AuthenticationController.passportLogin @req, @res, @next
  127. @req.login.callCount.should.equal 0
  128. it 'should send a json response with redirect', () ->
  129. @AuthenticationController.passportLogin @req, @res, @next
  130. @res.json.callCount.should.equal 1
  131. @res.json.calledWith({message: @info}).should.equal true
  132. describe 'getSessionUser', ->
  133. it 'should get the user object from session', ->
  134. @req.session =
  135. passport:
  136. user: {_id: 'one'}
  137. user = @AuthenticationController.getSessionUser(@req)
  138. expect(user).to.deep.equal {_id: 'one'}
  139. it 'should work with legacy sessions', ->
  140. @req.session =
  141. user: {_id: 'one'}
  142. user = @AuthenticationController.getSessionUser(@req)
  143. expect(user).to.deep.equal {_id: 'one'}
  144. describe "doPassportLogin", ->
  145. beforeEach ->
  146. @AuthenticationController._recordFailedLogin = sinon.stub()
  147. @AuthenticationController._recordSuccessfulLogin = sinon.stub()
  148. # @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  149. @req.body =
  150. email: @email
  151. password: @password
  152. redir: @redir = "/path/to/redir/to"
  153. @cb = sinon.stub()
  154. describe "when the users rate limit", ->
  155. beforeEach ->
  156. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  157. it "should block the request if the limit has been exceeded", (done)->
  158. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  159. @cb.callCount.should.equal 1
  160. @cb.calledWith(null, null).should.equal true
  161. done()
  162. describe 'when the user is authenticated', ->
  163. beforeEach ->
  164. @cb = sinon.stub()
  165. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  166. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  167. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  168. it "should attempt to authorise the user", ->
  169. @AuthenticationManager.authenticate
  170. .calledWith(email: @email.toLowerCase(), @password)
  171. .should.equal true
  172. it "should setup the user data in the background", ->
  173. @UserHandler.setupLoginData.calledWith(@user).should.equal true
  174. it "should establish the user's session", ->
  175. @cb.calledWith(null, @user).should.equal true
  176. it "should set res.session.justLoggedIn", ->
  177. @req.session.justLoggedIn.should.equal true
  178. it "should redirect the user to the specified location", ->
  179. expect(@req._redir).to.deep.equal @redir
  180. it "should record the successful login", ->
  181. @AuthenticationController._recordSuccessfulLogin
  182. .calledWith(@user._id)
  183. .should.equal true
  184. it "should tell the rate limiter that there was a success for that email", ->
  185. @LoginRateLimiter.recordSuccessfulLogin.calledWith(@email.toLowerCase()).should.equal true
  186. it "should log the successful login", ->
  187. @logger.log
  188. .calledWith(email: @email.toLowerCase(), user_id: @user._id.toString(), "successful log in")
  189. .should.equal true
  190. it "should track the login event", ->
  191. @AnalyticsManager.recordEvent
  192. .calledWith(@user._id, "user-logged-in")
  193. .should.equal true
  194. describe 'when the user is not authenticated', ->
  195. beforeEach ->
  196. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  197. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null)
  198. @cb = sinon.stub()
  199. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  200. it "should not establish the login", ->
  201. @cb.callCount.should.equal 1
  202. @cb.calledWith(null, false)
  203. # @res.body.should.exist
  204. expect(@cb.lastCall.args[2]).to.contain.all.keys ['text', 'type']
  205. # message:
  206. # text: 'Your email or password were incorrect. Please try again',
  207. # type: 'error'
  208. it "should not setup the user data in the background", ->
  209. @UserHandler.setupLoginData.called.should.equal false
  210. it "should record a failed login", ->
  211. @AuthenticationController._recordFailedLogin.called.should.equal true
  212. it "should log the failed login", ->
  213. @logger.log
  214. .calledWith(email: @email.toLowerCase(), "failed log in")
  215. .should.equal true
  216. describe "with a URL to a different domain", ->
  217. beforeEach ->
  218. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  219. @req.body.redir = "http://www.facebook.com/test"
  220. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  221. @cb = sinon.stub()
  222. @AuthenticationController.doPassportLogin(@req, @req.body.email, @req.body.password, @cb)
  223. it "should only redirect to the local path", ->
  224. expect(@req._redir).to.equal "/test"
  225. describe "getLoggedInUserId", ->
  226. beforeEach ->
  227. @req =
  228. session :{}
  229. it "should return the user id from the session", ()->
  230. @user_id = "2134"
  231. @req.session.user =
  232. _id:@user_id
  233. result = @AuthenticationController.getLoggedInUserId @req
  234. expect(result).to.equal @user_id
  235. it 'should return user for passport session', () ->
  236. @user_id = "2134"
  237. @req.session = {
  238. passport: {
  239. user: {
  240. _id:@user_id
  241. }
  242. }
  243. }
  244. result = @AuthenticationController.getLoggedInUserId @req
  245. expect(result).to.equal @user_id
  246. it "should return null if there is no user on the session", ()->
  247. result = @AuthenticationController.getLoggedInUserId @req
  248. expect(result).to.equal null
  249. it "should return null if there is no session", ()->
  250. @req = {}
  251. result = @AuthenticationController.getLoggedInUserId @req
  252. expect(result).to.equal null
  253. it "should return null if there is no req", ()->
  254. @req = {}
  255. result = @AuthenticationController.getLoggedInUserId @req
  256. expect(result).to.equal null
  257. describe "requireLogin", ->
  258. beforeEach ->
  259. @user =
  260. _id: "user-id-123"
  261. email: "user@sharelatex.com"
  262. @middleware = @AuthenticationController.requireLogin()
  263. describe "when the user is logged in", ->
  264. beforeEach ->
  265. @req.session =
  266. user: @user = {
  267. _id: "user-id-123"
  268. email: "user@sharelatex.com"
  269. }
  270. @middleware(@req, @res, @next)
  271. it "should call the next method in the chain", ->
  272. @next.called.should.equal true
  273. describe "when the user is not logged in", ->
  274. beforeEach ->
  275. @req.session = {}
  276. @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  277. @req.query = {}
  278. @middleware(@req, @res, @next)
  279. it "should redirect to the register or login page", ->
  280. @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true
  281. describe "requireGlobalLogin", ->
  282. beforeEach ->
  283. @req.headers = {}
  284. @AuthenticationController.httpAuth = sinon.stub()
  285. describe "with white listed url", ->
  286. beforeEach ->
  287. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  288. @req._parsedUrl.pathname = "/login"
  289. @AuthenticationController.requireGlobalLogin @req, @res, @next
  290. it "should call next() directly", ->
  291. @next.called.should.equal true
  292. describe "with white listed url and a query string", ->
  293. beforeEach ->
  294. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  295. @req._parsedUrl.pathname = "/login"
  296. @req.url = "/login?query=something"
  297. @AuthenticationController.requireGlobalLogin @req, @res, @next
  298. it "should call next() directly", ->
  299. @next.called.should.equal true
  300. describe "with http auth", ->
  301. beforeEach ->
  302. @req.headers["authorization"] = "Mock Basic Auth"
  303. @AuthenticationController.requireGlobalLogin @req, @res, @next
  304. it "should pass the request onto httpAuth", ->
  305. @AuthenticationController.httpAuth
  306. .calledWith(@req, @res, @next)
  307. .should.equal true
  308. describe "with a user session", ->
  309. beforeEach ->
  310. @req.session =
  311. user: {"mock": "user", "_id": "some_id"}
  312. @AuthenticationController.requireGlobalLogin @req, @res, @next
  313. it "should call next() directly", ->
  314. @next.called.should.equal true
  315. describe "with no login credentials", ->
  316. beforeEach ->
  317. @req.session = {}
  318. @AuthenticationController.requireGlobalLogin @req, @res, @next
  319. it "should redirect to the /login page", ->
  320. @res.redirectedTo.should.equal "/login"
  321. describe "_redirectToLoginOrRegisterPage", ->
  322. beforeEach ->
  323. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false })
  324. @req.session = {}
  325. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  326. @AuthenticationController._redirectToLoginPage = sinon.stub()
  327. @req.query = {}
  328. describe "they have come directly to the url", ->
  329. beforeEach ->
  330. @req.query = {}
  331. @middleware(@req, @res, @next)
  332. it "should redirect to the login page", ->
  333. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false
  334. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true
  335. describe "they have come via a templates link", ->
  336. beforeEach ->
  337. @req.query.zipUrl = "something"
  338. @middleware(@req, @res, @next)
  339. it "should redirect to the register page", ->
  340. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  341. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  342. describe "they have been invited to a project", ->
  343. beforeEach ->
  344. @req.query.project_name = "something"
  345. @middleware(@req, @res, @next)
  346. it "should redirect to the register page", ->
  347. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  348. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  349. describe "_redirectToRegisterPage", ->
  350. beforeEach ->
  351. @req.path = "/target/url"
  352. @req.query =
  353. extra_query: "foo"
  354. @AuthenticationController._redirectToRegisterPage(@req, @res)
  355. it "should redirect to the register page with a query string attached", ->
  356. @res.redirectedTo
  357. .should.equal "/register?extra_query=foo&redir=%2Ftarget%2Furl"
  358. it "should log out a message", ->
  359. @logger.log
  360. .calledWith(url: @url, "user not logged in so redirecting to register page")
  361. .should.equal true
  362. describe "_redirectToLoginPage", ->
  363. beforeEach ->
  364. @req.path = "/target/url"
  365. @req.query =
  366. extra_query: "foo"
  367. @AuthenticationController._redirectToLoginPage(@req, @res)
  368. it "should redirect to the register page with a query string attached", ->
  369. @res.redirectedTo.should.equal "/login?extra_query=foo&redir=%2Ftarget%2Furl"
  370. describe "_recordSuccessfulLogin", ->
  371. beforeEach ->
  372. @UserUpdater.updateUser = sinon.stub().callsArg(2)
  373. @AuthenticationController._recordSuccessfulLogin(@user._id, @callback)
  374. it "should increment the user.login.success metric", ->
  375. @Metrics.inc
  376. .calledWith("user.login.success")
  377. .should.equal true
  378. it "should update the user's login count and last logged in date", ->
  379. @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined
  380. @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1
  381. it "should call the callback", ->
  382. @callback.called.should.equal true
  383. describe "_recordFailedLogin", ->
  384. beforeEach ->
  385. @AuthenticationController._recordFailedLogin(@callback)
  386. it "should increment the user.login.failed metric", ->
  387. @Metrics.inc
  388. .calledWith("user.login.failed")
  389. .should.equal true
  390. it "should call the callback", ->
  391. @callback.called.should.equal true