diff --git a/services/web/app/coffee/Features/Authorization/AuthorizationMiddlewear.coffee b/services/web/app/coffee/Features/Authorization/AuthorizationMiddlewear.coffee index f321b015f6..96fcc5c583 100644 --- a/services/web/app/coffee/Features/Authorization/AuthorizationMiddlewear.coffee +++ b/services/web/app/coffee/Features/Authorization/AuthorizationMiddlewear.coffee @@ -100,7 +100,7 @@ module.exports = AuthorizationMiddlewear = res.redirect "/restricted" restricted : (req, res, next)-> - if AuthenticationController.isUserLoggedIn()? + if AuthenticationController.isUserLoggedIn(req) res.render 'user/restricted', title:'restricted' else diff --git a/services/web/app/coffee/Features/Project/ProjectController.coffee b/services/web/app/coffee/Features/Project/ProjectController.coffee index 28af4fbf8d..8c07c8a77f 100644 --- a/services/web/app/coffee/Features/Project/ProjectController.coffee +++ b/services/web/app/coffee/Features/Project/ProjectController.coffee @@ -89,7 +89,7 @@ module.exports = ProjectController = project_id = req.params.Project_id projectName = req.body.projectName logger.log project_id:project_id, projectName:projectName, "cloning project" - if !AuthenticationController.isUserLoggedIn()? + if !AuthenticationController.isUserLoggedIn() return res.send redir:"/register" currentUser = AuthenticationController.getSessionUser(req) projectDuplicator.duplicate currentUser, project_id, projectName, (err, project)-> @@ -186,7 +186,7 @@ module.exports = ProjectController = if !Settings.editorIsOpen return res.render("general/closed", {title:"updating_site"}) - if AuthenticationController.isUserLoggedIn(req)? + if AuthenticationController.isUserLoggedIn(req) user_id = AuthenticationController.getLoggedInUserId(req) anonymous = false else diff --git a/services/web/app/coffee/Features/Referal/ReferalMiddleware.coffee b/services/web/app/coffee/Features/Referal/ReferalMiddleware.coffee index ccfe7a802f..77cbef5254 100644 --- a/services/web/app/coffee/Features/Referal/ReferalMiddleware.coffee +++ b/services/web/app/coffee/Features/Referal/ReferalMiddleware.coffee @@ -3,7 +3,7 @@ AuthenticationController = require('../Authentication/AuthenticationController') module.exports = RefererMiddleware = getUserReferalId: (req, res, next) -> - if AuthenticationController.isUserLoggedIn()? + if AuthenticationController.isUserLoggedIn() user = AuthenticationController.getSessionUser(req) req.user.referal_id = user.referal_id next() diff --git a/services/web/app/coffee/Features/StaticPages/HomeController.coffee b/services/web/app/coffee/Features/StaticPages/HomeController.coffee index 3535c6c5eb..6675d55333 100755 --- a/services/web/app/coffee/Features/StaticPages/HomeController.coffee +++ b/services/web/app/coffee/Features/StaticPages/HomeController.coffee @@ -11,7 +11,7 @@ homepageExists = fs.existsSync Path.resolve(__dirname + "/../../../views/externa module.exports = HomeController = index : (req,res)-> - if AuthenticationController.isUserLoggedIn(req)? + if AuthenticationController.isUserLoggedIn(req) if req.query.scribtex_path? res.redirect "/project?scribtex_path=#{req.query.scribtex_path}" else diff --git a/services/web/app/coffee/Features/Subscription/SubscriptionController.coffee b/services/web/app/coffee/Features/Subscription/SubscriptionController.coffee index e9ccefe2c8..19ade80488 100644 --- a/services/web/app/coffee/Features/Subscription/SubscriptionController.coffee +++ b/services/web/app/coffee/Features/Subscription/SubscriptionController.coffee @@ -13,7 +13,7 @@ module.exports = SubscriptionController = plansPage: (req, res, next) -> plans = SubscriptionViewModelBuilder.buildViewModel() - if AuthenticationController.isUserLoggedIn(req)? + if AuthenticationController.isUserLoggedIn(req) baseUrl = "/register?redir=" else baseUrl = "" diff --git a/services/web/test/UnitTests/coffee/Authorization/AuthorizationMiddlewearTests.coffee b/services/web/test/UnitTests/coffee/Authorization/AuthorizationMiddlewearTests.coffee index bc62e603de..8631938807 100644 --- a/services/web/test/UnitTests/coffee/Authorization/AuthorizationMiddlewearTests.coffee +++ b/services/web/test/UnitTests/coffee/Authorization/AuthorizationMiddlewearTests.coffee @@ -8,19 +8,23 @@ Errors = require "../../../../app/js/Features/Errors/Errors.js" describe "AuthorizationMiddlewear", -> beforeEach -> + @user_id = "user-id-123" + @project_id = "project-id-123" + @AuthenticationController = + getLoggedInUserId: sinon.stub().returns(@user_id) + isUserLoggedIn: sinon.stub().returns(true) @AuthorizationMiddlewear = SandboxedModule.require modulePath, requires: "./AuthorizationManager": @AuthorizationManager = {} "logger-sharelatex": {log: () ->} "mongojs": ObjectId: @ObjectId = {} "../Errors/Errors": Errors - @user_id = "user-id-123" - @project_id = "project-id-123" + '../Authentication/AuthenticationController': @AuthenticationController @req = {} @res = {} @ObjectId.isValid = sinon.stub() @ObjectId.isValid.withArgs(@project_id).returns true @next = sinon.stub() - + METHODS_TO_TEST = { "ensureUserCanReadProject": "canUserReadProject" "ensureUserCanWriteProjectSettings": "canUserWriteProjectSettings" @@ -35,26 +39,25 @@ describe "AuthorizationMiddlewear", -> project_id: @project_id @AuthorizationManager[managerMethod] = sinon.stub() @AuthorizationMiddlewear.redirectToRestricted = sinon.stub() - + describe "with missing project_id", -> beforeEach -> @req.params = {} - + it "should return an error to next", -> @AuthorizationMiddlewear[middlewearMethod] @req, @res, @next @next.calledWith(new Error()).should.equal true describe "with logged in user", -> beforeEach -> - @req.session = - user: _id: @user_id + @AuthenticationController.getLoggedInUserId.returns(@user_id) describe "when user has permission", -> beforeEach -> @AuthorizationManager[managerMethod] .withArgs(@user_id, @project_id) .yields(null, true) - + it "should return next", -> @AuthorizationMiddlewear[middlewearMethod] @req, @res, @next @next.called.should.equal true @@ -64,49 +67,51 @@ describe "AuthorizationMiddlewear", -> @AuthorizationManager[managerMethod] .withArgs(@user_id, @project_id) .yields(null, false) - + it "should redirect to redirectToRestricted", -> @AuthorizationMiddlewear[middlewearMethod] @req, @res, @next @next.called.should.equal false @AuthorizationMiddlewear.redirectToRestricted .calledWith(@req, @res, @next) .should.equal true - + describe "with anonymous user", -> describe "when user has permission", -> beforeEach -> + @AuthenticationController.getLoggedInUserId.returns(null) @AuthorizationManager[managerMethod] .withArgs(null, @project_id) .yields(null, true) - + it "should return next", -> @AuthorizationMiddlewear[middlewearMethod] @req, @res, @next @next.called.should.equal true describe "when user doesn't have permission", -> beforeEach -> + @AuthenticationController.getLoggedInUserId.returns(null) @AuthorizationManager[managerMethod] .withArgs(null, @project_id) .yields(null, false) - + it "should redirect to redirectToRestricted", -> @AuthorizationMiddlewear[middlewearMethod] @req, @res, @next @next.called.should.equal false @AuthorizationMiddlewear.redirectToRestricted .calledWith(@req, @res, @next) .should.equal true - + describe "with malformed project id", -> beforeEach -> @req.params = project_id: "blah" @ObjectId.isValid = sinon.stub().returns false - + it "should return a not found error", (done) -> @AuthorizationMiddlewear[middlewearMethod] @req, @res, (error) -> error.should.be.instanceof Errors.NotFoundError done() - + describe "ensureUserIsSiteAdmin", -> beforeEach -> @AuthorizationManager.isUserSiteAdmin = sinon.stub() @@ -114,15 +119,14 @@ describe "AuthorizationMiddlewear", -> describe "with logged in user", -> beforeEach -> - @req.session = - user: _id: @user_id + @AuthenticationController.getLoggedInUserId.returns(@user_id) describe "when user has permission", -> beforeEach -> @AuthorizationManager.isUserSiteAdmin .withArgs(@user_id) .yields(null, true) - + it "should return next", -> @AuthorizationMiddlewear.ensureUserIsSiteAdmin @req, @res, @next @next.called.should.equal true @@ -132,49 +136,50 @@ describe "AuthorizationMiddlewear", -> @AuthorizationManager.isUserSiteAdmin .withArgs(@user_id) .yields(null, false) - + it "should redirect to redirectToRestricted", -> @AuthorizationMiddlewear.ensureUserIsSiteAdmin @req, @res, @next @next.called.should.equal false @AuthorizationMiddlewear.redirectToRestricted .calledWith(@req, @res, @next) .should.equal true - + describe "with anonymous user", -> describe "when user has permission", -> beforeEach -> + @AuthenticationController.getLoggedInUserId.returns(null) @AuthorizationManager.isUserSiteAdmin .withArgs(null) .yields(null, true) - + it "should return next", -> @AuthorizationMiddlewear.ensureUserIsSiteAdmin @req, @res, @next @next.called.should.equal true describe "when user doesn't have permission", -> beforeEach -> + @AuthenticationController.getLoggedInUserId.returns(null) @AuthorizationManager.isUserSiteAdmin .withArgs(null) .yields(null, false) - + it "should redirect to redirectToRestricted", -> @AuthorizationMiddlewear.ensureUserIsSiteAdmin @req, @res, @next @next.called.should.equal false @AuthorizationMiddlewear.redirectToRestricted .calledWith(@req, @res, @next) .should.equal true - + describe "ensureUserCanReadMultipleProjects", -> beforeEach -> @AuthorizationManager.canUserReadProject = sinon.stub() @AuthorizationMiddlewear.redirectToRestricted = sinon.stub() @req.query = project_ids: "project1,project2" - + describe "with logged in user", -> beforeEach -> - @req.session = - user: _id: @user_id + @AuthenticationController.getLoggedInUserId.returns(@user_id) describe "when user has permission to access all projects", -> beforeEach -> @@ -184,7 +189,7 @@ describe "AuthorizationMiddlewear", -> @AuthorizationManager.canUserReadProject .withArgs(@user_id, "project2") .yields(null, true) - + it "should return next", -> @AuthorizationMiddlewear.ensureUserCanReadMultipleProjects @req, @res, @next @next.called.should.equal true @@ -197,38 +202,40 @@ describe "AuthorizationMiddlewear", -> @AuthorizationManager.canUserReadProject .withArgs(@user_id, "project2") .yields(null, false) - + it "should redirect to redirectToRestricted", -> @AuthorizationMiddlewear.ensureUserCanReadMultipleProjects @req, @res, @next @next.called.should.equal false @AuthorizationMiddlewear.redirectToRestricted .calledWith(@req, @res, @next) .should.equal true - + describe "with anonymous user", -> describe "when user has permission", -> describe "when user has permission to access all projects", -> beforeEach -> + @AuthenticationController.getLoggedInUserId.returns(null) @AuthorizationManager.canUserReadProject .withArgs(null, "project1") .yields(null, true) @AuthorizationManager.canUserReadProject .withArgs(null, "project2") .yields(null, true) - + it "should return next", -> @AuthorizationMiddlewear.ensureUserCanReadMultipleProjects @req, @res, @next @next.called.should.equal true describe "when user doesn't have permission to access one of the projects", -> beforeEach -> + @AuthenticationController.getLoggedInUserId.returns(null) @AuthorizationManager.canUserReadProject .withArgs(null, "project1") .yields(null, true) @AuthorizationManager.canUserReadProject .withArgs(null, "project2") .yields(null, false) - + it "should redirect to redirectToRestricted", -> @AuthorizationMiddlewear.ensureUserCanReadMultipleProjects @req, @res, @next @next.called.should.equal false diff --git a/services/web/test/UnitTests/coffee/Chat/ChatControllerTests.coffee b/services/web/test/UnitTests/coffee/Chat/ChatControllerTests.coffee index d2ebe41c63..a491e4b499 100644 --- a/services/web/test/UnitTests/coffee/Chat/ChatControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/Chat/ChatControllerTests.coffee @@ -10,19 +10,24 @@ describe "ChatController", -> beforeEach -> + @user_id = 'ier_' @settings = {} - @ChatHandler = + @ChatHandler = sendMessage:sinon.stub() getMessages:sinon.stub() @EditorRealTimeController = emitToRoom:sinon.stub().callsArgWith(3) + + @AuthenticationController = + getLoggedInUserId: sinon.stub().returns(@user_id) @ChatController = SandboxedModule.require modulePath, requires: "settings-sharelatex":@settings "logger-sharelatex": log:-> "./ChatHandler":@ChatHandler "../Editor/EditorRealTimeController":@EditorRealTimeController - @query = + '../Authentication/AuthenticationController': @AuthenticationController + @query = before:"some time" @req = @@ -74,4 +79,3 @@ describe "ChatController", -> sentMessages.should.deep.equal messages done() @ChatController.getMessages @req, @res - diff --git a/services/web/test/UnitTests/coffee/Collaborators/CollaboratorsInviteControllerTests.coffee b/services/web/test/UnitTests/coffee/Collaborators/CollaboratorsInviteControllerTests.coffee index 0144583f05..96f25906e9 100644 --- a/services/web/test/UnitTests/coffee/Collaborators/CollaboratorsInviteControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/Collaborators/CollaboratorsInviteControllerTests.coffee @@ -11,7 +11,11 @@ ObjectId = require("mongojs").ObjectId describe "CollaboratorsInviteController", -> beforeEach -> + @user = + _id: 'id' @AnalyticsManger = recordEvent: sinon.stub() + @AuthenticationController = + getSessionUser: (req) => req.session.user @CollaboratorsInviteController = SandboxedModule.require modulePath, requires: "../Project/ProjectGetter": @ProjectGetter = {} '../Subscription/LimitationsManager' : @LimitationsManager = {} @@ -22,6 +26,7 @@ describe "CollaboratorsInviteController", -> "../Editor/EditorRealTimeController": @EditorRealTimeController = {emitToRoom: sinon.stub()} "../Notifications/NotificationsBuilder": @NotificationsBuilder = {} "../Analytics/AnalyticsManager": @AnalyticsManger + '../Authentication/AuthenticationController': @AuthenticationController @res = new MockResponse() @req = new MockRequest() diff --git a/services/web/test/UnitTests/coffee/Compile/CompileControllerTests.coffee b/services/web/test/UnitTests/coffee/Compile/CompileControllerTests.coffee index d7a13578e2..9874b77265 100644 --- a/services/web/test/UnitTests/coffee/Compile/CompileControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/Compile/CompileControllerTests.coffee @@ -10,10 +10,17 @@ MockResponse = require "../helpers/MockResponse" describe "CompileController", -> beforeEach -> - @CompileManager = + @user_id = 'wat' + @user = + _id: @user_id + email: 'user@example.com' + features: + compileGroup: "premium" + compileTimeout: 100 + @CompileManager = compile: sinon.stub() @ClsiManager = {} - @UserGetter = + @UserGetter = getUser:sinon.stub() @RateLimiter = {addCount:sinon.stub()} @settings = @@ -23,8 +30,13 @@ describe "CompileController", -> clsi_priority: url: "clsi-priority.example.com" @jar = {cookie:"stuff"} - @ClsiCookieManager = + @ClsiCookieManager = getCookieJar:sinon.stub().callsArgWith(1, null, @jar) + @AuthenticationController = + getLoggedInUser: sinon.stub().callsArgWith(1, null, @user) + getLoggedInUserId: sinon.stub().returns(@user_id) + getSessionUser: sinon.stub().returns(@user) + isUserLoggedIn: sinon.stub().returns(true) @CompileController = SandboxedModule.require modulePath, requires: "settings-sharelatex": @settings "request": @request = sinon.stub() @@ -34,18 +46,13 @@ describe "CompileController", -> "./CompileManager":@CompileManager "../User/UserGetter":@UserGetter "./ClsiManager": @ClsiManager - "../Authentication/AuthenticationController": @AuthenticationController = {} + "../Authentication/AuthenticationController": @AuthenticationController "../../infrastructure/RateLimiter":@RateLimiter "./ClsiCookieManager":@ClsiCookieManager @project_id = "project-id" - @user = - features: - compileGroup: "premium" - compileTimeout: 100 @next = sinon.stub() @req = new MockRequest() @res = new MockResponse() - @AuthenticationController.getLoggedInUserId = sinon.stub().callsArgWith(1, null, @user_id = "mock-user-id") describe "compile", -> beforeEach -> @@ -90,7 +97,7 @@ describe "CompileController", -> @CompileManager.compile .calledWith(@project_id, @user_id, { isAutoCompile: true }) .should.equal true - + describe "with the draft attribute", -> beforeEach -> @req.body = @@ -108,7 +115,7 @@ describe "CompileController", -> Project_id: @project_id @project = getSafeProjectName: () => @safe_name = "safe-name" - + @req.query = {pdfng:true} @Project.findById = sinon.stub().callsArgWith(2, null, @project) @@ -340,9 +347,9 @@ describe "CompileController", -> project_id:@project_id @CompileManager.compile.callsArgWith(3) @CompileController.proxyToClsi = sinon.stub() - @res = + @res = send:=> - + it "should call compile in the compile manager", (done)-> @CompileController.compileAndDownloadPdf @req, @res @CompileManager.compile.calledWith(@project_id).should.equal true diff --git a/services/web/test/UnitTests/coffee/Contact/ContactControllerTests.coffee b/services/web/test/UnitTests/coffee/Contact/ContactControllerTests.coffee index aa01ff1a0f..0f6c6a0404 100644 --- a/services/web/test/UnitTests/coffee/Contact/ContactControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/Contact/ContactControllerTests.coffee @@ -8,12 +8,15 @@ SandboxedModule = require('sandboxed-module') describe "ContactController", -> beforeEach -> + @AuthenticationController = + getLoggedInUserId: sinon.stub() @ContactController = SandboxedModule.require modulePath, requires: "logger-sharelatex": @logger = { log: sinon.stub(), error: sinon.stub() } "../User/UserGetter": @UserGetter = {} "./ContactManager": @ContactManager = {} "../Authentication/AuthenticationController": @AuthenticationController = {} "../../infrastructure/Modules": @Modules = { hooks: {} } + '../Authentication/AuthenticationController': @AuthenticationController @next = sinon.stub() @req = {} @@ -30,33 +33,33 @@ describe "ContactController", -> { _id: "contact-2", email: "jane@example.com", first_name: "Jane", last_name: "Example", unsued: "foo", holdingAccount: true } { _id: "contact-3", email: "jim@example.com", first_name: "Jim", last_name: "Example", unsued: "foo" } ] - @AuthenticationController.getLoggedInUserId = sinon.stub().callsArgWith(1, null, @user_id) + @AuthenticationController.getLoggedInUserId = sinon.stub().returns(@user_id) @ContactManager.getContactIds = sinon.stub().callsArgWith(2, null, @contact_ids) @UserGetter.getUsers = sinon.stub().callsArgWith(2, null, @contacts) @Modules.hooks.fire = sinon.stub().callsArg(3) - + @ContactController.getContacts @req, @res, @next - + it "should look up the logged in user id", -> @AuthenticationController.getLoggedInUserId .calledWith(@req) .should.equal true - + it "should get the users contact ids", -> @ContactManager.getContactIds .calledWith(@user_id, { limit: 50 }) .should.equal true - + it "should populate the users contacts ids", -> @UserGetter.getUsers .calledWith(@contact_ids, { email: 1, first_name: 1, last_name: 1, holdingAccount: 1 }) .should.equal true - + it "should fire the getContact module hook", -> @Modules.hooks.fire .calledWith("getContacts", @user_id) .should.equal true - + it "should return a formatted list of contacts in contact list order, without holding accounts", -> @res.send.args[0][0].contacts.should.deep.equal [ { id: "contact-1", email: "joe@example.com", first_name: "Joe", last_name: "Example", type: "user" } diff --git a/services/web/test/UnitTests/coffee/Notifications/NotificationsControllerTests.coffee b/services/web/test/UnitTests/coffee/Notifications/NotificationsControllerTests.coffee index 083257e62c..126b223f04 100644 --- a/services/web/test/UnitTests/coffee/Notifications/NotificationsControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/Notifications/NotificationsControllerTests.coffee @@ -10,16 +10,9 @@ describe 'NotificationsController', -> notification_id = "123njdskj9jlk" beforeEach -> - @handler = + @handler = getUserNotifications: sinon.stub().callsArgWith(1) markAsRead: sinon.stub().callsArgWith(2) - @controller = SandboxedModule.require modulePath, requires: - "./NotificationsHandler":@handler - "underscore":@underscore = - map:(arr)-> return arr - 'logger-sharelatex': - log:-> - err:-> @req = params: notification_id:notification_id @@ -28,6 +21,16 @@ describe 'NotificationsController', -> _id:user_id i18n: translate:-> + @AuthenticationController = + getLoggedInUserId: sinon.stub().returns(@req.session.user._id) + @controller = SandboxedModule.require modulePath, requires: + "./NotificationsHandler":@handler + "underscore":@underscore = + map:(arr)-> return arr + 'logger-sharelatex': + log:-> + err:-> + '../Authentication/AuthenticationController': @AuthenticationController it 'should ask the handler for all unread notifications', (done)-> allNotifications = [{_id: notification_id, user_id: user_id}] diff --git a/services/web/test/UnitTests/coffee/Project/ProjectControllerTests.coffee b/services/web/test/UnitTests/coffee/Project/ProjectControllerTests.coffee index faa1456b51..bcb2354b55 100644 --- a/services/web/test/UnitTests/coffee/Project/ProjectControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/Project/ProjectControllerTests.coffee @@ -12,12 +12,15 @@ describe "ProjectController", -> @project_id = "123213jlkj9kdlsaj" - @settings = + @user = + _id:"!£123213kjljkl" + first_name: "bjkdsjfk" + @settings = apis: chat: url:"chat.com" siteUrl: "mysite.com" - @ProjectDeleter = + @ProjectDeleter = archiveProject: sinon.stub().callsArg(1) deleteProject: sinon.stub().callsArg(1) restoreProject: sinon.stub().callsArg(1) @@ -29,7 +32,7 @@ describe "ProjectController", -> createBasicProject: sinon.stub().callsArgWith(2, null, {_id:@project_id}) @SubscriptionLocator = getUsersSubscription: sinon.stub() - @LimitationsManager = + @LimitationsManager = userHasSubscriptionOrIsGroupMember: sinon.stub() @TagsHandler = getAllTags: sinon.stub() @@ -39,7 +42,7 @@ describe "ProjectController", -> findById: sinon.stub() @AuthorizationManager = getPrivilegeLevelForProject:sinon.stub() - @EditorController = + @EditorController = renameProject:sinon.stub() @InactiveProjectManager = reactivateProjectIfRequired:sinon.stub() @@ -50,12 +53,17 @@ describe "ProjectController", -> @ProjectGetter = findAllUsersProjects: sinon.stub() getProject: sinon.stub() + @AuthenticationController = + getLoggedInUser: sinon.stub().callsArgWith(1, null, @user) + getLoggedInUserId: sinon.stub().returns(@user._id) + getSessionUser: sinon.stub().returns(@user) + isUserLoggedIn: sinon.stub().returns(true) @ProjectController = SandboxedModule.require modulePath, requires: "settings-sharelatex":@settings - "logger-sharelatex": + "logger-sharelatex": log:-> err:-> - "../../infrastructure/Metrics": + "../../infrastructure/Metrics": Timer:-> done:-> inc:-> @@ -73,21 +81,19 @@ describe "ProjectController", -> "./ProjectUpdateHandler":@ProjectUpdateHandler "../ReferencesSearch/ReferencesSearchHandler": @ReferencesSearchHandler "./ProjectGetter": @ProjectGetter + '../Authentication/AuthenticationController': @AuthenticationController - @user = - _id:"!£123213kjljkl" - first_name: "bjkdsjfk" @projectName = "£12321jkj9ujkljds" - @req = - params: + @req = + params: Project_id: @project_id session: user: @user body: - projectName: @projectName + projectName: @projectName i18n: translate:-> - @res = + @res = locals: jsPath:"js path here" @@ -139,7 +145,7 @@ describe "ProjectController", -> code.should.equal 204 done() @ProjectController.updateProjectSettings @req, @res - + describe "updateProjectAdminSettings", -> it "should update the public access level", (done) -> @EditorController.setPublicAccessLevel = sinon.stub().callsArg(2) @@ -178,7 +184,7 @@ describe "ProjectController", -> @ProjectController.restoreProject @req, @res describe "cloneProject", -> - it "should call the project duplicator", (done)-> + it "should call the project duplicator", (done)-> @res.send = (json)=> @ProjectDuplicator.duplicate.calledWith(@user, @project_id, @projectName).should.equal true json.project_id.should.equal @project_id @@ -214,7 +220,7 @@ describe "ProjectController", -> @readOnly = [{lastUpdated:3, _id:3, owner_ref: "user-1"}] @users = - 'user-1': + 'user-1': first_name: 'James' 'user-2': first_name: 'Henry' @@ -289,10 +295,10 @@ describe "ProjectController", -> describe "loadEditor", -> beforeEach -> @settings.editorIsOpen = true - @project = + @project = name:"my proj" _id:"213123kjlkj" - @user = + @user = _id:"123kj21k3lj" ace: fontSize:"massive" @@ -351,4 +357,3 @@ describe "ProjectController", -> @ProjectUpdateHandler.markAsOpened.calledWith(@project_id).should.equal true done() @ProjectController.loadEditor @req, @res - diff --git a/services/web/test/UnitTests/coffee/Security/RateLimiterMiddlewearTests.coffee b/services/web/test/UnitTests/coffee/Security/RateLimiterMiddlewearTests.coffee index 05f40a2553..7066ed21ef 100644 --- a/services/web/test/UnitTests/coffee/Security/RateLimiterMiddlewearTests.coffee +++ b/services/web/test/UnitTests/coffee/Security/RateLimiterMiddlewearTests.coffee @@ -5,9 +5,13 @@ modulePath = require('path').join __dirname, '../../../../app/js/Features/Securi describe "RateLimiterMiddlewear", -> beforeEach -> + @AuthenticationController = + getLoggedInUserId: () => + @req?.session?.user?._id @RateLimiterMiddlewear = SandboxedModule.require modulePath, requires: '../../infrastructure/RateLimiter' : @RateLimiter = {} "logger-sharelatex": @logger = {warn: sinon.stub()} + '../Authentication/AuthenticationController': @AuthenticationController @req = params: {} @res = @@ -15,7 +19,7 @@ describe "RateLimiterMiddlewear", -> write: sinon.stub() end: sinon.stub() @next = sinon.stub() - + describe "rateLimit", -> beforeEach -> @rateLimiter = @RateLimiterMiddlewear.rateLimit({ @@ -28,7 +32,7 @@ describe "RateLimiterMiddlewear", -> project_id: @project_id = "project-id" doc_id: @doc_id = "doc-id" } - + describe "when there is no session", -> beforeEach -> @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @@ -44,18 +48,18 @@ describe "RateLimiterMiddlewear", -> subjectName: "#{@project_id}:#{@doc_id}:#{@ip}" }) .should.equal true - + it "should pass on to next()", -> describe "when under the rate limit with logged in user", -> beforeEach -> @req.session = - user : + user : _id: @user_id = "user-id" @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @rateLimiter(@req, @res, @next) - + it "should call the rate limiter backend with the user_id", -> @RateLimiter.addCount .calledWith({ @@ -65,16 +69,16 @@ describe "RateLimiterMiddlewear", -> subjectName: "#{@project_id}:#{@doc_id}:#{@user_id}" }) .should.equal true - + it "should pass on to next()", -> @next.called.should.equal true - + describe "when under the rate limit with anonymous user", -> beforeEach -> @req.ip = @ip = "1.2.3.4" @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, true) @rateLimiter(@req, @res, @next) - + it "should call the rate limiter backend with the ip address", -> @RateLimiter.addCount .calledWith({ @@ -84,25 +88,25 @@ describe "RateLimiterMiddlewear", -> subjectName: "#{@project_id}:#{@doc_id}:#{@ip}" }) .should.equal true - + it "should pass on to next()", -> @next.called.should.equal true - + describe "when over the rate limit", -> beforeEach -> - @req.session = - user : + @req.session = + user : _id: @user_id = "user-id" @RateLimiter.addCount = sinon.stub().callsArgWith(1, null, false) @rateLimiter(@req, @res, @next) - + it "should return a 429", -> @res.status.calledWith(429).should.equal true @res.end.called.should.equal true - + it "should not continue", -> @next.called.should.equal false - + it "should log a warning", -> @logger.warn .calledWith({ @@ -112,4 +116,3 @@ describe "RateLimiterMiddlewear", -> subjectName: "#{@project_id}:#{@doc_id}:#{@user_id}" }, "rate limit exceeded") .should.equal true - \ No newline at end of file diff --git a/services/web/test/UnitTests/coffee/Subscription/SubscriptionControllerTests.coffee b/services/web/test/UnitTests/coffee/Subscription/SubscriptionControllerTests.coffee index db5e4e8c1c..1f935e420f 100644 --- a/services/web/test/UnitTests/coffee/Subscription/SubscriptionControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/Subscription/SubscriptionControllerTests.coffee @@ -20,12 +20,15 @@ mockSubscriptions = describe "SubscriptionController sanboxed", -> beforeEach -> - @user = {email:"tom@yahoo.com"} + @user = {email:"tom@yahoo.com", _id: 'one'} @activeRecurlySubscription = mockSubscriptions["subscription-123-active"] @AuthenticationController = getLoggedInUser: sinon.stub().callsArgWith(1, null, @user) - @SubscriptionHandler = + getLoggedInUserId: sinon.stub().returns(@user._id) + getSessionUser: sinon.stub().returns(@user) + isUserLoggedIn: sinon.stub().returns(true) + @SubscriptionHandler = createSubscription: sinon.stub().callsArgWith(3) updateSubscription: sinon.stub().callsArgWith(3) reactivateSubscription: sinon.stub().callsArgWith(1) @@ -36,19 +39,19 @@ describe "SubscriptionController sanboxed", -> @PlansLocator = findLocalPlanInSettings: sinon.stub() - @LimitationsManager = + @LimitationsManager = userHasSubscriptionOrIsGroupMember: sinon.stub() userHasSubscription : sinon.stub() - @RecurlyWrapper = + @RecurlyWrapper = sign: sinon.stub().callsArgWith(1, null, "somthing") - @SubscriptionViewModelBuilder = + @SubscriptionViewModelBuilder = buildUsersSubscriptionViewModel:sinon.stub().callsArgWith(1, null, @activeRecurlySubscription) buildViewModel: sinon.stub() - @settings = + @settings = coupon_codes: - upgradeToAnnualPromo: + upgradeToAnnualPromo: student:"STUDENTCODEHERE" collaborator:"COLLABORATORCODEHERE" apis: @@ -58,8 +61,8 @@ describe "SubscriptionController sanboxed", -> gaExperiments:{} @GeoIpLookup = getCurrencyCode:sinon.stub() - @SubscriptionDomainHandler = - getDomainLicencePage:sinon.stub() + @SubscriptionDomainHandler = + getDomainLicencePage:sinon.stub() @SubscriptionController = SandboxedModule.require modulePath, requires: '../Authentication/AuthenticationController': @AuthenticationController './SubscriptionHandler': @SubscriptionHandler @@ -68,7 +71,7 @@ describe "SubscriptionController sanboxed", -> "./LimitationsManager": @LimitationsManager "../../infrastructure/GeoIpLookup":@GeoIpLookup './RecurlyWrapper': @RecurlyWrapper - "logger-sharelatex": + "logger-sharelatex": log:-> warn:-> "settings-sharelatex": @settings @@ -78,7 +81,7 @@ describe "SubscriptionController sanboxed", -> @res = new MockResponse() @req = new MockRequest() @req.body = {} - @req.query = + @req.query = planCode:"123123" @stubbedCurrencyCode = "GBP" @@ -175,7 +178,7 @@ describe "SubscriptionController sanboxed", -> @res.render = (page, opts)=> opts.currency.should.equal "EUR" done() - @SubscriptionController.paymentPage @req, @res + @SubscriptionController.paymentPage @req, @res it "should use the geo ip currency if non is provided", (done)-> @@ -183,8 +186,8 @@ describe "SubscriptionController sanboxed", -> @res.render = (page, opts)=> opts.currency.should.equal @stubbedCurrencyCode done() - @SubscriptionController.paymentPage @req, @res - + @SubscriptionController.paymentPage @req, @res + describe "successful_subscription", -> beforeEach (done) -> @SubscriptionViewModelBuilder.buildUsersSubscriptionViewModel.callsArgWith(1, null, {}) @@ -226,7 +229,7 @@ describe "SubscriptionController sanboxed", -> it "should render the dashboard", -> @res.renderedTemplate.should.equal "subscriptions/dashboard" - + describe "with a user with a paid subscription", -> beforeEach (done) -> @res.callback = done @@ -238,7 +241,7 @@ describe "SubscriptionController sanboxed", -> @res.rendered.should.equal true @res.renderedTemplate.should.equal "subscriptions/dashboard" done() - + it "should set the correct subscription details", -> @res.renderedVariables.subscription.should.deep.equal @activeRecurlySubscription @@ -251,7 +254,7 @@ describe "SubscriptionController sanboxed", -> it "should render the dashboard", -> @res.renderedTemplate.should.equal "subscriptions/dashboard" - + it "should set the correct subscription details", -> @res.renderedVariables.subscription.should.deep.equal @activeRecurlySubscription @@ -431,7 +434,7 @@ describe "SubscriptionController sanboxed", -> describe "processUpgradeToAnnualPlan", -> beforeEach -> - + it "should tell the subscription handler to update the subscription with the annual plan and apply a coupon code", (done)-> @req.body = planName:"student" @@ -452,6 +455,3 @@ describe "SubscriptionController sanboxed", -> done() @SubscriptionController.processUpgradeToAnnualPlan @req, @res - - - diff --git a/services/web/test/UnitTests/coffee/Subscription/SubscriptionGroupControllerTests.coffee b/services/web/test/UnitTests/coffee/Subscription/SubscriptionGroupControllerTests.coffee index 455c441239..5c835e5cc5 100644 --- a/services/web/test/UnitTests/coffee/Subscription/SubscriptionGroupControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/Subscription/SubscriptionGroupControllerTests.coffee @@ -9,8 +9,19 @@ describe "SubscriptionGroupController", -> beforeEach -> @user = {_id:"!@312431",email:"user@email.com"} + @adminUserId = "123jlkj" + @subscription_id = "123434325412" + @user_email = "bob@gmail.com" + @req = + session: + user: + _id: @adminUserId + email:@user_email + params: + subscription_id:@subscription_id + query:{} @subscription = {} - @GroupHandler = + @GroupHandler = addUserToGroup: sinon.stub().callsArgWith(2, null, @user) removeUserFromGroup: sinon.stub().callsArgWith(2) isUserPartOfGroup: sinon.stub() @@ -18,15 +29,18 @@ describe "SubscriptionGroupController", -> processGroupVerification:sinon.stub() getPopulatedListOfMembers: sinon.stub().callsArgWith(1, null, [@user]) @SubscriptionLocator = getUsersSubscription: sinon.stub().callsArgWith(1, null, @subscription) + @AuthenticationController = + getLoggedInUserId: (req) -> req.session.user._id + getSessionUser: (req) -> req.session.user - @SubscriptionDomainHandler = + @SubscriptionDomainHandler = findDomainLicenceBySubscriptionId:sinon.stub() @OneTimeTokenHandler = getValueFromTokenAndExpire:sinon.stub() - @ErrorsController = + @ErrorsController = notFound:sinon.stub() @Controller = SandboxedModule.require modulePath, requires: @@ -35,18 +49,8 @@ describe "SubscriptionGroupController", -> "./SubscriptionLocator": @SubscriptionLocator "./SubscriptionDomainHandler":@SubscriptionDomainHandler "../Errors/ErrorController":@ErrorsController + '../Authentication/AuthenticationController': @AuthenticationController - @adminUserId = "123jlkj" - @subscription_id = "123434325412" - @user_email = "bob@gmail.com" - @req = - session: - user: - _id: @adminUserId - email:@user_email - params: - subscription_id:@subscription_id - query:{} @token = "super-secret-token" @@ -76,7 +80,7 @@ describe "SubscriptionGroupController", -> @Controller.removeUserFromGroup @req, res - describe "renderSubscriptionGroupAdminPage", -> + describe "renderSubscriptionGroupAdminPage", -> it "should redirect you if you don't have a group account", (done)-> @subscription.groupPlan = false @@ -177,7 +181,7 @@ describe "SubscriptionGroupController", -> @Controller.completeJoin @req, res - describe "exportGroupCsv", -> + describe "exportGroupCsv", -> beforeEach -> @subscription.groupPlan = true diff --git a/services/web/test/UnitTests/coffee/Tags/TagsControllerTests.coffee b/services/web/test/UnitTests/coffee/Tags/TagsControllerTests.coffee index dbce6c094a..059460a4c4 100644 --- a/services/web/test/UnitTests/coffee/Tags/TagsControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/Tags/TagsControllerTests.coffee @@ -11,24 +11,28 @@ describe 'TagsController', -> tag = "some_class101" beforeEach -> - @handler = + @handler = addProjectToTag: sinon.stub().callsArgWith(3) removeProjectFromTag: sinon.stub().callsArgWith(3) deleteTag: sinon.stub().callsArg(2) renameTag: sinon.stub().callsArg(3) createTag: sinon.stub() + @AuthenticationController = + getLoggedInUserId: (req) => + req.session.user._id @controller = SandboxedModule.require modulePath, requires: "./TagsHandler":@handler 'logger-sharelatex': log:-> err:-> + '../Authentication/AuthenticationController': @AuthenticationController @req = params: project_id:project_id session: user: _id:user_id - + @res = {} @res.status = sinon.stub().returns @res @res.end = sinon.stub() @@ -49,26 +53,26 @@ describe 'TagsController', -> @req.session.user._id = @user_id = "user-id-123" @req.body = name: @name = "tag-name" @controller.createTag @req, @res - + it "should create the tag in the backend", -> @handler.createTag .calledWith(@user_id, @name) .should.equal true - + it "should return the tag", -> @res.json.calledWith(@tag).should.equal true - + describe "deleteTag", -> beforeEach -> @req.params.tag_id = @tag_id = "tag-id-123" @req.session.user._id = @user_id = "user-id-123" @controller.deleteTag @req, @res - + it "should delete the tag in the backend", -> @handler.deleteTag .calledWith(@user_id, @tag_id) .should.equal true - + it "should return 204 status code", -> @res.status.calledWith(204).should.equal true @res.end.called.should.equal true @@ -82,56 +86,55 @@ describe 'TagsController', -> beforeEach -> @req.body = name: @name = "new-name" @controller.renameTag @req, @res - + it "should delete the tag in the backend", -> @handler.renameTag .calledWith(@user_id, @tag_id, @name) .should.equal true - + it "should return 204 status code", -> @res.status.calledWith(204).should.equal true @res.end.called.should.equal true - + describe "without a name", -> beforeEach -> @controller.renameTag @req, @res - + it "should not call the backend", -> @handler.renameTag.called.should.equal false - + it "should return 400 (bad request) status code", -> @res.status.calledWith(400).should.equal true @res.end.called.should.equal true - + describe "addProjectToTag", -> beforeEach -> @req.params.tag_id = @tag_id = "tag-id-123" @req.params.project_id = @project_id = "project-id-123" @req.session.user._id = @user_id = "user-id-123" @controller.addProjectToTag @req, @res - + it "should add the tag to the project in the backend", -> @handler.addProjectToTag .calledWith(@user_id, @tag_id, @project_id) .should.equal true - + it "should return 204 status code", -> @res.status.calledWith(204).should.equal true @res.end.called.should.equal true - + describe "removeProjectFromTag", -> beforeEach -> @req.params.tag_id = @tag_id = "tag-id-123" @req.params.project_id = @project_id = "project-id-123" @req.session.user._id = @user_id = "user-id-123" @controller.removeProjectFromTag @req, @res - + it "should remove the tag from the project in the backend", -> @handler.removeProjectFromTag .calledWith(@user_id, @tag_id, @project_id) .should.equal true - + it "should return 204 status code", -> @res.status.calledWith(204).should.equal true @res.end.called.should.equal true - \ No newline at end of file diff --git a/services/web/test/UnitTests/coffee/TrackChanges/TrackChangesControllerTests.coffee b/services/web/test/UnitTests/coffee/TrackChanges/TrackChangesControllerTests.coffee index ad9f1ed04a..bcc57b58b8 100644 --- a/services/web/test/UnitTests/coffee/TrackChanges/TrackChangesControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/TrackChanges/TrackChangesControllerTests.coffee @@ -6,18 +6,20 @@ SandboxedModule = require('sandboxed-module') describe "TrackChangesController", -> beforeEach -> + @user_id = "user-id-123" + @AuthenticationController = + getLoggedInUserId: sinon.stub().returns(@user_id) @TrackChangesController = SandboxedModule.require modulePath, requires: "request" : @request = sinon.stub() "settings-sharelatex": @settings = {} "logger-sharelatex": @logger = {log: sinon.stub(), error: sinon.stub()} - "../Authentication/AuthenticationController": @AuthenticationController = {} + "../Authentication/AuthenticationController": @AuthenticationController describe "proxyToTrackChangesApi", -> beforeEach -> @req = { url: "/mock/url", method: "POST" } @res = "mock-res" @next = sinon.stub() - @user_id = "user-id-123" @settings.apis = trackchanges: url: "http://trackchanges.example.com" @@ -26,7 +28,6 @@ describe "TrackChangesController", -> pipe: sinon.stub() on: (event, handler) -> @events[event] = handler @request.returns @proxy - @AuthenticationController.getLoggedInUserId = sinon.stub().callsArgWith(1, null, @user_id) @TrackChangesController.proxyToTrackChangesApi @req, @res, @next describe "successfully", -> @@ -56,4 +57,3 @@ describe "TrackChangesController", -> it "should pass the error up the call chain", -> @next.calledWith(@error).should.equal true - diff --git a/services/web/test/UnitTests/coffee/Uploads/ProjectUploadControllerTests.coffee b/services/web/test/UnitTests/coffee/Uploads/ProjectUploadControllerTests.coffee index 176ae96d24..764265424c 100644 --- a/services/web/test/UnitTests/coffee/Uploads/ProjectUploadControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/Uploads/ProjectUploadControllerTests.coffee @@ -15,13 +15,16 @@ describe "ProjectUploadController", -> @metrics = Timer: class Timer done: sinon.stub() + @AuthenticationController = + getLoggedInUserId: sinon.stub().returns(@user_id) @ProjectUploadController = SandboxedModule.require modulePath, requires: "./ProjectUploadManager" : @ProjectUploadManager = {} "./FileSystemImportManager" : @FileSystemImportManager = {} "logger-sharelatex" : @logger = {log: sinon.stub(), error: sinon.stub(), err:->} "../../infrastructure/Metrics": @metrics + '../Authentication/AuthenticationController': @AuthenticationController "fs" : @fs = {} - + describe "uploadProject", -> beforeEach -> @path = "/path/to/file/on/disk.zip" @@ -55,13 +58,13 @@ describe "ProjectUploadController", -> .createProjectFromZipArchive .calledWith(sinon.match.any, "filename", sinon.match.any) .should.equal true - + it "should create a project from the zip archive", -> @ProjectUploadManager .createProjectFromZipArchive .calledWith(sinon.match.any, sinon.match.any, @path) .should.equal true - + it "should return a successful response to the FileUploader client", -> expect(@res.body).to.deep.equal success: true diff --git a/services/web/test/UnitTests/coffee/User/UserControllerTests.coffee b/services/web/test/UnitTests/coffee/User/UserControllerTests.coffee index 19d17e7ac3..63879e9c4c 100644 --- a/services/web/test/UnitTests/coffee/User/UserControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/User/UserControllerTests.coffee @@ -16,9 +16,18 @@ describe "UserController", -> @user = _id:@user_id - save:sinon.stub().callsArgWith(0) + save: sinon.stub().callsArgWith(0) ace:{} + @req = + user: {} + session: + destroy:-> + user : + _id : @user_id + email:"old@something.com" + body:{} + @UserDeleter = deleteUser: sinon.stub().callsArgWith(1) @UserLocator = @@ -31,6 +40,8 @@ describe "UserController", -> registerNewUser: sinon.stub() @AuthenticationController = establishUserSession: sinon.stub().callsArg(2) + getLoggedInUserId: sinon.stub().returns(@user._id) + getSessionUser: sinon.stub().returns(@req.session.user) @AuthenticationManager = authenticate: sinon.stub() setUserPassword: sinon.stub() @@ -67,13 +78,6 @@ describe "UserController", -> err:-> "../../infrastructure/Metrics": inc:-> - @req = - session: - destroy:-> - user : - _id : @user_id - email:"old@something.com" - body:{} @res = send: sinon.stub() json: sinon.stub() @@ -172,7 +176,7 @@ describe "UserController", -> cb(null, @user) @res.sendStatus = (code)=> code.should.equal 200 - @req.session.user.email.should.equal @newEmail + @req.user.email.should.equal @newEmail done() @UserController.updateUserSettings @req, @res diff --git a/services/web/test/UnitTests/coffee/User/UserPagesControllerTests.coffee b/services/web/test/UnitTests/coffee/User/UserPagesControllerTests.coffee index 4b36ace39c..0df1d65fe6 100644 --- a/services/web/test/UnitTests/coffee/User/UserPagesControllerTests.coffee +++ b/services/web/test/UnitTests/coffee/User/UserPagesControllerTests.coffee @@ -11,7 +11,7 @@ describe "UserPagesController", -> beforeEach -> @settings = {} - @user = + @user = _id: @user_id = "kwjewkl" features:{} email: "joe@example.com" @@ -25,6 +25,8 @@ describe "UserPagesController", -> getUserRegistrationStatus : sinon.stub().callsArgWith(1, null, @dropboxStatus) @ErrorController = notFound: sinon.stub() + @AuthenticationController = + getLoggedInUserId: sinon.stub().returns(@user._id) @UserPagesController = SandboxedModule.require modulePath, requires: "settings-sharelatex":@settings "logger-sharelatex": log:-> @@ -32,7 +34,8 @@ describe "UserPagesController", -> "./UserGetter": @UserGetter "../Errors/ErrorController": @ErrorController '../Dropbox/DropboxHandler': @DropboxHandler - @req = + '../Authentication/AuthenticationController': @AuthenticationController + @req = query:{} session: user:@user @@ -111,24 +114,24 @@ describe "UserPagesController", -> opts.user.should.equal @user done() @UserPagesController.settingsPage @req, @res - + describe "activateAccountPage", -> beforeEach -> @req.query.user_id = @user_id @req.query.token = @token = "mock-token-123" - + it "should 404 without a user_id", (done) -> delete @req.query.user_id @ErrorController.notFound = () -> done() @UserPagesController.activateAccountPage @req, @res - + it "should 404 without a token", (done) -> delete @req.query.token @ErrorController.notFound = () -> done() @UserPagesController.activateAccountPage @req, @res - + it "should 404 without a valid user_id", (done) -> @UserGetter.getUser = sinon.stub().callsArgWith(2, null, null) @ErrorController.notFound = () -> @@ -142,7 +145,7 @@ describe "UserPagesController", -> url.should.equal "/login?email=#{encodeURIComponent(@user.email)}" done() @UserPagesController.activateAccountPage @req, @res - + it "render the activation page if the user has not logged in before", (done) -> @user.loginCount = 0 @res.render = (page, opts) => @@ -150,4 +153,4 @@ describe "UserPagesController", -> opts.email.should.equal @user.email opts.token.should.equal @token done() - @UserPagesController.activateAccountPage @req, @res \ No newline at end of file + @UserPagesController.activateAccountPage @req, @res