AuthenticationControllerTests.coffee 16 KB

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