AuthenticationControllerTests.coffee 16 KB

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