AuthenticationControllerTests.coffee 15 KB

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