AuthenticationControllerTests.coffee 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  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() }
  23. "settings-sharelatex": {}
  24. "../User/UserSessionsManager": @UserSessionsManager =
  25. trackSession: sinon.stub()
  26. untrackSession: sinon.stub()
  27. revokeAllUserSessions: sinon.stub().callsArgWith(1, null)
  28. @user =
  29. _id: ObjectId()
  30. email: @email = "USER@example.com"
  31. first_name: "bob"
  32. last_name: "brown"
  33. referal_id: 1234
  34. isAdmin: false
  35. @password = "banana"
  36. @req = new MockRequest()
  37. @res = new MockResponse()
  38. @callback = @next = sinon.stub()
  39. tk.freeze(Date.now())
  40. afterEach ->
  41. tk.reset()
  42. describe "login", ->
  43. beforeEach ->
  44. @AuthenticationController._recordFailedLogin = sinon.stub()
  45. @AuthenticationController._recordSuccessfulLogin = sinon.stub()
  46. @AuthenticationController.establishUserSession = sinon.stub().callsArg(2)
  47. @req.body =
  48. email: @email
  49. password: @password
  50. redir: @redir = "/path/to/redir/to"
  51. describe "when the users rate limit", ->
  52. it "should block the request if the limit has been exceeded", (done)->
  53. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, false)
  54. @res =
  55. send: (code)=>
  56. @res.statusCode.should.equal 429
  57. done()
  58. @AuthenticationController.login(@req, @res)
  59. describe 'when the user is authenticated', ->
  60. beforeEach ->
  61. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  62. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  63. @AuthenticationController.login(@req, @res)
  64. it "should attempt to authorise the user", ->
  65. @AuthenticationManager.authenticate
  66. .calledWith(email: @email.toLowerCase(), @password)
  67. .should.equal true
  68. it "should setup the user data in the background", ->
  69. @UserHandler.setupLoginData.calledWith(@user).should.equal true
  70. it "should establish the user's session", ->
  71. @AuthenticationController.establishUserSession
  72. .calledWith(@req, @user)
  73. .should.equal true
  74. it "should set res.session.justLoggedIn", ->
  75. @req.session.justLoggedIn.should.equal true
  76. it "should redirect the user to the specified location", ->
  77. expect(@res.body).to.deep.equal redir: @redir
  78. it "should record the successful login", ->
  79. @AuthenticationController._recordSuccessfulLogin
  80. .calledWith(@user._id)
  81. .should.equal true
  82. it "should tell the rate limiter that there was a success for that email", ->
  83. @LoginRateLimiter.recordSuccessfulLogin.calledWith(@email.toLowerCase()).should.equal true
  84. it "should log the successful login", ->
  85. @logger.log
  86. .calledWith(email: @email.toLowerCase(), user_id: @user._id.toString(), "successful log in")
  87. .should.equal true
  88. it "should track the login event", ->
  89. @AnalyticsManager.recordEvent
  90. .calledWith(@user._id, "user-logged-in")
  91. .should.equal true
  92. describe 'when the user is not authenticated', ->
  93. beforeEach ->
  94. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  95. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, null)
  96. @AuthenticationController.login(@req, @res)
  97. it "should return an error", ->
  98. # @res.body.should.exist
  99. expect(@res.body.message).to.exist
  100. # message:
  101. # text: 'Your email or password were incorrect. Please try again',
  102. # type: 'error'
  103. it "should not establish a session", ->
  104. @AuthenticationController.establishUserSession.called.should.equal false
  105. it "should not setup the user data in the background", ->
  106. @UserHandler.setupLoginData.called.should.equal false
  107. it "should record a failed login", ->
  108. @AuthenticationController._recordFailedLogin.called.should.equal true
  109. it "should log the failed login", ->
  110. @logger.log
  111. .calledWith(email: @email.toLowerCase(), "failed log in")
  112. .should.equal true
  113. describe "with a URL to a different domain", ->
  114. beforeEach ->
  115. @LoginRateLimiter.processLoginRequest.callsArgWith(1, null, true)
  116. @req.body.redir = "http://www.facebook.com/test"
  117. @AuthenticationManager.authenticate = sinon.stub().callsArgWith(2, null, @user)
  118. @AuthenticationController.login(@req, @res)
  119. it "should only redirect to the local path", ->
  120. expect(@res.body).to.deep.equal redir: "/test"
  121. describe "getLoggedInUserId", ->
  122. beforeEach ->
  123. @req =
  124. session :{}
  125. it "should return the user id from the session", (done)->
  126. @user_id = "2134"
  127. @req.session.user =
  128. _id:@user_id
  129. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  130. expect(user_id).to.equal @user_id
  131. done()
  132. it "should return null if there is no user on the session", (done)->
  133. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  134. expect(user_id).to.be.null
  135. done()
  136. it "should return null if there is no session", (done)->
  137. @req = {}
  138. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  139. expect(user_id).to.be.null
  140. done()
  141. it "should return null if there is no req", (done)->
  142. @req = {}
  143. @AuthenticationController.getLoggedInUserId @req, (err, user_id)=>
  144. expect(user_id).to.be.null
  145. done()
  146. describe "getLoggedInUser", ->
  147. beforeEach ->
  148. @UserGetter.getUser = sinon.stub().callsArgWith(1, null, @user)
  149. describe "with an established session", ->
  150. beforeEach ->
  151. @req.session =
  152. user: @user
  153. @AuthenticationController.getLoggedInUser(@req, @callback)
  154. it "should look up the user in the database", ->
  155. @UserGetter.getUser
  156. .calledWith(@user._id)
  157. .should.equal true
  158. it "should return the user", ->
  159. @callback.calledWith(null, @user).should.equal true
  160. describe "requireLogin", ->
  161. beforeEach ->
  162. @user =
  163. _id: "user-id-123"
  164. email: "user@sharelatex.com"
  165. @middleware = @AuthenticationController.requireLogin()
  166. describe "when the user is logged in", ->
  167. beforeEach ->
  168. @req.session =
  169. user: @user = {
  170. _id: "user-id-123"
  171. email: "user@sharelatex.com"
  172. }
  173. @middleware(@req, @res, @next)
  174. it "should set the user property on the request", ->
  175. @req.user.should.deep.equal @user
  176. it "should call the next method in the chain", ->
  177. @next.called.should.equal true
  178. describe "when the user is not logged in", ->
  179. beforeEach ->
  180. @req.session = {}
  181. @AuthenticationController._redirectToLoginOrRegisterPage = sinon.stub()
  182. @req.query = {}
  183. @middleware(@req, @res, @next)
  184. it "should redirect to the register or login page", ->
  185. @AuthenticationController._redirectToLoginOrRegisterPage.calledWith(@req, @res).should.equal true
  186. describe "requireGlobalLogin", ->
  187. beforeEach ->
  188. @req.headers = {}
  189. @AuthenticationController.httpAuth = sinon.stub()
  190. describe "with white listed url", ->
  191. beforeEach ->
  192. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  193. @req._parsedUrl.pathname = "/login"
  194. @AuthenticationController.requireGlobalLogin @req, @res, @next
  195. it "should call next() directly", ->
  196. @next.called.should.equal true
  197. describe "with white listed url and a query string", ->
  198. beforeEach ->
  199. @AuthenticationController.addEndpointToLoginWhitelist "/login"
  200. @req._parsedUrl.pathname = "/login"
  201. @req.url = "/login?query=something"
  202. @AuthenticationController.requireGlobalLogin @req, @res, @next
  203. it "should call next() directly", ->
  204. @next.called.should.equal true
  205. describe "with http auth", ->
  206. beforeEach ->
  207. @req.headers["authorization"] = "Mock Basic Auth"
  208. @AuthenticationController.requireGlobalLogin @req, @res, @next
  209. it "should pass the request onto httpAuth", ->
  210. @AuthenticationController.httpAuth
  211. .calledWith(@req, @res, @next)
  212. .should.equal true
  213. describe "with a user session", ->
  214. beforeEach ->
  215. @req.session =
  216. user: {"mock": "user"}
  217. @AuthenticationController.requireGlobalLogin @req, @res, @next
  218. it "should call next() directly", ->
  219. @next.called.should.equal true
  220. describe "with no login credentials", ->
  221. beforeEach ->
  222. @AuthenticationController.requireGlobalLogin @req, @res, @next
  223. it "should redirect to the /login page", ->
  224. @res.redirectedTo.should.equal "/login"
  225. describe "_redirectToLoginOrRegisterPage", ->
  226. beforeEach ->
  227. @middleware = @AuthenticationController.requireLogin(@options = { load_from_db: false })
  228. @req.session = {}
  229. @AuthenticationController._redirectToRegisterPage = sinon.stub()
  230. @AuthenticationController._redirectToLoginPage = sinon.stub()
  231. @req.query = {}
  232. describe "they have come directly to the url", ->
  233. beforeEach ->
  234. @req.query = {}
  235. @middleware(@req, @res, @next)
  236. it "should redirect to the login page", ->
  237. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal false
  238. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal true
  239. describe "they have come via a templates link", ->
  240. beforeEach ->
  241. @req.query.zipUrl = "something"
  242. @middleware(@req, @res, @next)
  243. it "should redirect to the register page", ->
  244. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  245. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  246. describe "they have been invited to a project", ->
  247. beforeEach ->
  248. @req.query.project_name = "something"
  249. @middleware(@req, @res, @next)
  250. it "should redirect to the register page", ->
  251. @AuthenticationController._redirectToRegisterPage.calledWith(@req, @res).should.equal true
  252. @AuthenticationController._redirectToLoginPage.calledWith(@req, @res).should.equal false
  253. describe "_redirectToRegisterPage", ->
  254. beforeEach ->
  255. @req.path = "/target/url"
  256. @req.query =
  257. extra_query: "foo"
  258. @AuthenticationController._redirectToRegisterPage(@req, @res)
  259. it "should redirect to the register page with a query string attached", ->
  260. @res.redirectedTo
  261. .should.equal "/register?extra_query=foo&redir=%2Ftarget%2Furl"
  262. it "should log out a message", ->
  263. @logger.log
  264. .calledWith(url: @url, "user not logged in so redirecting to register page")
  265. .should.equal true
  266. describe "_redirectToLoginPage", ->
  267. beforeEach ->
  268. @req.path = "/target/url"
  269. @req.query =
  270. extra_query: "foo"
  271. @AuthenticationController._redirectToLoginPage(@req, @res)
  272. it "should redirect to the register page with a query string attached", ->
  273. @res.redirectedTo.should.equal "/login?extra_query=foo&redir=%2Ftarget%2Furl"
  274. describe "_recordSuccessfulLogin", ->
  275. beforeEach ->
  276. @UserUpdater.updateUser = sinon.stub().callsArg(2)
  277. @AuthenticationController._recordSuccessfulLogin(@user._id, @callback)
  278. it "should increment the user.login.success metric", ->
  279. @Metrics.inc
  280. .calledWith("user.login.success")
  281. .should.equal true
  282. it "should update the user's login count and last logged in date", ->
  283. @UserUpdater.updateUser.args[0][1]["$set"]["lastLoggedIn"].should.not.equal undefined
  284. @UserUpdater.updateUser.args[0][1]["$inc"]["loginCount"].should.equal 1
  285. it "should call the callback", ->
  286. @callback.called.should.equal true
  287. describe "_recordFailedLogin", ->
  288. beforeEach ->
  289. @AuthenticationController._recordFailedLogin(@callback)
  290. it "should increment the user.login.failed metric", ->
  291. @Metrics.inc
  292. .calledWith("user.login.failed")
  293. .should.equal true
  294. it "should call the callback", ->
  295. @callback.called.should.equal true
  296. describe "establishUserSession", ->
  297. beforeEach ->
  298. @req.session =
  299. save: sinon.stub().callsArg(0)
  300. destroy : sinon.stub()
  301. @req.sessionStore =
  302. generate: sinon.stub()
  303. @req.ip = "1.2.3.4"
  304. @AuthenticationController.establishUserSession @req, @user, @callback
  305. it "should set the session user to a basic version of the user", ->
  306. @req.session.user._id.should.equal @user._id
  307. @req.session.user.email.should.equal @user.email
  308. @req.session.user.first_name.should.equal @user.first_name
  309. @req.session.user.last_name.should.equal @user.last_name
  310. @req.session.user.referal_id.should.equal @user.referal_id
  311. @req.session.user.isAdmin.should.equal @user.isAdmin
  312. @req.session.user.ip_address.should.equal @req.ip
  313. expect(typeof @req.session.user.ip_address).to.equal 'string'
  314. expect(typeof @req.session.user.session_created).to.equal 'string'
  315. it "should destroy the session", ->
  316. @req.session.destroy.called.should.equal true
  317. it "should regenerate the session to protect against session fixation", ->
  318. @req.sessionStore.generate.calledWith(@req).should.equal true
  319. it "should return the callback", ->
  320. @callback.called.should.equal true