From c451be20de4cb95bbd234dbdb1db3fef94c4aaca Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 3 May 2016 20:06:55 +0200 Subject: [PATCH 001/157] Add skeleton --- src/routes/databaseRouter.ts | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 src/routes/databaseRouter.ts diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts new file mode 100644 index 0000000..eac2efb --- /dev/null +++ b/src/routes/databaseRouter.ts @@ -0,0 +1,9 @@ +/** + * This class contains API definitions for companies database connections + * Created by Davide Polonio on 03/05/16. + */ + +class DatabaseRouter { + + +} \ No newline at end of file From 80786f8b96c6e02f77ec3831c6ab2c7b7cc9b178 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 3 May 2016 20:44:04 +0200 Subject: [PATCH 002/157] Add initial stuff --- src/routes/databaseRouter.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index eac2efb..c13143c 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -3,7 +3,15 @@ * Created by Davide Polonio on 03/05/16. */ +import * as express from "express"; + class DatabaseRouter { + public expressRef : express.Express; + + + constructor(expressRef : express.Express) { + this.expressRef = expressRef; + } } \ No newline at end of file From 5277b87b2f78d6fb3ae0734eaba890b5ab680d9e Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 3 May 2016 20:44:25 +0200 Subject: [PATCH 003/157] Add empty test --- test/routes/databaseRouterTest.ts | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 test/routes/databaseRouterTest.ts diff --git a/test/routes/databaseRouterTest.ts b/test/routes/databaseRouterTest.ts new file mode 100644 index 0000000..ab41dab --- /dev/null +++ b/test/routes/databaseRouterTest.ts @@ -0,0 +1,29 @@ +/** + * This is the test for DatabaseRouter class + * Created by Davide Polonio on 03/05/16. + */ + +import * as DatabaseRouter from "../../src/routes/databaseRouter"; +import * as express from "express"; +import * as Chai from "chai"; + +describe("DatabaseRouter", () => { + + /* nothing to test for now + let toTest : DatabaseRouter; + let dummyExpress : express.Express = express(); + + beforeEach(function () : void { + + toTest = new DatabaseRouter(dummyExpress); + }); + + describe("#nameOfWhatYouAreTesting", () => { + it ("should ", () => { + + // Your code here + }); + + }); + */ +}); \ No newline at end of file From fd9235e7c274c8ea18c22d911dbd1e1a7b4efdc9 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 3 May 2016 20:48:00 +0200 Subject: [PATCH 004/157] Add personal memo --- src/routes/databaseRouter.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index c13143c..5571434 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -14,4 +14,5 @@ class DatabaseRouter { this.expressRef = expressRef; } -} \ No newline at end of file +} +// I have to export something here? \ No newline at end of file From 3b27d66dc86376f5d2158776f6d27b2a83a14087 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 3 May 2016 20:53:36 +0200 Subject: [PATCH 005/157] Fix for lint rules --- src/routes/databaseRouter.ts | 6 +++--- test/routes/databaseRouterTest.ts | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 5571434..eb2d821 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -8,11 +8,11 @@ import * as express from "express"; class DatabaseRouter { public expressRef : express.Express; - - + + constructor(expressRef : express.Express) { this.expressRef = expressRef; } } -// I have to export something here? \ No newline at end of file +// I have to export something here? diff --git a/test/routes/databaseRouterTest.ts b/test/routes/databaseRouterTest.ts index ab41dab..16a15e3 100644 --- a/test/routes/databaseRouterTest.ts +++ b/test/routes/databaseRouterTest.ts @@ -26,4 +26,4 @@ describe("DatabaseRouter", () => { }); */ -}); \ No newline at end of file +}); From e5dbbcd1039b5fcda3821de473b45e9932170fb2 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 3 May 2016 20:56:58 +0200 Subject: [PATCH 006/157] Set expressRef to private --- src/routes/databaseRouter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index eb2d821..bc541e2 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -7,7 +7,7 @@ import * as express from "express"; class DatabaseRouter { - public expressRef : express.Express; + private expressRef : express.Express; constructor(expressRef : express.Express) { From 4d15d13ea5693f84e72f6b530604e866716214a7 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 09:47:33 +0200 Subject: [PATCH 007/157] Add a space in the comments --- src/routes/databaseRouter.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index bc541e2..021bd21 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -1,5 +1,6 @@ /** * This class contains API definitions for companies database connections + * * Created by Davide Polonio on 03/05/16. */ From 8a4cfe678973c0d126b0d63a9814863d64bf0002 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 10:59:20 +0200 Subject: [PATCH 008/157] Add empty line --- test/routes/databaseRouterTest.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/test/routes/databaseRouterTest.ts b/test/routes/databaseRouterTest.ts index 16a15e3..1feb7a1 100644 --- a/test/routes/databaseRouterTest.ts +++ b/test/routes/databaseRouterTest.ts @@ -1,5 +1,6 @@ /** * This is the test for DatabaseRouter class + * * Created by Davide Polonio on 03/05/16. */ From d28557df6a91de06ba9ee35b6735fbacfebf9997 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 11:02:53 +0200 Subject: [PATCH 009/157] Fix Jenkinsfile --- Jenkinsfile | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index a5d6b88..af8e09e 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,12 +1,4 @@ node { - // Mark the code checkout 'stage'.... - stage 'Checkout' - - sh '''#!/bin/bash -rm -rf * -''' - // Get some code from a GitHub repository - git url: 'https://github.com/BugBusterSWE/MaaS.git' stage 'Install' @@ -34,4 +26,4 @@ npm run build . /opt/nvm/.bashrc npm test ''' -} \ No newline at end of file +} From 5c65d7ef090dd650f79336b02fd9097820763fd5 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 11:06:18 +0200 Subject: [PATCH 010/157] Mini fix --- Jenkinsfile | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/Jenkinsfile b/Jenkinsfile index af8e09e..01e656f 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,5 +1,12 @@ node { + stage 'List' + + sh '''#!/bin/bash +. /opt/nvm/.bashrc +ls -laR +''' + stage 'Install' sh '''#!/bin/bash From c0b5ba3b9cad7166fb2af5b311b467648c235097 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 11:11:17 +0200 Subject: [PATCH 011/157] An example --- test/routes/something.example | 1 + 1 file changed, 1 insertion(+) create mode 100644 test/routes/something.example diff --git a/test/routes/something.example b/test/routes/something.example new file mode 100644 index 0000000..deba01f --- /dev/null +++ b/test/routes/something.example @@ -0,0 +1 @@ +something From a2dfd705debd059bcb22dc5f67b7880417d01555 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 11:18:57 +0200 Subject: [PATCH 012/157] Only list test/ --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index 01e656f..7ff0e19 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -4,7 +4,7 @@ node { sh '''#!/bin/bash . /opt/nvm/.bashrc -ls -laR +ls -laR test/ ''' stage 'Install' From e4fe126653ae1e3a17b8f62133419ef5bda69d07 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 11:41:03 +0200 Subject: [PATCH 013/157] Remove debug --- Jenkinsfile | 7 ------- 1 file changed, 7 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 7ff0e19..af8e09e 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -1,12 +1,5 @@ node { - stage 'List' - - sh '''#!/bin/bash -. /opt/nvm/.bashrc -ls -laR test/ -''' - stage 'Install' sh '''#!/bin/bash From 976e633fb3e6f98d6d5e8d91036958fb6c8d7435 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 12:27:04 +0200 Subject: [PATCH 014/157] Add promise --- package.json | 7 ++++--- typings.json | 1 + 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index c4ff215..64e3e82 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,8 @@ "author": "BugBusters bugbusterswe@gmail.com", "license": "MIT", "dependencies": { - "express": "^4.13.1" + "express": "^4.13.1", + "promise": "^7.1.1" }, "devDependencies": { "apidoc": "^0.15.1", @@ -50,8 +51,8 @@ "mocha": "^2.4.5", "rimraf": "^2.5.2", "tslint": "^3.5.0", - "typedoc": "^0.3.12", + "typedoc": "latest", "typescript": "^1.8.7", - "typings": "^0.7.9" + "typings": "latest" } } diff --git a/typings.json b/typings.json index 817e332..7946105 100644 --- a/typings.json +++ b/typings.json @@ -6,6 +6,7 @@ "mime": "registry:dt/mime#0.0.0+20160316155526", "mocha": "registry:dt/mocha#2.2.5+20160317120654", "node": "registry:dt/node#4.0.0+20160330064709", + "promise": "registry:dt/promise#7.1.1+20160316171810", "serve-static": "registry:dt/serve-static#0.0.0+20160317120654" } } From c4d6f74a556786e0686760dc0d60e1e245b2e755 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 13:35:37 +0200 Subject: [PATCH 015/157] Add es6 typings --- typings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/typings.json b/typings.json index 7946105..ff5a6a6 100644 --- a/typings.json +++ b/typings.json @@ -1,12 +1,12 @@ { "ambientDependencies": { "chai": "registry:dt/chai#3.4.0+20160317120654", + "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", "express": "registry:dt/express#4.0.0+20160317120654", "express-serve-static-core": "registry:dt/express-serve-static-core#0.0.0+20160322035842", "mime": "registry:dt/mime#0.0.0+20160316155526", "mocha": "registry:dt/mocha#2.2.5+20160317120654", "node": "registry:dt/node#4.0.0+20160330064709", - "promise": "registry:dt/promise#7.1.1+20160316171810", "serve-static": "registry:dt/serve-static#0.0.0+20160317120654" } } From 59c0243b35f6dbe433a5ab46a265f5cab08cd9b7 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 13:35:51 +0200 Subject: [PATCH 016/157] Write documentation --- src/routes/databaseRouter.ts | 36 +++++++++++++++++++++++++++++------- 1 file changed, 29 insertions(+), 7 deletions(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 021bd21..a9ae48d 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -1,19 +1,41 @@ +import * as express from "express"; +import * as promise from "promise"; + /** - * This class contains API definitions for companies database connections + * This class contains API definitions for companies database connections. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Polonio | Create class | 03/05/2016 | * - * Created by Davide Polonio on 03/05/16. + * @author Davide Polonio + * @license MIT + * */ - -import * as express from "express"; - class DatabaseRouter { + /** + * @description Ref for express. + */ private expressRef : express.Express; - + /** + * @description Public constructor. It need a express ref. + * + * @param expressRef {express.Express} + * Reference to the express application + * + * @return {DatabaseRouter} + */ constructor(expressRef : express.Express) { this.expressRef = expressRef; } + + + public request( req : express.Request, res : express.Response, next : express.NextFunction ) : Promise { + + return req.params; + } } -// I have to export something here? From 4ebc826b4d9eb0d2b21feae92e99f8bbf5acb334 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Wed, 4 May 2016 13:38:36 +0200 Subject: [PATCH 017/157] Write documentation --- src/routes/databaseRouter.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index a9ae48d..66abd70 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -33,9 +33,11 @@ class DatabaseRouter { this.expressRef = expressRef; } - + /** + * @todo implement function + */ public request( req : express.Request, res : express.Response, next : express.NextFunction ) : Promise { - return req.params; + // Work in progress } } From 38711fa4ef438461e1747acb306deebdb099c917 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Wed, 4 May 2016 16:06:06 +0200 Subject: [PATCH 018/157] Add MaaS init file --- src/maas.ts | 56 ++++++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 49 insertions(+), 7 deletions(-) diff --git a/src/maas.ts b/src/maas.ts index bb54bce..234b598 100644 --- a/src/maas.ts +++ b/src/maas.ts @@ -1,13 +1,55 @@ -/** - * Created by davide on 26/03/16. - */ - -import * as test from "./main"; import * as express from "express"; -/*import {Express} from "express";*/ +import * as bodyParser from "body-parser"; +import * as http from "http"; +import {ConfigurationChooser} from "./config/configurationChooser"; +import {Configuration} from "./config/configuration"; +import {UserModel} from "./models/userModel"; +import {DSLModel} from "./models/dslModel"; +import {DatabaseModel} from "./models/databaseModel"; +import {CompanyModel} from "./models/companyModel"; +import {LevelChecker} from "./lib/levelChecker"; +import {AuthenticationChecker} from "./lib/authenticationChecker"; +import * as routes from "./routes"; +// Get the current configuration +let configuration : Configuration = ConfigurationChooser.getConfig(); +let user : UserModel = new UserModel(); // Get the user's model +let dsl : DSLModel = new DSLModel(); // Get the dsl's model +let database : DatabaseModel = new DatabaseModel(); // Get the database's model +let company : CompanyModel = new CompanyModel(); // Get the company's model +// Get the instance of the level checker +let lvlChecker : LevelChecker = LevelChecker.getInstance(); +// Get the instance of the authentication checker +let authChecker : AuthenticationChecker = AuthenticationChecker.getInstance(); +// Initializing app let app : express.Express = express(); +// Allow to get data from body in JSON format +app.use(bodyParser.urlencoded({extended: true})); +app.use(bodyParser.json()); + +// Middlewares' configuration +// Authenticator configuration +authChecker.initialize({ + secret: configuration.getServerSecret(), + getUserFunction: user.login +}); + +// Level Authenticator configuration +lvlChecker.initialize({ + pathToLevel: ["body"] +}); + +// DSL Checker?? todo + +// Routes' require +app.use("/api", routes); +app.post("/api/login", authChecker.login); -test.HelloWorld("test"); +// Starting the server +app.set("port", process.env.PORT || 3000); +let server : http.Server = app.listen(app.get("port"), function () : void { + console.log("Express server is listening on port " + server.address().port + + " in " + configuration.getEnvName() + " environment."); +}); From 656fbbd6ae40f6e290b6c0ecb7c2a26ecec8d473 Mon Sep 17 00:00:00 2001 From: drigoni Date: Thu, 5 May 2016 15:00:33 +0200 Subject: [PATCH 019/157] Make class template See issue #11 --- src/routes/companyRouter.ts | 43 +++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 src/routes/companyRouter.ts diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts new file mode 100644 index 0000000..a5f36b0 --- /dev/null +++ b/src/routes/companyRouter.ts @@ -0,0 +1,43 @@ +import * as express from "express"; +import * as promise from "es6-promise"; + +/** + * This class contains endpoint definition about companies. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Rigoni | Create class | 03/05/2016 | + * + * @author Davide Rigoni + * @license MIT + * + */ +class CompanyRouter { + + /** + * @description Ref for express. + */ + private expressRef : express.Express; + + /** + * @description Public constructor. It need a express ref. + * + * @param expressRef {express.Express} + * Reference to the express application + * + * @return {CompanyRouter} + */ + constructor(expressRef : express.Express) { + + this.expressRef = expressRef; + } + + /** + * @todo implement function + */ + public request( req : express.Request, res : express.Response, next : express.NextFunction ) : Promise { + + // Work in progress + } +} From 372f11809957c8edd749678a2d2ba070038d6372 Mon Sep 17 00:00:00 2001 From: drigoni Date: Thu, 5 May 2016 16:37:02 +0200 Subject: [PATCH 020/157] Make template of class --- package.json | 3 ++- src/models/company.ts | 23 +++++++++++++++++++++++ typings.json | 1 + 3 files changed, 26 insertions(+), 1 deletion(-) create mode 100644 src/models/company.ts diff --git a/package.json b/package.json index c4ff215..a2cae16 100644 --- a/package.json +++ b/package.json @@ -40,7 +40,8 @@ "author": "BugBusters bugbusterswe@gmail.com", "license": "MIT", "dependencies": { - "express": "^4.13.1" + "express": "^4.13.1", + "promise": "^7.1.1" }, "devDependencies": { "apidoc": "^0.15.1", diff --git a/src/models/company.ts b/src/models/company.ts new file mode 100644 index 0000000..409740a --- /dev/null +++ b/src/models/company.ts @@ -0,0 +1,23 @@ +import * as express from "express"; +import * as promise from "es6-promise"; + +/** + * This class define the company business logic. It contains model and scheme defined by MongooseJS. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Rigoni | Create class | 03/05/2016 | + * + * @author Davide Rigoni + * @license MIT + * + */ +class Company { + /** + * @todo implement function + */ + public getCompany(){ + + } +} diff --git a/typings.json b/typings.json index 817e332..ff5a6a6 100644 --- a/typings.json +++ b/typings.json @@ -1,6 +1,7 @@ { "ambientDependencies": { "chai": "registry:dt/chai#3.4.0+20160317120654", + "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", "express": "registry:dt/express#4.0.0+20160317120654", "express-serve-static-core": "registry:dt/express-serve-static-core#0.0.0+20160322035842", "mime": "registry:dt/mime#0.0.0+20160316155526", From c684702403284f3ecd23cceb4b1ffc72d1174d6c Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Thu, 5 May 2016 23:16:48 +0200 Subject: [PATCH 021/157] Add some middlewares --- src/maas.ts | 113 +++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 108 insertions(+), 5 deletions(-) diff --git a/src/maas.ts b/src/maas.ts index 234b598..0136105 100644 --- a/src/maas.ts +++ b/src/maas.ts @@ -31,21 +31,124 @@ app.use(bodyParser.json()); // Middlewares' configuration // Authenticator configuration -authChecker.initialize({ +/*authChecker.initialize({ secret: configuration.getServerSecret(), getUserFunction: user.login }); -// Level Authenticator configuration +// Level configuration lvlChecker.initialize({ pathToLevel: ["body"] -}); +});*/ // DSL Checker?? todo // Routes' require -app.use("/api", routes); -app.post("/api/login", authChecker.login); +/*app.use("/api", routes); +app.post("/api/login", authChecker.login);*/ +app.post("/api/companies/:company_id/users", + function(req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + authChecker.authenticate(req.body.user_id); + next(); +}, function(err : Error, + req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + if (err) { + res.status(500).send("Authenticate yourself firstly!") + } + lvlChecker.requireOwner(req.body.user_id); + next(); +}, function(err : Error, + req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + if (err) { + res.status(500).send("You aren't an owner!") + } +}); + +app.put("/api/companies/:company_id/users/:user_id/credentials", + function(req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + authChecker.authenticate(req.body.user_id); + next(); + }, function(err : Error, + req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + if (err) { + res.status(500).send("Authenticate yourself firstly!") + } + } +); + +app.delete("api/companies/:company_id/users/:user_id", + function(req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + authChecker.authenticate(req.body.user_id); + next(); + }, function(err : Error, + req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + if (err) { + res.status(500).send("Authenticate yourself firstly!") + } + lvlChecker.requireOwner(req.body.user_id); + next(); + }, function(err : Error, + req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + if (err) { + res.status(500).send("You aren't an owner!"); + } + } +); + +app.get("/api/companies/:company_id/", + function(req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + authChecker.authenticate(req.body.user_id); + next(); + }, function(err : Error, + req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + if (err) { + res.status(500).send("Authenticate yourself firstly!") + } + } +); + +app.put("/api/companies/:company_id/", + function(req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + authChecker.authenticate(req.body.user_id); + next(); + }, function(err : Error, + req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + if (err) { + res.status(500).send("Authenticate yourself firstly!") + } + lvlChecker.requireAdmin(req.body.user_id); + next(); + }, function(err : Error, + req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + res.status(500).send("You aren't an owner!"); + } +); // Starting the server app.set("port", process.env.PORT || 3000); From 77d9beadf0c29a66a3811cca05c810c90709463b Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 09:56:46 +0200 Subject: [PATCH 022/157] Create a first draft for databaseRouter After a discussion with @WeissL I understand what I have to do. Missing tests See issue #10 --- src/routes/databaseRouter.ts | 50 ++++++++++++++++++++++++------------ 1 file changed, 33 insertions(+), 17 deletions(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 66abd70..389e640 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -1,5 +1,4 @@ import * as express from "express"; -import * as promise from "promise"; /** * This class contains API definitions for companies database connections. @@ -10,34 +9,51 @@ import * as promise from "promise"; * | Davide Polonio | Create class | 03/05/2016 | * * @author Davide Polonio - * @license MIT + * @copyright MIT + * + * + * @todo Missing reference to the DatabaseModel object * */ class DatabaseRouter { /** - * @description Ref for express. + * @description Personal router for the class. The class load request here. */ - private expressRef : express.Express; + private routerRef : express.Router; /** - * @description Public constructor. It need a express ref. - * - * @param expressRef {express.Express} - * Reference to the express application + * @description Public constructor. * * @return {DatabaseRouter} */ - constructor(expressRef : express.Express) { + constructor() { + + this.routerRef = new express.Router(); - this.expressRef = expressRef; + this.createGetRouter(); } - - /** - * @todo implement function - */ - public request( req : express.Request, res : express.Response, next : express.NextFunction ) : Promise { - - // Work in progress + + private createGetRouter () : void { + + this.routerRef.get("/api/companies/:company_id/databases", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + + // Get the id of the database to query + let companyId = req.param[0]; + + //Query the database + + //If something goes wrong, call next() + next(); + }); } + + public getRouter () : express.Router { + + return this.routerRef; + } + } From 27dfaceb18495a0068bd530fed7af82f94c3dac7 Mon Sep 17 00:00:00 2001 From: drigoni Date: Fri, 6 May 2016 10:14:18 +0200 Subject: [PATCH 023/157] Create the createGetRouter method See issue #11 --- src/routes/companyRouter.ts | 38 +++++++++++++++++++++++++++---------- 1 file changed, 28 insertions(+), 10 deletions(-) diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index a5f36b0..50111d8 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -16,28 +16,46 @@ import * as promise from "es6-promise"; class CompanyRouter { /** - * @description Ref for express. + * @description Ref for express router. */ - private expressRef : express.Express; + private routerRef : express.Router; /** - * @description Public constructor. It need a express ref. + * @description Public constructor. It need a express router ref. * - * @param expressRef {express.Express} + * @param expressRef {express.Router} * Reference to the express application * * @return {CompanyRouter} */ - constructor(expressRef : express.Express) { - - this.expressRef = expressRef; + constructor() { + this.routerRef = express.Router(); + this.createGetRouter(); } /** - * @todo implement function + * @description Create company router */ - public request( req : express.Request, res : express.Response, next : express.NextFunction ) : Promise { + private createGetRouter () : void { + this.routerRef.get("/api/companies/:company_id", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + // Get the id of the database to query + let companyId = req.param[0]; + //Query the database + //If something goes wrong, call next() + next(); + }); + } + - // Work in progress + /** + * @description Return the express.Router param + * + * @returns {express.Router} + */ + public getRouter(): express.Router{ + return this.routerRef; } } From 0e7b4705d80316e55660b0cd11483cc55df517c9 Mon Sep 17 00:00:00 2001 From: drigoni Date: Fri, 6 May 2016 10:15:32 +0200 Subject: [PATCH 024/157] Change "noImplicitAny" to false See issue #11 --- burstmake.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/burstmake.json b/burstmake.json index 8e097ef..70c2757 100644 --- a/burstmake.json +++ b/burstmake.json @@ -5,7 +5,7 @@ "moduleResolution" : "node", "target": "es5", "declaration": false, - "noImplicitAny": true, + "noImplicitAny": false, "noEmitOnError": true, "sourceMap": true }, From 67b401593f294846453b2e271e7ca02549fdc9f4 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 10:16:54 +0200 Subject: [PATCH 025/157] Fix compilation errors on databaseRouters --- src/routes/databaseRouter.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 389e640..be0af1f 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -29,7 +29,7 @@ class DatabaseRouter { */ constructor() { - this.routerRef = new express.Router(); + this.routerRef = express.Router(); this.createGetRouter(); } @@ -41,8 +41,10 @@ class DatabaseRouter { res : express.Response, next : express.NextFunction) => { - // Get the id of the database to query - let companyId = req.param[0]; + /* Get the id of the database to query + * This need noImplicitAny: false + */ + let companyId : number = req.param[0]; //Query the database From 4894fa71c8905efb0bd0c7ecae1cf18cb46c2c82 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 10:17:09 +0200 Subject: [PATCH 026/157] Set noImplicitAny to false --- burstmake.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/burstmake.json b/burstmake.json index 8e097ef..70c2757 100644 --- a/burstmake.json +++ b/burstmake.json @@ -5,7 +5,7 @@ "moduleResolution" : "node", "target": "es5", "declaration": false, - "noImplicitAny": true, + "noImplicitAny": false, "noEmitOnError": true, "sourceMap": true }, From 08e3a265cd1e707b5b1fed28fcb449ef7a176c8f Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 10:39:54 +0200 Subject: [PATCH 027/157] Add mongoose dep --- typings.json | 1 + 1 file changed, 1 insertion(+) diff --git a/typings.json b/typings.json index 817e332..e02719f 100644 --- a/typings.json +++ b/typings.json @@ -5,6 +5,7 @@ "express-serve-static-core": "registry:dt/express-serve-static-core#0.0.0+20160322035842", "mime": "registry:dt/mime#0.0.0+20160316155526", "mocha": "registry:dt/mocha#2.2.5+20160317120654", + "mongoose": "registry:dt/mongoose#3.8.5+20160505185535", "node": "registry:dt/node#4.0.0+20160330064709", "serve-static": "registry:dt/serve-static#0.0.0+20160317120654" } From 9a013e1b1ef8fccf24a84ef8f46b3b117a87b58d Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 11:00:16 +0200 Subject: [PATCH 028/157] Add skeleton for databaseModel --- src/models/databaseModel.ts | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 src/models/databaseModel.ts diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts new file mode 100644 index 0000000..7fab773 --- /dev/null +++ b/src/models/databaseModel.ts @@ -0,0 +1,21 @@ +/** + * DatabaseModel manage all connections to MongoDB companies databases. + * Implements model and schema of MongooseJS. + * + * This model represent a connection to a company. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Polonio | Create class | 06/05/2016 | + * + * @author Davide Polonio + * @copyright MIT + * + * + */ + +class DatabaseModel { + + +} \ No newline at end of file From 606da71e626c1d305fff3f11512b06eec9295913 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Fri, 6 May 2016 11:08:12 +0200 Subject: [PATCH 029/157] Add router facade --- src/routes/routerFacade.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/routes/routerFacade.ts diff --git a/src/routes/routerFacade.ts b/src/routes/routerFacade.ts new file mode 100644 index 0000000..3c274ec --- /dev/null +++ b/src/routes/routerFacade.ts @@ -0,0 +1,15 @@ +/** + * Here we export all route files. You need only to import this file. + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Matteo Di Pirro | Create module | 06/05/2016 | + * + * @author Matteo Di Pirro + * @license MIT + */ + +export {DatabaseRouter} from "./databaseRouter"; +export {DSLRouter} from "./dslRouter"; +export {UserRouter} from "./userRouter"; +export {CompanyRouter} from "./companyRouter"; From d90f1568c8714e3ce612783c1b2bb8b7d2b0cdc0 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 11:12:55 +0200 Subject: [PATCH 030/157] Add personal notes --- src/routes/databaseRouter.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index be0af1f..16b808f 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -1,4 +1,5 @@ import * as express from "express"; +//import autentication checker /** * This class contains API definitions for companies database connections. @@ -41,6 +42,23 @@ class DatabaseRouter { res : express.Response, next : express.NextFunction) => { + let idUser : number = req.body[0]; + + /* + * Here I use authentication checker and I need to check + * the user level. + * 1 - Call authentication checker as class .authenticate + * authenticationChecker.authenticate() -> returns a boolean + * + * If the boolean returned is `false` the user + * hasn't right permission and so I raise a error and + * I have to call next with the error. + * + * 2 - See 1 but with level checker. The minimum is MEMBER. + * If > MEMBER I query the database. + */ + + /* Get the id of the database to query * This need noImplicitAny: false */ @@ -49,7 +67,7 @@ class DatabaseRouter { //Query the database //If something goes wrong, call next() - next(); + next(/*new Error("description")*/); }); } From 17e39257c8be961cbee1393fae2ffba920e74731 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 11:15:50 +0200 Subject: [PATCH 031/157] Fix typo --- src/routes/databaseRouter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 16b808f..1f22cfc 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -1,5 +1,5 @@ import * as express from "express"; -//import autentication checker +/* import authentication checker */ /** * This class contains API definitions for companies database connections. From 8047e40ecfdae70fc2634d81245e80fe269bc008 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 11:16:55 +0200 Subject: [PATCH 032/157] TSLint compliant --- src/routes/databaseRouter.ts | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 1f22cfc..b9e4c94 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -35,6 +35,11 @@ class DatabaseRouter { this.createGetRouter(); } + public getRouter () : express.Router { + + return this.routerRef; + } + private createGetRouter () : void { this.routerRef.get("/api/companies/:company_id/databases", @@ -64,16 +69,11 @@ class DatabaseRouter { */ let companyId : number = req.param[0]; - //Query the database + // Query the database - //If something goes wrong, call next() + // If something goes wrong, call next() next(/*new Error("description")*/); }); } - public getRouter () : express.Router { - - return this.routerRef; - } - } From a5db80344816a9558a128e1ccab408579532b617 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Fri, 6 May 2016 11:24:10 +0200 Subject: [PATCH 033/157] Add scratch checker see issue #19 --- src/lib/dslChecker.ts | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 src/lib/dslChecker.ts diff --git a/src/lib/dslChecker.ts b/src/lib/dslChecker.ts new file mode 100644 index 0000000..514783b --- /dev/null +++ b/src/lib/dslChecker.ts @@ -0,0 +1,34 @@ +/** + * Class to check if a json data is structured as a DSLStructure. + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Andrea Mantovani | Create class | 06/05/2016 | + * + * @author Andrea Mantovani + * @license MIT + */ +class DSLChecker { + /** + * Public construtorn, it do anything. + * @return {DSLChecker} This + */ + public constructor() {} + + /** + * Check if data rappresent a DSLStructure. If true, it returns a + * DSLCecker setted with the values inside data, else, it throw a + * exception. + * + * @param data {Object} JSON valid data + * @return {DSLStructure} Savable structure into DB + * @throws {DSLParseException} + */ + public check( data : Object ) : DSLStructure { + let structure : DSLStructure = new DSLStructure(); + + + + + } +} \ No newline at end of file From 80d044aea5c925b93c598208bd70073076ba7096 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 11:45:20 +0200 Subject: [PATCH 034/157] Add documentation on test --- test/routes/databaseRouterTest.ts | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/test/routes/databaseRouterTest.ts b/test/routes/databaseRouterTest.ts index 1feb7a1..38f1e95 100644 --- a/test/routes/databaseRouterTest.ts +++ b/test/routes/databaseRouterTest.ts @@ -1,13 +1,20 @@ -/** - * This is the test for DatabaseRouter class - * - * Created by Davide Polonio on 03/05/16. - */ - import * as DatabaseRouter from "../../src/routes/databaseRouter"; import * as express from "express"; import * as Chai from "chai"; +/** + * This is the test for DatabaseRouter class + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Polonio | Create class | 03/05/2016 | + * + * @author Davide Polonio + * @copyright MIT + * + * Created by Davide Polonio on 03/05/16. + */ describe("DatabaseRouter", () => { /* nothing to test for now From e1064b4bdd40635462ca6f7518feca019468ac71 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 11:56:37 +0200 Subject: [PATCH 035/157] Remove example --- test/routes/something.example | 1 - 1 file changed, 1 deletion(-) delete mode 100644 test/routes/something.example diff --git a/test/routes/something.example b/test/routes/something.example deleted file mode 100644 index deba01f..0000000 --- a/test/routes/something.example +++ /dev/null @@ -1 +0,0 @@ -something From fb3802ccc77ed5da9ff65251b5f69c17057c20d1 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Fri, 6 May 2016 12:04:29 +0200 Subject: [PATCH 036/157] Push stuff --- src/models/databaseModel.ts | 21 ++++++++++++++-- test/models/databaseModelTest.ts | 42 ++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) create mode 100644 test/models/databaseModelTest.ts diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 7fab773..9de0e7b 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -17,5 +17,22 @@ class DatabaseModel { - -} \ No newline at end of file + constructor () { + + // For now nothing to do here + } + + /** + * @description Return a database from the identifier + * + * @param identifier + * + * @return // To choose + */ + public getDatabase ( identifier : number ) : void { + + // TODO to implement + } +} + +export default DatabaseModel; \ No newline at end of file diff --git a/test/models/databaseModelTest.ts b/test/models/databaseModelTest.ts new file mode 100644 index 0000000..195d2f8 --- /dev/null +++ b/test/models/databaseModelTest.ts @@ -0,0 +1,42 @@ +import * as DatabaseModel from "../../src/models/databaseModel"; +import * as Chai from "chai"; + +/** + * DatabaseModel manage all connections to MongoDB companies databases. + * Implements model and schema of MongooseJS. + * + * This model represent a connection to a company. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Polonio | Create class | 06/05/2016 | + * + * @author Davide Polonio + * @copyright MIT + * + * + */ + +describe("DatabaseModel", () => { + + /* + let toTest:someThing; // Name of the object to test + + // Call one of the many function that are in the Mocha framework + beforeEach(function ():void { + + toTest = new someThing(); // You can do something before every test + }); + + // This function starts a single test + describe("#nameOfWhatYouAreTesting", () => { + it("should ", () => { + + // Your code here + + Chai.expect(toTest.sayHello(name)).to.equal("Hello Derp"); + }); + + */ + }); From d81174bb2181b524d1ad8c12eae264a83e0a4a73 Mon Sep 17 00:00:00 2001 From: drigoni Date: Fri, 6 May 2016 15:02:39 +0200 Subject: [PATCH 037/157] Change class name and add class method See issue #6 --- package.json | 1 + src/models/company.ts | 23 --------------- src/models/companyModel.ts | 60 ++++++++++++++++++++++++++++++++++++++ typings.json | 1 + 4 files changed, 62 insertions(+), 23 deletions(-) delete mode 100644 src/models/company.ts create mode 100644 src/models/companyModel.ts diff --git a/package.json b/package.json index a2cae16..b1f96dc 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,7 @@ "license": "MIT", "dependencies": { "express": "^4.13.1", + "mongoose": "^4.4.14", "promise": "^7.1.1" }, "devDependencies": { diff --git a/src/models/company.ts b/src/models/company.ts deleted file mode 100644 index 409740a..0000000 --- a/src/models/company.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as express from "express"; -import * as promise from "es6-promise"; - -/** - * This class define the company business logic. It contains model and scheme defined by MongooseJS. - * - * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Davide Rigoni | Create class | 03/05/2016 | - * - * @author Davide Rigoni - * @license MIT - * - */ -class Company { - /** - * @todo implement function - */ - public getCompany(){ - - } -} diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts new file mode 100644 index 0000000..dc4c728 --- /dev/null +++ b/src/models/companyModel.ts @@ -0,0 +1,60 @@ +import * as promise from "es6-promise"; +import * as mongoose from "mongoose"; +import {Model} from "mongoose"; + +/** + * This class define the company business logic. It contains model and scheme + * defined by MongooseJS. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Rigoni | Create class | 03/05/2016 | + * + * @author Davide Rigoni + * @license MIT + * + */ +class CompanyModel extends Model{ + name : string; + idOwner : string; + + /** + * @description constructor + * @param name + * @param idOwner + * @return {CompanyModel} + */ + constructor (name : string, idOwner : string) { + this.name = name; + this.idOwner = idOwner; + + //verifico se esiste la company + } + + public getCompany(name : string) : CompanyModel{ + //return json + } + + public update(c : CompanyModel) : void { + //return json + } + + public delete() : void { + //return json + } + + + + static private findCompany(name : string) : CompanyModel{ + //return json + } + + static public createCompany(c : CompanyModel, e : string, + p : string) : CompanyModel { + //create user + //return json + } + + +} diff --git a/typings.json b/typings.json index ff5a6a6..cc03637 100644 --- a/typings.json +++ b/typings.json @@ -6,6 +6,7 @@ "express-serve-static-core": "registry:dt/express-serve-static-core#0.0.0+20160322035842", "mime": "registry:dt/mime#0.0.0+20160316155526", "mocha": "registry:dt/mocha#2.2.5+20160317120654", + "mongoose": "registry:dt/mongoose#3.8.5+20160505185535", "node": "registry:dt/node#4.0.0+20160330064709", "serve-static": "registry:dt/serve-static#0.0.0+20160317120654" } From d2e9ac3dff135915c0978aaaed55b3e434d7f4d3 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Fri, 6 May 2016 18:00:50 +0200 Subject: [PATCH 038/157] False rule no-string-literal The access with string is necessary to implemet map. See issue#19 --- tslint.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tslint.json b/tslint.json index 06aca6e..c1baeba 100644 --- a/tslint.json +++ b/tslint.json @@ -44,7 +44,7 @@ "no-eval": true, "no-null-keyword": true, "no-shadowed-variable": false, - "no-string-literal": true, + "no-string-literal": false, "no-switch-case-fall-through": true, "no-unreachable": true, "no-unused-expression": true, From f42016a6275f802dddfe3d324a1044ed13cf9a28 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Fri, 6 May 2016 18:01:19 +0200 Subject: [PATCH 039/157] Create interface for the Map See issue#19 --- src/lib/map.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/lib/map.ts diff --git a/src/lib/map.ts b/src/lib/map.ts new file mode 100644 index 0000000..267d379 --- /dev/null +++ b/src/lib/map.ts @@ -0,0 +1,15 @@ +/** + * Interface to expose the utility of map, it associates the key with the value. + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Andrea Mantovani | Create interface | 06/05/2016 | + * + * @author Andrea Mantovani + * @license MIT + */ +interface Map { + [k : string] : value; +} + +export default Map; From 5de50559176ca03d0893b641c47b7c7be8780f68 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Fri, 6 May 2016 18:03:07 +0200 Subject: [PATCH 040/157] Implement method check For the moment, it checks only required params. See issue#19 --- src/lib/dslChecker.ts | 191 ++++++++++++++++++++++++++++++++++++------ 1 file changed, 167 insertions(+), 24 deletions(-) diff --git a/src/lib/dslChecker.ts b/src/lib/dslChecker.ts index 514783b..cc121da 100644 --- a/src/lib/dslChecker.ts +++ b/src/lib/dslChecker.ts @@ -1,5 +1,15 @@ +/* +TODO: Create one class for each structure in a DSL ( cell, collection, ... ) +TODO: In any class insert a static method to check the form of a Object +TODO: Check type of attribute +TODO: Create DSLStructure ( id: number, value: structure ). +TODO: Check attribute generated automatically +*/ + +import Map from "./map.ts"; + /** - * Class to check if a json data is structured as a DSLStructure. + * Class to check if a json data has been structure as a DSLStructure. * @history * | Author | Action Performed | Data | * | --- | --- | --- | @@ -9,26 +19,159 @@ * @license MIT */ class DSLChecker { - /** - * Public construtorn, it do anything. - * @return {DSLChecker} This - */ - public constructor() {} - - /** - * Check if data rappresent a DSLStructure. If true, it returns a - * DSLCecker setted with the values inside data, else, it throw a - * exception. - * - * @param data {Object} JSON valid data - * @return {DSLStructure} Savable structure into DB - * @throws {DSLParseException} - */ - public check( data : Object ) : DSLStructure { - let structure : DSLStructure = new DSLStructure(); - - - - - } -} \ No newline at end of file + /** + * @description + * For any structure in the DSL, it store the set of mandatory params. + * @type {Map>} + */ + private mandatory : Map>; + + /** + * @description + * For any structure in the DSL, it store the set of optional params. + * @type {Map>} + */ + private optional : Map>; + + /** + * @description + * Public constructor, it do anything. + * @return {DSLChecker} This. + */ + public constructor() { + this.setMandatory(); + this.setOptional(); + } + + /** + * @description + * Check if data rappresent a DSLStructure. If true, it returns a + * DSLCecker setted with the values inside data, else, it throw a + * exception. + * + * @param data {Object} JSON valid data. + * @return {DSLStructure} Savable structure into DB. + */ + public check(data : Object) : boolean { + if (data !== undefined) { + /* + Create a deep copy of data. In this way, I can modify + *copy* and not to create side effect. + */ + let copy : Object = JSON.parse(JSON.stringify(data)); + + if (copy["root"] !== undefined) { + // The only once that it isn't a dsl component + delete copy["root"]; + let keys : Array = Object.keys(data); + + let error : boolean = false; + let index : number = 0; + + /* + For each dsl components. It will stop when a error + is occurred or no components have errors. + */ + while (!error && index < keys.length) { + let attribute : Object = copy[keys[index]]; + let type : string = attribute["pModel"]["type"]; + + error = !this.allRequiredAttributes( + attribute, + this.mandatory[type] + ); + + // Next key + index += 1; + } + + return error; + + } else { + return false; + } + } else { + return false; + } + } + + /** + * @description + * Check if all required attributes are present in the structure. + * @param struct {Object} + * Part of DSL Structure to check mandatory attributes. + * @return {boolean} + * True if all mandatory params are present, false otherwise. + */ + private allRequiredAttributes( + struct : Object, + required : Array + ) : boolean { + let correct : boolean = true; + let index : number = 0; + + while (correct && index < required.length) { + // Check if the param exists + correct = (struct[required[index]] !== undefined); + + // Next attribute + index += 1; + } + + return correct; + } + + /** + * @description + * Set all mandatory params of the DSL structures into *mandatory* Map. + */ + private setMandatory() : void { + this.mandatory["action"] = ["set"]; + this.mandatory["cell"] = ["input", "type"]; + this.mandatory["collection"] = ["name"]; + this.mandatory["column"] = ["name"]; + this.mandatory["dashboard"] = ["name"]; + this.mandatory["dashrow"] = []; + this.mandatory["document"] = []; + this.mandatory["index"] = []; + this.mandatory["row"] = ["name"]; + } + + /** + * @description + * Set all optional params of the DSL structures into *optional* Map. + */ + private setOptional() : void { + this.optional["action"] = []; + this.optional["cell"] = []; + this.optional["collection"] = [ + "label", + "id", + "weight" + ]; + this.optional["column"] = [ + "label", + "sortable", + "selectable", + "trasformation" + ]; + this.optional["dashboard"] = [ + "rows" + ]; + this.optional["dashrow"] = []; + this.optional["document"] = [ + "populate" + ]; + this.optional["index"] = [ + "perpage", + "populate", + "sortby", + "order", + "query" + ]; + this.optional["row"] = [ + "label", + "transformation" + ]; + } +} From a51d2c3df67c5b0cc58eb98ebc95374a8bebfd07 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Fri, 6 May 2016 18:09:03 +0200 Subject: [PATCH 041/157] Remove at type in the comments See issue#19 --- src/lib/dslChecker.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/lib/dslChecker.ts b/src/lib/dslChecker.ts index cc121da..2d34d53 100644 --- a/src/lib/dslChecker.ts +++ b/src/lib/dslChecker.ts @@ -22,14 +22,12 @@ class DSLChecker { /** * @description * For any structure in the DSL, it store the set of mandatory params. - * @type {Map>} */ private mandatory : Map>; /** * @description * For any structure in the DSL, it store the set of optional params. - * @type {Map>} */ private optional : Map>; From dc781a67b6e7bfb44e024857cf13d2e254457d09 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Fri, 6 May 2016 18:11:56 +0200 Subject: [PATCH 042/157] Correct description of check's return type See issue#19 --- src/lib/dslChecker.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lib/dslChecker.ts b/src/lib/dslChecker.ts index 2d34d53..397119e 100644 --- a/src/lib/dslChecker.ts +++ b/src/lib/dslChecker.ts @@ -48,7 +48,8 @@ class DSLChecker { * exception. * * @param data {Object} JSON valid data. - * @return {DSLStructure} Savable structure into DB. + * @return {boolean} + * True if data is a savable structure into DB, false otherwise. */ public check(data : Object) : boolean { if (data !== undefined) { From 906bc5d4dadd027e53d04dfcf0175e4b63796263 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Fri, 6 May 2016 18:19:02 +0200 Subject: [PATCH 043/157] Create file dslModes See issue#4 --- src/models/dslModel.ts | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 src/models/dslModel.ts diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts new file mode 100644 index 0000000..e69de29 From ee22f60d3b4c5c8241dc87ed671f30d11d5b7815 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sat, 7 May 2016 10:36:04 +0200 Subject: [PATCH 044/157] Started the user model --- src/models/userModel.ts | 123 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 123 insertions(+) create mode 100644 src/models/userModel.ts diff --git a/src/models/userModel.ts b/src/models/userModel.ts new file mode 100644 index 0000000..4bfd6b0 --- /dev/null +++ b/src/models/userModel.ts @@ -0,0 +1,123 @@ +import * as mongoose from "mongoose"; +import * as crypto from "crypto"; + +/** + * This is the model to represent users in MaaS. Extends model class. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Luca Bianco | Create class | 07/05/2016 | + * + * @author Luca Bianco + * @license MIT + */ + +class UserModel extends Model { + + private PWD_DEFAULT_ITERATIONS : number = 1000; + private PWD_LENGHT : number = 50; + + private USER_TYPES : Array = [ + "BASE", + "ADMIN", + "OWNER", + "SUPERADMIN" + ]; + + constructor() { + super(); + } + + protected getSchema() : mongoose.Schema { + schema : mongoose.Schema = new mongoose.Schema({ + username: { + type: String, + required: true, + sparse: true + }, + passwordHashed: { + type: String, + required: true + }, + passwordSalt: { + type: String, + required: true + }, + passwordIterations: { + type: Number, + default: this.PWD_DEFAULT_ITERATIONS + }, + level: { + type: String, + required: true, + enum: this.USER_TYPES, + default: this.USER_TYPES[0] + } + }); + + schema.virtual("password") + .set(function (password) : void { + this._password = password; + this.passwordSalt = this.generateSalt(); + this.passwordHashed = this.hashPassword(this._password); + }) + .get(function () : string { + return this._password; + }); + + this.setSchemaMethods(schema); + + return schema; + } + + private setSchemaMethods(schema : mongoose.Schema) : void { + schema.methods = { + + authenticate: function (passwordText : string) : boolean { + return this.hashPassword(passwordText) === this.hashed_pwd; + }, + + generateSalt: function () : string { + return crypto.randomBytes(16).toString("base64"); + }, + + hashPassword: function (password) : string { + return crypto + .pbkdf2Sync(password, + this.passwordSalt, + this.passwordIterations, + this.PWD_LENGTH) + .toString("base64"); + } + }; + } + + protected getModel() : mongoose.model { + return mongoose.model ("User", this.getSchema()); + } + + + public login(username: string, password: string) : Promise { + return new Promise( function (resolve, reject) { + model.findOne( + {username: username}, + function (error, user : mongoose.model) { + if (error) { + reject(err); + } else { + if ( !user.authenticate(password)) { + reject( new Error("Password non valida")); + } else { + delete user.passwordHashed; + delete user.passwordSalt; + delete user.passwordIterations; + resolve(user); + } + } + }) + }); + } +} + +export default UserModel; From e45f53165016a07d98ef428538c1cf3b406838f9 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Sat, 7 May 2016 11:09:28 +0200 Subject: [PATCH 045/157] Correct routes import/export --- src/routes/routerFacade.ts | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/src/routes/routerFacade.ts b/src/routes/routerFacade.ts index 3c274ec..ab34d58 100644 --- a/src/routes/routerFacade.ts +++ b/src/routes/routerFacade.ts @@ -9,7 +9,14 @@ * @license MIT */ -export {DatabaseRouter} from "./databaseRouter"; -export {DSLRouter} from "./dslRouter"; -export {UserRouter} from "./userRouter"; -export {CompanyRouter} from "./companyRouter"; +// Import the routes +import DSLRouter from "./dslRouter"; +import UserRouter from "./userRouter"; +import DatabaseRouter from "./databaseRouter"; +import CompanyRouter from "./companyRouter"; + +// Export the routes +export {default as DatabaseRouter} from "./databaseRouter"; +export {default as DSLRouter} from "./dslRouter"; +export {default as UserRouter} from "./userRouter"; +export {default as CompanyRouter} from "./companyRouter"; From 6bec125ae61d9fc4552d8a852e1be7868ca61669 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Sat, 7 May 2016 12:05:21 +0200 Subject: [PATCH 046/157] Complete class Check all flow struct but not throw exception if there is a mistake. See issue#19 --- src/lib/dslChecker.ts | 428 ++++++++++++++++++++++++++++++------------ 1 file changed, 307 insertions(+), 121 deletions(-) diff --git a/src/lib/dslChecker.ts b/src/lib/dslChecker.ts index 397119e..8b260c5 100644 --- a/src/lib/dslChecker.ts +++ b/src/lib/dslChecker.ts @@ -1,176 +1,362 @@ /* -TODO: Create one class for each structure in a DSL ( cell, collection, ... ) -TODO: In any class insert a static method to check the form of a Object -TODO: Check type of attribute -TODO: Create DSLStructure ( id: number, value: structure ). -TODO: Check attribute generated automatically -*/ +TODO: Remove assertion +TODO: Replace comment control with exception +TODO: Refactor method extractModel + */ -import Map from "./map.ts"; +import Map from "./map" +import * as assert from "assert" /** * Class to check if a json data has been structure as a DSLStructure. * @history * | Author | Action Performed | Data | - * | --- | --- | --- | + * | --- | --- | --- | + * | Andrea Mantovani | Completed class DSLChecker | 07/05/2016 | * | Andrea Mantovani | Create class | 06/05/2016 | * * @author Andrea Mantovani * @license MIT */ class DSLChecker { + private flowControl : Map<(struct : Object, id : string) => boolean>; + /** * @description - * For any structure in the DSL, it store the set of mandatory params. + * Default constructor. + * @return {DSLChecker} + * This. */ - private mandatory : Map>; + constructor() { + this.flowControl = {}; // Initialize + this.flowControl["cell"] = this.checkLeaf; + this.flowControl["collection"] = this.checkCollection; + this.flowControl["dashboard"] = this.checkDashboard; + this.flowControl["document"] = this.checkDocument; + this.flowControl["index"] = this.checkIndex; + this.flowControl["leaf"] = this.checkLeaf; + } /** * @description - * For any structure in the DSL, it store the set of optional params. + * Check if data represents a DSLStructure. The data use the editor to be + * create. Therefore, is not necessary all control. + * @param data {Object} + * JSON valid data. + * @return {boolean} + * True if data is a savable structure into DB, false otherwise. + * @throws {AssertionError} */ - private optional : Map>; + public check(data : Object) : boolean { + assert(data, "The param 'data' is undefined"); + + let root : string = data["root"]; + + // No root found + if (root === undefined) { + return false; + } + + let struct : Object = data[root]; + assert(struct, "Unexpected finish of structure"); + + let type : string = struct["type"]; + assert( + type, + `The attribute 'type' of the element ${root} is not defined` + ); + + let follow : (struct : Object, id : string) => boolean + = this.flowControl[type]; + + assert( + follow, + `The value ${type} as 'type', in the elemen ${root}, no math ` + + `with anything expected` + ); + + // Catch all exception throw from the innested calls. + try { + return follow(data, root); + + } catch (err : assert.AssertionError) { + throw err; + } + } /** * @description - * Public constructor, it do anything. - * @return {DSLChecker} This. + * Return true if the collection created it is right. + * @param data {Object} + * JSON valid data + * @param id {string} + * Id of the collection structure into *data* + * @return {boolean} + * True if be start here is possible reach a leaf structure. + * @throws {AssertionError} */ - public constructor() { - this.setMandatory(); - this.setOptional(); + private checkCollection(data : Object, id : string) : boolean { + let collStruct : Object = data[id]; + + // No collection found + if (collStruct === undefined) { + return false; + } + + // Extract the model of the collection + let collection : Object = this.extractModel(data, id); + let actions : Array = collection["action"]; + let index : string = collection["index"]; + let document : string = collection["document"]; + + /* + if (actions === undefined) { + throw new DSLParseStructureException( + `The collection ${id} don't have a setted action attribute` + ); + } + + if (index === undefined) { + throw new DSLParseStructureException( + `The collection ${id} don't have a setted index attribute` + ); + } + */ + return ( + this.checkLeafs(data, actions) && + this.flowControl["index"](data, index) && + this.flowControl["document"](data, document) + ); } /** * @description - * Check if data rappresent a DSLStructure. If true, it returns a - * DSLCecker setted with the values inside data, else, it throw a - * exception. - * - * @param data {Object} JSON valid data. + * Return true if the dashboard created it is right. + * @param data {Object} + * JSON valid data + * @param id {string} + * Id of the dashboard structure into *data* * @return {boolean} - * True if data is a savable structure into DB, false otherwise. + * True if be start here is possible reach a leaf structure. + * @throws {AssertionError} */ - public check(data : Object) : boolean { - if (data !== undefined) { - /* - Create a deep copy of data. In this way, I can modify - *copy* and not to create side effect. - */ - let copy : Object = JSON.parse(JSON.stringify(data)); - - if (copy["root"] !== undefined) { - // The only once that it isn't a dsl component - delete copy["root"]; - let keys : Array = Object.keys(data); - - let error : boolean = false; - let index : number = 0; - - /* - For each dsl components. It will stop when a error - is occurred or no components have errors. - */ - while (!error && index < keys.length) { - let attribute : Object = copy[keys[index]]; - let type : string = attribute["pModel"]["type"]; - - error = !this.allRequiredAttributes( - attribute, - this.mandatory[type] - ); - - // Next key - index += 1; - } - - return error; - - } else { - return false; - } - } else { + private checkDashboard(data : Object, id : string) : boolean { + let dashStruct : Object = data[id]; + + // No collection found + if (dashStruct === undefined) { return false; } + + // Extract the model of the dashboard + let dashboard : Object = this.extractModel(data, id); + let rows : Array = dashboard["rows"]; + + /* + if (rows === undefined) { + throw new DSLParseStructureException( + `The dashboard ${id} don't have a setted rows attribute` + ); + } + */ + // Is similar at what to happen in the function checkLeafs + let correct : boolean = true; + + rows.forEach((row : string) => { + // Get type for the current row + let type : string = this.extractType(data, row); + correct = correct && this.flowControl[type](data, row); + }); + + return correct; } /** * @description - * Check if all required attributes are present in the structure. - * @param struct {Object} - * Part of DSL Structure to check mandatory attributes. + * Return true if the Document created it is right. + * @param data {Object} + * JSON valid data + * @param id {string} + * Id of the document structure into *data* * @return {boolean} - * True if all mandatory params are present, false otherwise. + * True if be start here is possible reach a leaf structure. + * @throws {AssertionError} */ - private allRequiredAttributes( - struct : Object, - required : Array - ) : boolean { - let correct : boolean = true; - let index : number = 0; + private checkDocument(data : Object, id : string) : boolean { + let docStruct : Object = data[id]; + + // No collection found + if (docStruct === undefined) { + return false; + } + + // Extract the model of Document + let document : Object = this.extractModel(data, id); + let actions : Array = document["action"]; + let rows : Array = document["row"]; + + /* + if (actions === undefined) { + throw new DSLParseStructureException( + `The document ${id} don't have a setted action attribute` + ); + } + + if (rows === undefined) { + throw new DSLParseStructureException( + `The document ${id} don't have a setted row attribute` + ); + } + */ + return (this.checkLeafs(data, actions) && this.checkLeafs(data, rows)); + } + + /** + * @description + * Return true if the Index created it is right. + * @param data {Object} + * JSON valid data + * @param id {string} + * Id of the index structure into *data* + * @return {boolean} + * True if be start here is possible reach a leaf structure. + * @throws {AssertionError} + */ + private checkIndex(data : Object, id : string) : boolean { + let indexStruct : Object = data[id]; + + // No collection found + if (indexStruct === undefined) { + return false; + } - while (correct && index < required.length) { - // Check if the param exists - correct = (struct[required[index]] !== undefined); + // Extract the model of Index + let index : Object = this.extractModel(data, id); + let columns : Array = index["column"]; - // Next attribute - index += 1; + /* + if (columns === undefined) { + throw new DSLParseStructureException( + `The index ${id} don't have a setted column attribute` + ); } + */ + + return this.checkLeafs(data, columns); + } + + /** + * @description + * Return true if the general leaf created it is right. + * @param data {Object} + * JSON valid data + * @param id {string} + * Id of the leaf structure into *data* + * @return {boolean} + * True if is a really leaf, false otherwise. + * @throws {AssertionError} + */ + private checkLeaf(data : Object, id : string) : boolean { + let leafStruct : Object = data[id]; + + // No collection found + if (leafStruct === undefined) { + return false; + } + + /* + Common model for any leaf. If no exception is throw, the leaf will + be correct. + */ + this.extractModel(data, id); + return true; + } + + /** + * @description + * Call the *flowControl* for the case 'leaf' for each leafs. + * @param data {Object} + * JSON valid data + * @param ids {Array} + * Ids of each leafs + * @return {boolean} + * True if each calls at the *flowControl* returns true. + * @throws {AssertionError} + */ + private checkLeafs( + data : Object, + ids : Array + ) : boolean { + let correct : boolean = true; + + ids.forEach((id : string) => { + /* + Follow the control. If each calls at the flowControl returns true, + the structure will be correct. This because, also if only once + call of flowControl returns false, the operator && will keep + variable correct to the false. + */ + correct = correct && this.flowControl["leaf"](data, id); + }); return correct; } /** * @description - * Set all mandatory params of the DSL structures into *mandatory* Map. + * Get the pModel inside any structure. + * @param data {Object} + * JSON valid data + * @param id {string} + * Id of the structure into *data* + * @return {Object} + * The content of **pModel** attribute. + * @throws {AssertionError} */ - private setMandatory() : void { - this.mandatory["action"] = ["set"]; - this.mandatory["cell"] = ["input", "type"]; - this.mandatory["collection"] = ["name"]; - this.mandatory["column"] = ["name"]; - this.mandatory["dashboard"] = ["name"]; - this.mandatory["dashrow"] = []; - this.mandatory["document"] = []; - this.mandatory["index"] = []; - this.mandatory["row"] = ["name"]; + private extractModel(data : Object, id : string) : Object { + let model : Object = data[id]["pModel"]; + + /* + if (model === undefined) { + throw new DSLParseStructureException( + `The pModel for the structure ${id} is expected` + ); + } + */ + + return model; } /** * @description - * Set all optional params of the DSL structures into *optional* Map. + * Extract type from object received with the id passed by argument. + * @param data {Object} + * JSON valid data + * @param id {string} + * Key to access to the content + * @return {string} + * The type of object + * @throws {DSLParseStructureException} */ - private setOptional() : void { - this.optional["action"] = []; - this.optional["cell"] = []; - this.optional["collection"] = [ - "label", - "id", - "weight" - ]; - this.optional["column"] = [ - "label", - "sortable", - "selectable", - "trasformation" - ]; - this.optional["dashboard"] = [ - "rows" - ]; - this.optional["dashrow"] = []; - this.optional["document"] = [ - "populate" - ]; - this.optional["index"] = [ - "perpage", - "populate", - "sortby", - "order", - "query" - ]; - this.optional["row"] = [ - "label", - "transformation" - ]; + private extractType(data : Object, id : string) : string { + let struct : Object = data[id]; + /* + if (struct === undefined) { + throw new DSLParseStructureException( + "Unexpected finish of structure" + ) + + } + */ + let type : string = struct["type"]; + /* + if (type === undefined) { + throw new DSLParseStructureException( + `The attribute 'type' of the element ${id} ` + + "is not defined" + ) + } + */ + return type; } } From 7dd8376adc3be76965d584ded41bacf49e187055 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Sat, 7 May 2016 12:30:03 +0200 Subject: [PATCH 047/157] Add body parser --- package.json | 1 + typings.json | 1 + 2 files changed, 2 insertions(+) diff --git a/package.json b/package.json index c4ff215..bf430e9 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "author": "BugBusters bugbusterswe@gmail.com", "license": "MIT", "dependencies": { + "body-parser": "^1.15.1", "express": "^4.13.1" }, "devDependencies": { diff --git a/typings.json b/typings.json index 817e332..c1eb762 100644 --- a/typings.json +++ b/typings.json @@ -1,5 +1,6 @@ { "ambientDependencies": { + "body-parser": "registry:dt/body-parser#0.0.0+20160317120654", "chai": "registry:dt/chai#3.4.0+20160317120654", "express": "registry:dt/express#4.0.0+20160317120654", "express-serve-static-core": "registry:dt/express-serve-static-core#0.0.0+20160322035842", From b3cacd20a2642a6c282a45d96d9659574c2bd914 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Sat, 7 May 2016 12:30:18 +0200 Subject: [PATCH 048/157] Set endpoints --- src/maas.ts | 144 ++-------------------------------------------------- 1 file changed, 5 insertions(+), 139 deletions(-) diff --git a/src/maas.ts b/src/maas.ts index 0136105..961a728 100644 --- a/src/maas.ts +++ b/src/maas.ts @@ -1,154 +1,20 @@ import * as express from "express"; import * as bodyParser from "body-parser"; import * as http from "http"; -import {ConfigurationChooser} from "./config/configurationChooser"; -import {Configuration} from "./config/configuration"; -import {UserModel} from "./models/userModel"; -import {DSLModel} from "./models/dslModel"; -import {DatabaseModel} from "./models/databaseModel"; -import {CompanyModel} from "./models/companyModel"; -import {LevelChecker} from "./lib/levelChecker"; -import {AuthenticationChecker} from "./lib/authenticationChecker"; -import * as routes from "./routes"; - -// Get the current configuration -let configuration : Configuration = ConfigurationChooser.getConfig(); -let user : UserModel = new UserModel(); // Get the user's model -let dsl : DSLModel = new DSLModel(); // Get the dsl's model -let database : DatabaseModel = new DatabaseModel(); // Get the database's model -let company : CompanyModel = new CompanyModel(); // Get the company's model -// Get the instance of the level checker -let lvlChecker : LevelChecker = LevelChecker.getInstance(); -// Get the instance of the authentication checker -let authChecker : AuthenticationChecker = AuthenticationChecker.getInstance(); +import ConfigurationChooser from "./config/configurationChooser"; +import Configuration from "./config/configuration"; +import * as routes from "./routes/routerFacade"; // Initializing app let app : express.Express = express(); +let configuration : Configuration = ConfigurationChooser.getConfig(); // Allow to get data from body in JSON format app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); -// Middlewares' configuration -// Authenticator configuration -/*authChecker.initialize({ - secret: configuration.getServerSecret(), - getUserFunction: user.login -}); - -// Level configuration -lvlChecker.initialize({ - pathToLevel: ["body"] -});*/ - -// DSL Checker?? todo - // Routes' require -/*app.use("/api", routes); -app.post("/api/login", authChecker.login);*/ -app.post("/api/companies/:company_id/users", - function(req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - authChecker.authenticate(req.body.user_id); - next(); -}, function(err : Error, - req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - if (err) { - res.status(500).send("Authenticate yourself firstly!") - } - lvlChecker.requireOwner(req.body.user_id); - next(); -}, function(err : Error, - req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - if (err) { - res.status(500).send("You aren't an owner!") - } -}); - -app.put("/api/companies/:company_id/users/:user_id/credentials", - function(req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - authChecker.authenticate(req.body.user_id); - next(); - }, function(err : Error, - req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - if (err) { - res.status(500).send("Authenticate yourself firstly!") - } - } -); - -app.delete("api/companies/:company_id/users/:user_id", - function(req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - authChecker.authenticate(req.body.user_id); - next(); - }, function(err : Error, - req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - if (err) { - res.status(500).send("Authenticate yourself firstly!") - } - lvlChecker.requireOwner(req.body.user_id); - next(); - }, function(err : Error, - req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - if (err) { - res.status(500).send("You aren't an owner!"); - } - } -); - -app.get("/api/companies/:company_id/", - function(req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - authChecker.authenticate(req.body.user_id); - next(); - }, function(err : Error, - req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - if (err) { - res.status(500).send("Authenticate yourself firstly!") - } - } -); - -app.put("/api/companies/:company_id/", - function(req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - authChecker.authenticate(req.body.user_id); - next(); - }, function(err : Error, - req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - if (err) { - res.status(500).send("Authenticate yourself firstly!") - } - lvlChecker.requireAdmin(req.body.user_id); - next(); - }, function(err : Error, - req : express.Request, - res : express.Response, - next : express.NextFunction) : void { - res.status(500).send("You aren't an owner!"); - } -); +app.use("/api", routes); // Starting the server app.set("port", process.env.PORT || 3000); From b54d60170502ad5de78988e14d82e1299537ffcf Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Sat, 7 May 2016 14:03:40 +0200 Subject: [PATCH 049/157] Check the existance of structure before take its model See issue#19 --- src/lib/dslChecker.ts | 21 +++++---------------- 1 file changed, 5 insertions(+), 16 deletions(-) diff --git a/src/lib/dslChecker.ts b/src/lib/dslChecker.ts index 8b260c5..386fc84 100644 --- a/src/lib/dslChecker.ts +++ b/src/lib/dslChecker.ts @@ -1,7 +1,6 @@ /* TODO: Remove assertion TODO: Replace comment control with exception -TODO: Refactor method extractModel */ import Map from "./map" @@ -96,10 +95,8 @@ class DSLChecker { * @throws {AssertionError} */ private checkCollection(data : Object, id : string) : boolean { - let collStruct : Object = data[id]; - // No collection found - if (collStruct === undefined) { + if (data[id] === undefined) { return false; } @@ -141,10 +138,8 @@ class DSLChecker { * @throws {AssertionError} */ private checkDashboard(data : Object, id : string) : boolean { - let dashStruct : Object = data[id]; - // No collection found - if (dashStruct === undefined) { + if (data[id] === undefined) { return false; } @@ -183,10 +178,8 @@ class DSLChecker { * @throws {AssertionError} */ private checkDocument(data : Object, id : string) : boolean { - let docStruct : Object = data[id]; - // No collection found - if (docStruct === undefined) { + if (data[id] === undefined) { return false; } @@ -223,10 +216,8 @@ class DSLChecker { * @throws {AssertionError} */ private checkIndex(data : Object, id : string) : boolean { - let indexStruct : Object = data[id]; - // No collection found - if (indexStruct === undefined) { + if (data[id] === undefined) { return false; } @@ -257,10 +248,8 @@ class DSLChecker { * @throws {AssertionError} */ private checkLeaf(data : Object, id : string) : boolean { - let leafStruct : Object = data[id]; - // No collection found - if (leafStruct === undefined) { + if (data[id] === undefined) { return false; } From ad4ce2eababbf17cb25f79689463806dc1d29021 Mon Sep 17 00:00:00 2001 From: drigoni Date: Sat, 7 May 2016 17:34:01 +0200 Subject: [PATCH 050/157] Implement some methods See issue #6 --- src/models/companyModel.ts | 96 +++++++++++++++++++++++++++++--------- 1 file changed, 75 insertions(+), 21 deletions(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index dc4c728..196ea3d 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -1,6 +1,6 @@ import * as promise from "es6-promise"; import * as mongoose from "mongoose"; -import {Model} from "mongoose"; +import Model from "Model"; /** * This class define the company business logic. It contains model and scheme @@ -16,45 +16,99 @@ import {Model} from "mongoose"; * */ class CompanyModel extends Model{ - name : string; - idOwner : string; + /** + * @description company's name + */ + private name : string; + + /** + * @description id of the company's owner + */ + private idOwner : string; /** - * @description constructor + * @description Schema's company + */ + private companySchema; + + /** + * @description model's company + */ + private company; + + /** + * @description Constructor. It connect with the DB to find the company * @param name * @param idOwner * @return {CompanyModel} */ constructor (name : string, idOwner : string) { + this.name = name; this.idOwner = idOwner; - //verifico se esiste la company + this.companySchema = this.getConnection().Schema({ + name: String, + idOwner: String + }); + + this.company = this.getConnection().model("Company", + this.companySchema); } + /** + * @description Return the company's name and idOwner + * @param name + */ public getCompany(name : string) : CompanyModel{ - //return json - } + return this.company.findOne({name: this.name}, + function (err, user) { + // TODO: Something to return + }); + }; - public update(c : CompanyModel) : void { - //return json - } + /** + * @description Update the data of the company + * @param company model + */ + public update(company : CompanyModel) : void { + return this.company.findOneAndUpdate( + {name: this.name, idOwner: this.idOwner}, + c, function (err, user) { + // TODO: Something to update + }); + }; + /** + * @description Delete the company from the DB + */ public delete() : void { - //return json - } - - + return this.company.findOneAndRemove( + {name: this.name, idOwner: this.idOwner}, function (err, user) { + // TODO: Something to delete + }); + }; - static private findCompany(name : string) : CompanyModel{ - //return json + /** + * @description Create a new company into DB and return it + * @param name is the company's name + * @param email is the owner's email + * @param password is the owner's password + * @return {CompanyModel} + */ + static public createCompany(name : CompanyModel, email : string, + password : string) : CompanyModel{ + // TODO: make a company and save it } - static public createCompany(c : CompanyModel, e : string, - p : string) : CompanyModel { - //create user - //return json - } + /** + * @description find a company in the DB + * @param name of the company + * @return {CompanyModel} + */ + static private findCompany(name : string) : CompanyModel{ + // TODO: find a company and return it or give error + }; } From 219f598018b566b3ee9096c2a2126c5dc38d9c85 Mon Sep 17 00:00:00 2001 From: drigoni Date: Sat, 7 May 2016 17:43:23 +0200 Subject: [PATCH 051/157] Template for companyModelTest See issue #6 --- test/models/companyModelTest.ts | 35 +++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 test/models/companyModelTest.ts diff --git a/test/models/companyModelTest.ts b/test/models/companyModelTest.ts new file mode 100644 index 0000000..df593c6 --- /dev/null +++ b/test/models/companyModelTest.ts @@ -0,0 +1,35 @@ +import * as CompanyModel from "../../src/models/companyModel"; +import * as Chai from "chai" + +/** + * CompanyModel implements the company business logic. It contains model and + * scheme defined by MongooseJS. + * + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Rigoni | Create class | 06/05/2016 | + * + * @author Davide Rigoni + * @copyright MIT + * + * + */ + +describe("DatabaseModel", () => { + + /* + let toTest:someThing; // Name of the object to test + // Call one of the many function that are in the Mocha framework + beforeEach(function ():void { + toTest = new someThing(); // You can do something before every test + }); + // This function starts a single test + describe("#nameOfWhatYouAreTesting", () => { + it("should ", () => { + // Your code here + Chai.expect(toTest.sayHello(name)).to.equal("Hello Derp"); + }); + */ +}); \ No newline at end of file From 814378629b0b3935d6efdc998c8f526cd70854a0 Mon Sep 17 00:00:00 2001 From: drigoni Date: Sat, 7 May 2016 17:44:43 +0200 Subject: [PATCH 052/157] Add some stuff --- package.json | 1 + src/models/companyModel.ts | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index b1f96dc..98651b9 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "author": "BugBusters bugbusterswe@gmail.com", "license": "MIT", "dependencies": { + "chai": "^3.5.0", "express": "^4.13.1", "mongoose": "^4.4.14", "promise": "^7.1.1" diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index 196ea3d..e38d24c 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -3,8 +3,8 @@ import * as mongoose from "mongoose"; import Model from "Model"; /** - * This class define the company business logic. It contains model and scheme - * defined by MongooseJS. + * CompanyModel implements the company business logic. It contains model and + * scheme defined by MongooseJS. * * @history * | Author | Action Performed | Data | From 90bbef97ef685ecc3eecce442ea7a8c5a3ee6927 Mon Sep 17 00:00:00 2001 From: drigoni Date: Sat, 7 May 2016 17:51:57 +0200 Subject: [PATCH 053/157] Add companyRouterTest and install chai See issue #11 --- package.json | 1 + src/routes/companyRouter.ts | 20 +++++++++++++++----- test/routes/companyRouterTest.ts | 32 ++++++++++++++++++++++++++++++++ 3 files changed, 48 insertions(+), 5 deletions(-) create mode 100644 test/routes/companyRouterTest.ts diff --git a/package.json b/package.json index c4ff215..81f3650 100644 --- a/package.json +++ b/package.json @@ -40,6 +40,7 @@ "author": "BugBusters bugbusterswe@gmail.com", "license": "MIT", "dependencies": { + "chai": "^3.5.0", "express": "^4.13.1" }, "devDependencies": { diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index 50111d8..cd6310a 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -41,11 +41,21 @@ class CompanyRouter { (req : express.Request, res : express.Response, next : express.NextFunction) => { - // Get the id of the database to query - let companyId = req.param[0]; - //Query the database - //If something goes wrong, call next() - next(); + /* + * Here I use authentication checker and I need to check + * the user level. + * 1 - Call authentication checker as class .authenticate + * authenticationChecker.authenticate() -> returns a boolean + * + * If the boolean returned is `false` the user + * hasn't right permission and so I raise a error and + * I have to call next with the error. + * + * 2 - See 1 but with level checker. The minimum is MEMBER. + * If > MEMBER I query the database. + * + * // If something goes wrong, call next() + * // next(/*new Error("description")*/); }); } diff --git a/test/routes/companyRouterTest.ts b/test/routes/companyRouterTest.ts new file mode 100644 index 0000000..8403d59 --- /dev/null +++ b/test/routes/companyRouterTest.ts @@ -0,0 +1,32 @@ +import * as CompanyRouter from "../../src/routes/companyRouter"; +import * as express from "express"; +import * as Chai from "chai"; + +/** + * This is the test for CompanyRouter class + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Rigoni | Create class | 03/05/2016 | + * + * @author Davide Rigoni + * @copyright MIT + * + * Created by Davide Rigoni on 03/05/16. + */ +describe("DatabaseRouter", () => { + + /* nothing to test for now + let toTest : DatabaseRouter; + let dummyExpress : express.Express = express(); + beforeEach(function () : void { + toTest = new DatabaseRouter(dummyExpress); + }); + describe("#nameOfWhatYouAreTesting", () => { + it ("should ", () => { + // Your code here + }); + }); + */ +}); \ No newline at end of file From 945125df08e1038f202999f56b992c41ac71d725 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Sat, 7 May 2016 17:55:59 +0200 Subject: [PATCH 054/157] Replace all AssertionError with Error See issue#19 --- src/lib/dslChecker.ts | 90 +++++++++++++++++++++---------------------- 1 file changed, 45 insertions(+), 45 deletions(-) diff --git a/src/lib/dslChecker.ts b/src/lib/dslChecker.ts index 386fc84..a77ec84 100644 --- a/src/lib/dslChecker.ts +++ b/src/lib/dslChecker.ts @@ -4,7 +4,6 @@ TODO: Replace comment control with exception */ import Map from "./map" -import * as assert from "assert" /** * Class to check if a json data has been structure as a DSLStructure. @@ -44,10 +43,12 @@ class DSLChecker { * JSON valid data. * @return {boolean} * True if data is a savable structure into DB, false otherwise. - * @throws {AssertionError} + * @throws {Error} */ public check(data : Object) : boolean { - assert(data, "The param 'data' is undefined"); + if (data === undefined) { + throw new Error("The param 'data' is undefined"); + } let root : string = data["root"]; @@ -57,28 +58,34 @@ class DSLChecker { } let struct : Object = data[root]; - assert(struct, "Unexpected finish of structure"); + + if (struct === undefined) { + throw new Error("Unexpected finish of structure"); + } let type : string = struct["type"]; - assert( - type, - `The attribute 'type' of the element ${root} is not defined` - ); + + if (type === undefined) { + throw new Error( + `The attribute 'type' of the element ${root} is not defined` + ); + } let follow : (struct : Object, id : string) => boolean = this.flowControl[type]; - assert( - follow, - `The value ${type} as 'type', in the elemen ${root}, no math ` + - `with anything expected` - ); + if (follow === undefined) { + throw new Error( + `The value ${type} as 'type', in the elemen ${root}, no ` + + `math with anything expected` + ); + } // Catch all exception throw from the innested calls. try { return follow(data, root); - } catch (err : assert.AssertionError) { + } catch (err : Error) { throw err; } } @@ -92,7 +99,7 @@ class DSLChecker { * Id of the collection structure into *data* * @return {boolean} * True if be start here is possible reach a leaf structure. - * @throws {AssertionError} + * @throws {Error} */ private checkCollection(data : Object, id : string) : boolean { // No collection found @@ -106,19 +113,18 @@ class DSLChecker { let index : string = collection["index"]; let document : string = collection["document"]; - /* if (actions === undefined) { - throw new DSLParseStructureException( + throw new Error( `The collection ${id} don't have a setted action attribute` ); } if (index === undefined) { - throw new DSLParseStructureException( + throw new Error( `The collection ${id} don't have a setted index attribute` ); } - */ + return ( this.checkLeafs(data, actions) && this.flowControl["index"](data, index) && @@ -135,7 +141,7 @@ class DSLChecker { * Id of the dashboard structure into *data* * @return {boolean} * True if be start here is possible reach a leaf structure. - * @throws {AssertionError} + * @throws {Error} */ private checkDashboard(data : Object, id : string) : boolean { // No collection found @@ -147,13 +153,12 @@ class DSLChecker { let dashboard : Object = this.extractModel(data, id); let rows : Array = dashboard["rows"]; - /* if (rows === undefined) { - throw new DSLParseStructureException( + throw new Error( `The dashboard ${id} don't have a setted rows attribute` ); } - */ + // Is similar at what to happen in the function checkLeafs let correct : boolean = true; @@ -175,7 +180,7 @@ class DSLChecker { * Id of the document structure into *data* * @return {boolean} * True if be start here is possible reach a leaf structure. - * @throws {AssertionError} + * @throws {Error} */ private checkDocument(data : Object, id : string) : boolean { // No collection found @@ -188,19 +193,18 @@ class DSLChecker { let actions : Array = document["action"]; let rows : Array = document["row"]; - /* if (actions === undefined) { - throw new DSLParseStructureException( + throw new Error( `The document ${id} don't have a setted action attribute` ); } if (rows === undefined) { - throw new DSLParseStructureException( + throw new Error( `The document ${id} don't have a setted row attribute` ); } - */ + return (this.checkLeafs(data, actions) && this.checkLeafs(data, rows)); } @@ -213,7 +217,7 @@ class DSLChecker { * Id of the index structure into *data* * @return {boolean} * True if be start here is possible reach a leaf structure. - * @throws {AssertionError} + * @throws {Error} */ private checkIndex(data : Object, id : string) : boolean { // No collection found @@ -225,13 +229,11 @@ class DSLChecker { let index : Object = this.extractModel(data, id); let columns : Array = index["column"]; - /* if (columns === undefined) { - throw new DSLParseStructureException( + throw new Error( `The index ${id} don't have a setted column attribute` ); } - */ return this.checkLeafs(data, columns); } @@ -245,7 +247,7 @@ class DSLChecker { * Id of the leaf structure into *data* * @return {boolean} * True if is a really leaf, false otherwise. - * @throws {AssertionError} + * @throws {Error} */ private checkLeaf(data : Object, id : string) : boolean { // No collection found @@ -270,7 +272,7 @@ class DSLChecker { * Ids of each leafs * @return {boolean} * True if each calls at the *flowControl* returns true. - * @throws {AssertionError} + * @throws {Error} */ private checkLeafs( data : Object, @@ -300,18 +302,16 @@ class DSLChecker { * Id of the structure into *data* * @return {Object} * The content of **pModel** attribute. - * @throws {AssertionError} + * @throws {Error} */ private extractModel(data : Object, id : string) : Object { let model : Object = data[id]["pModel"]; - /* if (model === undefined) { - throw new DSLParseStructureException( + throw new Error( `The pModel for the structure ${id} is expected` ); } - */ return model; } @@ -325,27 +325,27 @@ class DSLChecker { * Key to access to the content * @return {string} * The type of object - * @throws {DSLParseStructureException} + * @throws {Error} */ private extractType(data : Object, id : string) : string { let struct : Object = data[id]; - /* + if (struct === undefined) { - throw new DSLParseStructureException( + throw new Error( "Unexpected finish of structure" ) } - */ + let type : string = struct["type"]; - /* + if (type === undefined) { - throw new DSLParseStructureException( + throw new Error( `The attribute 'type' of the element ${id} ` + "is not defined" ) } - */ + return type; } } From 03376d738a36bad36e40b18d4e789c9cf90c4318 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Sun, 8 May 2016 12:21:15 +0200 Subject: [PATCH 055/157] Add a space --- src/models/databaseModel.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 9de0e7b..76ac38a 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -35,4 +35,4 @@ class DatabaseModel { } } -export default DatabaseModel; \ No newline at end of file +export default DatabaseModel; From 9a6c734389eb66d0544cc187eb327c16224ddaea Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sun, 8 May 2016 16:43:25 +0200 Subject: [PATCH 056/157] Created the module for the authentication --- src/lib/AuthenticationChecker.ts | 98 ++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 src/lib/AuthenticationChecker.ts diff --git a/src/lib/AuthenticationChecker.ts b/src/lib/AuthenticationChecker.ts new file mode 100644 index 0000000..d180a7c --- /dev/null +++ b/src/lib/AuthenticationChecker.ts @@ -0,0 +1,98 @@ +/** + * This class is used to check the authentication for the requests + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Luca Bianco | Create class | 07/05/2016 | + * + * @author Luca Bianco + * @license MIT + */ + +class AuthenticationChecker { + + private secret : string; + private authenticateFunction : any; + + private DEFAULT_EXPIRE_TIME : number = 60 * 24 * 7; + + private USERNAME_BODY_FIELD : string = "username"; + private PASSWORD_BODY_FIELD : string = "username"; + + constructor() { + + } + + public login(request, response) : void { + let username : string = request.body[this.USERNAME_BODY_FIELD]; + let password : string = request.body[this.PASSWORD_BODY_FIELD]; + + UserModel + .login(username, password) + .then(function (error, user) { + if ( error || !user ) { + this.loginFailed(response); + } else { + let userToken : string = this.createToken( user ); + response.status(200); + response.json({ + done: true, + message: "Authentication done", + token: userToken, + user_id: user._id + }); + } + }) + } + + public authenticate (request, response, next) { + let token : string = request.body.token || + request.query.token || + request.headers["x-access-token"]; + + if ( !token ) { + this.responseTokenNotFound(response); + } else { + jwt.verify(token, this.secret, function(err, decoded) { + if ( err ) { + this.responseAuthenticationFailed(response); + } else { + request.user = decoded; + next(); + } + }); + } + } + + private createToken( data : any ) { + return jwt.sign({ + data: data, + expireTime: this.DEFAULT_EXPIRE_TIME + }); + } + + private responseTokenNotFound( response ) : void { + response.status(403); + response.json({ + done: false, + message: "Authentication failed. No Token Found" + }); + } + + private responseAuthenticationFailed( response ) : void { + response.status(403); + response.json({ + done: false, + message: "Authentication failed. Token invalid" + }); + } + + private loginFailed( response ) : void { + response.status(401); + response.json({ + done: false, + message: "Login Failed" + }); + } +} From ff837448102992ae6b595ea7ac801afaca0aadfd Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sun, 8 May 2016 17:10:47 +0200 Subject: [PATCH 057/157] Created the class levelChecker --- src/lib/LevelChecker.ts | 45 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 src/lib/LevelChecker.ts diff --git a/src/lib/LevelChecker.ts b/src/lib/LevelChecker.ts new file mode 100644 index 0000000..caf1a25 --- /dev/null +++ b/src/lib/LevelChecker.ts @@ -0,0 +1,45 @@ +/** + * This class checks the level of the user from the request + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Luca Bianco | Create class | 07/05/2016 | + * + * @author Luca Bianco + * @license MIT + * + */ + +class LevelChecker { + + private levelsAllowed : Array; + + constructor (levelsAllowed : Array) { + this.levelsAllowed = levelsAllowed; + } + + public check(request, response, next ) : void { + + let user : Object = request.user || undefined; + + if ( !user ) { + this.accessDenied(response); + } else { + if ( this.levelsAllowed.indexOf(user.level) ) { + // Level is inside of allowed so go to next middleware + next(); + } else { + this.accessDenied(response); + } + } + } + + private accessDenied(response) : void { + response.status(400); + response.json({ + done: false, + message: "Unauthorized" + }); + } +} From c12de4fe1252a15b52f3e289db62fce5a1c9c43b Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Sun, 8 May 2016 18:05:59 +0200 Subject: [PATCH 058/157] Use definition to mongoose and add method Add method: get, getAll, add See issue#4 --- src/models/dslModel.ts | 189 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 189 insertions(+) diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index e69de29..782dded 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -0,0 +1,189 @@ +import * as mongoose from "mongoose"; +import Model from "./model.ts"; + +type Promise = mongoose.Promise; + +/** + * Define the form of a permission of a user on the DSL. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Andrea Mantovani | Create interface | 07/05/2016 | + * + * @author Andrea Mantovani + * @license MIT + */ +export interface PermissionOnDSL { + /** + * @description + * Id user + */ + user : string; + + /** + * @description + * Set the permission of read a DSL + */ + read : boolean; + + /** + * @description + * Set the permission of execute a DSL + */ + exec : boolean; +} + +/** + * Define the attribute of a dsl's document. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Andrea Mantovani | Create interface | 08/05/2016 | + * + * @author Andrea Mantovani + * @license MIT + */ +export interface DSLDocument extends mongoose.Document { + /** + * @description + * Register of users with access to the DSL + */ + permission : Array, + /** + * @description + * Code of the DSL + */ + content : string; +} + +/** + * DSLModel implements the dsl business logic. It contains model and scheme + * defined by MongooseJS. + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Andrea Mantovani | Add method *get*, *getAll*, *add* | 08/05/2016 | + * | Andrea Mantovani | Create class | 07/05/2016 | + * + * @author Andrea Mantovani + * @license MIT + */ +export class DSLModel extends Model { + /** + * Schema of the collection in the MongoDB database. It follows the + * definition declared in the DSLDocument interface. + */ + private static schema : mongoose.Schema = new mongoose.Schema({ + permission: [{user: String, read: Boolean, exec: Boolean}], + content: String + }); + + /** + * Model's dsl + */ + private model : mongoose.Model; + + /** + * Default constructor. + * @return {DSLModel} + * This. + */ + constructor() { + this.model = this.getConnection().model( + "DSL", + DSLModel.schema + ); + } + + /** + * Get the DLSs that the user have access it. + * @param user {string} + * Id user + * @return {Promise} + * The promise for the set of DSL'code. + */ + public getAll(user : string) : Promise { + return this.model + /* + Get all relative DSL document where the user is show in the + permissions table + */ + .find({ + permission: { + $elemMatch: { // Necessary for multiple conditions + user: user, + read: true + } + } + }) + /* + Select only the code of the DSL + */ + .select("content") + /* + Exec query + */ + .exec(); + } + + /** + * Get the DSL with the id specified and the user is able to access + * @param user {string} + * Id of the user + * @param id {string} + * Id of the DSL + * @return {Promise} + * The promise for the DSL's code. + */ + public get(user : string, id : string) : Promise { + // Take the only one matching result + return this.model.findOne({ + _id: id, // Univocal key assigned by MongoDB + permission: { + $elemMatch: { + user: user, + read: true + } + } + }) + .select("content") + .exec(); + } + + /** + * Save DSLDocument in the database. + * @param dsl {DSLDocument} + * Any compliant object at the DSLDocument interface + * @returns {Promise} + * Promise of the request to save the document into the database. The + * template param defines the *resolve* data type when the promise + * has resolved. + */ + public add(dsl : DSLDocument) : + Promise<(data : Result) => void> { + return new mongoose.Promise<(data : Result) => void>(( + reject : (err : Object) => void, // Object is better than any + resolve : (data : Result) => void + ) => { + /* + Create an other document within the value of param dsl. + In this way, there isn't any problem with the real content of dls. + */ + let doc : DSLDocument = new this.model({ + permission: dsl.permission, + content: dsl.content + }); + + // Save dsl + doc.save( (err : Object, data : Result) => { + if (err !== undefined) { + reject(err); + } else { + resolve(data); + } + }); + }); + } +} From 3cbe17eb97927df59cb0215f4152fe6ac4db7e64 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Sun, 8 May 2016 21:40:44 +0200 Subject: [PATCH 059/157] Add methods update and delete. Use HTML for class'history. See issue#4 --- src/models/dslModel.ts | 65 +++++++++++++++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 10 deletions(-) diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index 782dded..0e953c7 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -62,10 +62,25 @@ export interface DSLDocument extends mongoose.Document { * DSLModel implements the dsl business logic. It contains model and scheme * defined by MongooseJS. * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Andrea Mantovani | Add method *get*, *getAll*, *add* | 08/05/2016 | - * | Andrea Mantovani | Create class | 07/05/2016 | + * + * + * + * + * + * + * + * + * + *
AuthorAction PerformedData
Andrea Mantovani + * Add methods: + *
    + *
  • *get*
  • + *
  • *getAll*
  • + *
  • *add*
  • + *
  • *update*
  • + *
  • *delete*
  • + *
+ *
08/05/2016
Andrea MantovaniCreate class07/05/2016
* * @author Andrea Mantovani * @license MIT @@ -102,7 +117,8 @@ export class DSLModel extends Model { * @param user {string} * Id user * @return {Promise} - * The promise for the set of DSL'code. + * The promise for the set of DSL documents with only the attribute + * content. */ public getAll(user : string) : Promise { return this.model @@ -134,8 +150,8 @@ export class DSLModel extends Model { * Id of the user * @param id {string} * Id of the DSL - * @return {Promise} - * The promise for the DSL's code. + * @return {Promise} + * The promise for the DSL document with only the attribute content. */ public get(user : string, id : string) : Promise { // Take the only one matching result @@ -158,7 +174,7 @@ export class DSLModel extends Model { * Any compliant object at the DSLDocument interface * @returns {Promise} * Promise of the request to save the document into the database. The - * template param defines the *resolve* data type when the promise + * template param *Result* defines the param type when the promise * has resolved. */ public add(dsl : DSLDocument) : @@ -169,7 +185,7 @@ export class DSLModel extends Model { ) => { /* Create an other document within the value of param dsl. - In this way, there isn't any problem with the real content of dls. + In this way, there isn't any problem with the real content of dsl. */ let doc : DSLDocument = new this.model({ permission: dsl.permission, @@ -177,7 +193,7 @@ export class DSLModel extends Model { }); // Save dsl - doc.save( (err : Object, data : Result) => { + doc.save((err : Object, data : Result) => { if (err !== undefined) { reject(err); } else { @@ -186,4 +202,33 @@ export class DSLModel extends Model { }); }); } + + /** + * Udpate the dsl'code with the id specified + * @param id {string} + * Id of the dsl + * @param content {string} + * Code to insert in the the dsl + * @return {Promise} + * Promise to the returned document after the operation. To more + * information about the structure of document refer to the official + * documentation: [Update#Output - MongoDB](http://bit.ly/1Ygx5UW) + */ + public update(id : string, content : string) : Promise { + // Update specified dsl and return the mongoose.Promise + return this.model.update({_id: id}, {content: content}).exec(); + } + + /** + * Delete the dsl with id specified. + * @param id {string} + * Id of the dsl + * @returns {Promise} + * Promise to the null returned document. Define **only** the + * *onReject* function. + */ + public delete(id : string) : Promise<{}> { + // Remove specified dsl and return the mongoose.Promise + return this.model.remove({_id: id}).exec(); + } } From 7a1a51072c6a2d883b56384c6f9feff10dd89d85 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Mon, 9 May 2016 09:41:34 +0200 Subject: [PATCH 060/157] Import mongoose --- src/models/databaseModel.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 76ac38a..7075579 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -1,3 +1,4 @@ +import * as moongose from "mongoose"; /** * DatabaseModel manage all connections to MongoDB companies databases. * Implements model and schema of MongooseJS. From c5e31929db66be6d06c5fbd406b55017f1b21327 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 9 May 2016 11:05:00 +0200 Subject: [PATCH 061/157] Add test for DSLChecker See issue#19 --- test/lib/dslCheckerTest.ts | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 test/lib/dslCheckerTest.ts diff --git a/test/lib/dslCheckerTest.ts b/test/lib/dslCheckerTest.ts new file mode 100644 index 0000000..0effa95 --- /dev/null +++ b/test/lib/dslCheckerTest.ts @@ -0,0 +1,26 @@ +import DSLChecker from "../../src/lib/dslChecker" +import * as mocha from "mocha" +import * as Chai from "chai" + +describe("DSLCheckTest", () => { + + let toTest : DSLChecker; + + // Call one of the many function that are in the Mocha framework + beforeEach(() => { + toTest = new DSLChecker(); + }); + + // This function starts a single test + describe("#workWithCell", () => { + it ("should return true", () => { + Chai.expect(toTest.check({ + root: "1", + "1": { + type: "cell", + pModel: {} + } + })).to.equal( true ); + }); + }); +}); \ No newline at end of file From 1319fc3405cfe1d2e303b50dc9a2fac587b530d0 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 9 May 2016 11:07:05 +0200 Subject: [PATCH 062/157] Static member extract type and model See issue#19 --- src/lib/dslChecker.ts | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/src/lib/dslChecker.ts b/src/lib/dslChecker.ts index a77ec84..e932b6e 100644 --- a/src/lib/dslChecker.ts +++ b/src/lib/dslChecker.ts @@ -85,7 +85,7 @@ class DSLChecker { try { return follow(data, root); - } catch (err : Error) { + } catch (err) { throw err; } } @@ -108,7 +108,7 @@ class DSLChecker { } // Extract the model of the collection - let collection : Object = this.extractModel(data, id); + let collection : Object = DSLChecker.extractModel(data, id); let actions : Array = collection["action"]; let index : string = collection["index"]; let document : string = collection["document"]; @@ -150,7 +150,7 @@ class DSLChecker { } // Extract the model of the dashboard - let dashboard : Object = this.extractModel(data, id); + let dashboard : Object = DSLChecker.extractModel(data, id); let rows : Array = dashboard["rows"]; if (rows === undefined) { @@ -164,7 +164,7 @@ class DSLChecker { rows.forEach((row : string) => { // Get type for the current row - let type : string = this.extractType(data, row); + let type : string = DSLChecker.extractType(data, row); correct = correct && this.flowControl[type](data, row); }); @@ -189,7 +189,7 @@ class DSLChecker { } // Extract the model of Document - let document : Object = this.extractModel(data, id); + let document : Object = DSLChecker.extractModel(data, id); let actions : Array = document["action"]; let rows : Array = document["row"]; @@ -226,7 +226,7 @@ class DSLChecker { } // Extract the model of Index - let index : Object = this.extractModel(data, id); + let index : Object = DSLChecker.extractModel(data, id); let columns : Array = index["column"]; if (columns === undefined) { @@ -259,7 +259,7 @@ class DSLChecker { Common model for any leaf. If no exception is throw, the leaf will be correct. */ - this.extractModel(data, id); + DSLChecker.extractModel(data, id); return true; } @@ -304,7 +304,7 @@ class DSLChecker { * The content of **pModel** attribute. * @throws {Error} */ - private extractModel(data : Object, id : string) : Object { + private static extractModel(data : Object, id : string) : Object { let model : Object = data[id]["pModel"]; if (model === undefined) { @@ -327,7 +327,7 @@ class DSLChecker { * The type of object * @throws {Error} */ - private extractType(data : Object, id : string) : string { + private static extractType(data : Object, id : string) : string { let struct : Object = data[id]; if (struct === undefined) { @@ -349,3 +349,5 @@ class DSLChecker { return type; } } + +export default DSLChecker; From 642e8f85ec0408a5aebf4779799d40e6369d0b0e Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 9 May 2016 11:08:01 +0200 Subject: [PATCH 063/157] Option noImplicitAny set false See issue#19 --- burstmake.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/burstmake.json b/burstmake.json index 8e097ef..70c2757 100644 --- a/burstmake.json +++ b/burstmake.json @@ -5,7 +5,7 @@ "moduleResolution" : "node", "target": "es5", "declaration": false, - "noImplicitAny": true, + "noImplicitAny": false, "noEmitOnError": true, "sourceMap": true }, From b9adce6eaafd135e2366c581bc147c3782bfd06e Mon Sep 17 00:00:00 2001 From: drigoni Date: Mon, 9 May 2016 11:36:17 +0200 Subject: [PATCH 064/157] Change some stuff Signed-off-by: drigoni --- src/models/companyModel.ts | 40 +++++++++++++------------------------- 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index e38d24c..432d7b7 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -1,6 +1,12 @@ -import * as promise from "es6-promise"; import * as mongoose from "mongoose"; -import Model from "Model"; +import {Model} from "./model"; + + +interface CompanyDocument extends mongoose.Document { + name : string, + idOwner : string; +} + /** * CompanyModel implements the company business logic. It contains model and @@ -15,26 +21,17 @@ import Model from "Model"; * @license MIT * */ -class CompanyModel extends Model{ - /** - * @description company's name - */ - private name : string; - - /** - * @description id of the company's owner - */ - private idOwner : string; - +export class CompanyModel extends Model { /** * @description Schema's company */ - private companySchema; + private static schema : mongoose.Schema = + new mongoose.Schema({name: String, idOwner: String}); /** * @description model's company */ - private company; + private company : mongoose.Model; /** * @description Constructor. It connect with the DB to find the company @@ -43,17 +40,8 @@ class CompanyModel extends Model{ * @return {CompanyModel} */ constructor (name : string, idOwner : string) { - - this.name = name; - this.idOwner = idOwner; - - this.companySchema = this.getConnection().Schema({ - name: String, - idOwner: String - }); - this.company = this.getConnection().model("Company", - this.companySchema); + CompanyModel.schema); } /** @@ -71,7 +59,7 @@ class CompanyModel extends Model{ * @description Update the data of the company * @param company model */ - public update(company : CompanyModel) : void { + public update(company : CompanyDocument) : void { return this.company.findOneAndUpdate( {name: this.name, idOwner: this.idOwner}, c, function (err, user) { From cbb4ee95135a36693fc0046f53af772842589bfb Mon Sep 17 00:00:00 2001 From: drigoni Date: Mon, 9 May 2016 11:39:12 +0200 Subject: [PATCH 065/157] Try new key GPG --- src/models/companyModel.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index 432d7b7..60c5e31 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -6,8 +6,6 @@ interface CompanyDocument extends mongoose.Document { name : string, idOwner : string; } - - /** * CompanyModel implements the company business logic. It contains model and * scheme defined by MongooseJS. From 336b576685c965818d5afa20957aa27bba963cb6 Mon Sep 17 00:00:00 2001 From: drigoni Date: Mon, 9 May 2016 11:45:47 +0200 Subject: [PATCH 066/157] Test GPG --- src/models/companyModel.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index 60c5e31..3c3299c 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -42,6 +42,7 @@ export class CompanyModel extends Model { CompanyModel.schema); } + /** * @description Return the company's name and idOwner * @param name From 446e5e5bb50d8c8794411dbe93c1e11ba2f4289a Mon Sep 17 00:00:00 2001 From: drigoni Date: Mon, 9 May 2016 11:47:39 +0200 Subject: [PATCH 067/157] Test GPG --- src/models/companyModel.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index 3c3299c..60c5e31 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -42,7 +42,6 @@ export class CompanyModel extends Model { CompanyModel.schema); } - /** * @description Return the company's name and idOwner * @param name From 5dc3c452260e59b8a3ff53905d2df7f311955b73 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Mon, 9 May 2016 11:59:33 +0200 Subject: [PATCH 068/157] Try GPG --- src/models/databaseModel.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 7075579..36a9452 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -5,6 +5,7 @@ import * as moongose from "mongoose"; * * This model represent a connection to a company. * + * * @history * | Author | Action Performed | Data | * | --- | --- | --- | From 6d4aaadd7678cca12688cfdd71c3d223d0b79eb3 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Mon, 9 May 2016 12:29:54 +0200 Subject: [PATCH 069/157] Integration with @mdipirro code --- src/models/databaseModel.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 36a9452..6626a21 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -1,4 +1,5 @@ import * as moongose from "mongoose"; +import Model from "./model"; /** * DatabaseModel manage all connections to MongoDB companies databases. * Implements model and schema of MongooseJS. @@ -17,11 +18,17 @@ import * as moongose from "mongoose"; * */ -class DatabaseModel { +class DatabaseModel extends Model { + /** + * @description Call the super constructor. + * + * @return {DatabaseModel} + * This + */ constructor () { - // For now nothing to do here + super(); } /** From cd4807263eec8af58126ca0f321c6d84bcd23230 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Mon, 9 May 2016 12:35:06 +0200 Subject: [PATCH 070/157] Add interface --- src/models/databaseModel.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 6626a21..a341df1 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -1,5 +1,12 @@ -import * as moongose from "mongoose"; +import * as mongoose from "mongoose"; import Model from "./model"; + +interface DatabaseDocument extends mongoose.Document { + name : string, + idOwner : string; +} + + /** * DatabaseModel manage all connections to MongoDB companies databases. * Implements model and schema of MongooseJS. From a57a444b9535ef7542645063c567fba6f4dd0aae Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Mon, 9 May 2016 13:23:04 +0200 Subject: [PATCH 071/157] First draft --- src/models/databaseModel.ts | 64 +++++++++++++++++++++++++++++++++---- 1 file changed, 58 insertions(+), 6 deletions(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index a341df1..d2a6de1 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -1,8 +1,29 @@ -import * as mongoose from "mongoose"; +import * as m from "mongoose"; import Model from "./model"; -interface DatabaseDocument extends mongoose.Document { + +/** + * DatabaseModel is a interface that represent the document on MongoDB. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Polonio | Create interface| 09/05/2016 | + * + * @author Davide Polonio + * @copyright MIT + * + * + */ + +export interface DatabaseDocument extends m.Document { + /** + * @description Represent the company name. + */ name : string, + /** + * @description Represent the owner id. + */ idOwner : string; } @@ -25,7 +46,22 @@ interface DatabaseDocument extends mongoose.Document { * */ -class DatabaseModel extends Model { +export class DatabaseModel extends Model { + + /** + * Schema of the collection in the MongoDB database. It follows the + * definition declared in the DSLDocument interface. + */ + private static schema : m.Schema = new m.Schema({ + name: String, + idOwner: String + }); + + /** + * Model's dsl + */ + private model : m.Model; + /** * @description Call the super constructor. @@ -35,7 +71,12 @@ class DatabaseModel extends Model { */ constructor () { - super(); + this.model = this.getConnection() + .getRawConnection() + .model( + "Database", + DatabaseModel.schema + ); } /** @@ -45,9 +86,20 @@ class DatabaseModel extends Model { * * @return // To choose */ - public getDatabase ( identifier : number ) : void { + public getDatabase ( identifier : number ) : m.Promise { - // TODO to implement + return this.model + /* + Get all relative DSL document where the user is show in the + permissions table + */ + .find({ + idOwner: identifier + }) + /* + Exec query + */ + .exec(); } } From 18273ad4052f52fd8ab4b64bce9f42fada6af2b4 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Mon, 9 May 2016 13:26:21 +0200 Subject: [PATCH 072/157] Add call on super class --- src/models/databaseModel.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index d2a6de1..c957e70 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -71,6 +71,8 @@ export class DatabaseModel extends Model { */ constructor () { + super(); + this.model = this.getConnection() .getRawConnection() .model( From ff46c075876db1ebe0c761dd10621286e2a0a169 Mon Sep 17 00:00:00 2001 From: korut94 Date: Mon, 9 May 2016 13:27:49 +0200 Subject: [PATCH 073/157] Use arrow function to store the this --- src/lib/dslChecker.ts | 57 ++++++++++++++++++++++++++++--------------- 1 file changed, 38 insertions(+), 19 deletions(-) diff --git a/src/lib/dslChecker.ts b/src/lib/dslChecker.ts index e932b6e..1c754d7 100644 --- a/src/lib/dslChecker.ts +++ b/src/lib/dslChecker.ts @@ -1,8 +1,3 @@ -/* -TODO: Remove assertion -TODO: Replace comment control with exception - */ - import Map from "./map" /** @@ -27,12 +22,36 @@ class DSLChecker { */ constructor() { this.flowControl = {}; // Initialize - this.flowControl["cell"] = this.checkLeaf; - this.flowControl["collection"] = this.checkCollection; - this.flowControl["dashboard"] = this.checkDashboard; - this.flowControl["document"] = this.checkDocument; - this.flowControl["index"] = this.checkIndex; - this.flowControl["leaf"] = this.checkLeaf; + + this.flowControl["cell"] = + (struct : Object, id : string) : boolean => { + return this.checkLeaf(struct, id); + }; + + this.flowControl["collection"] = + (struct : Object, id : string) : boolean => { + return this.checkCollection(struct, id); + } + + this.flowControl["dashboard"] = + (struct : Object, id : string) : boolean => { + return this.checkDashboard(struct, id); + } + + this.flowControl["document"] = + (struct : Object, id : string) : boolean => { + return this.checkDocument(struct, id); + } + + this.flowControl["index"] = + (struct : Object, id : string) : boolean => { + return this.checkIndex(struct, id); + } + + this.flowControl["leaf"] = + (struct : Object, id : string) : boolean => { + return this.checkLeaf(struct, id); + } } /** @@ -108,7 +127,7 @@ class DSLChecker { } // Extract the model of the collection - let collection : Object = DSLChecker.extractModel(data, id); + let collection : Object = this.extractModel(data, id); let actions : Array = collection["action"]; let index : string = collection["index"]; let document : string = collection["document"]; @@ -150,7 +169,7 @@ class DSLChecker { } // Extract the model of the dashboard - let dashboard : Object = DSLChecker.extractModel(data, id); + let dashboard : Object = this.extractModel(data, id); let rows : Array = dashboard["rows"]; if (rows === undefined) { @@ -164,7 +183,7 @@ class DSLChecker { rows.forEach((row : string) => { // Get type for the current row - let type : string = DSLChecker.extractType(data, row); + let type : string = this.extractType(data, row); correct = correct && this.flowControl[type](data, row); }); @@ -189,7 +208,7 @@ class DSLChecker { } // Extract the model of Document - let document : Object = DSLChecker.extractModel(data, id); + let document : Object = this.extractModel(data, id); let actions : Array = document["action"]; let rows : Array = document["row"]; @@ -226,7 +245,7 @@ class DSLChecker { } // Extract the model of Index - let index : Object = DSLChecker.extractModel(data, id); + let index : Object = this.extractModel(data, id); let columns : Array = index["column"]; if (columns === undefined) { @@ -259,7 +278,7 @@ class DSLChecker { Common model for any leaf. If no exception is throw, the leaf will be correct. */ - DSLChecker.extractModel(data, id); + this.extractModel(data, id); return true; } @@ -304,7 +323,7 @@ class DSLChecker { * The content of **pModel** attribute. * @throws {Error} */ - private static extractModel(data : Object, id : string) : Object { + private extractModel(data : Object, id : string) : Object { let model : Object = data[id]["pModel"]; if (model === undefined) { @@ -327,7 +346,7 @@ class DSLChecker { * The type of object * @throws {Error} */ - private static extractType(data : Object, id : string) : string { + private extractType(data : Object, id : string) : string { let struct : Object = data[id]; if (struct === undefined) { From bea39cca2e45dc98620c1384edc132a4ff2be4d3 Mon Sep 17 00:00:00 2001 From: korut94 Date: Mon, 9 May 2016 13:28:08 +0200 Subject: [PATCH 074/157] Insert test --- test/lib/dslCheckerTest.ts | 60 +++++++++++++++++++++++++++++++++++--- 1 file changed, 56 insertions(+), 4 deletions(-) diff --git a/test/lib/dslCheckerTest.ts b/test/lib/dslCheckerTest.ts index 0effa95..1184065 100644 --- a/test/lib/dslCheckerTest.ts +++ b/test/lib/dslCheckerTest.ts @@ -11,16 +11,68 @@ describe("DSLCheckTest", () => { toTest = new DSLChecker(); }); - // This function starts a single test - describe("#workWithCell", () => { - it ("should return true", () => { + /* + Test to show if DSLChecker check correctly a DSLStruct with inside + only the root elements (Cell,Collection,Dashboard,Document) + */ + describe("#workWithOnlyRoot", () => { + it("Cell", () => { Chai.expect(toTest.check({ root: "1", "1": { type: "cell", pModel: {} } - })).to.equal( true ); + })).to.equal(true); }); + + it("Collection", () => { + Chai.expect(toTest.check({ + root: "1", + "1": { + type: "collection", + pModel: { + action: ["2"], + index: "3", + document: "4" + } + }, + + "2": { + type: "action", + pModel: {} + }, + + "3": { + type: "index", + pModel: { + column: ["5"] + } + }, + + "4": { + type: "document", + pModel: { + action: ["6"], + row: ["7"] + } + }, + + "5": { + type: "column", + pModel: {} + }, + + "6": { + type: "action", + pModel: {} + }, + + "7": { + type: "row", + pModel: {} + } + })).to.equal(true); + }); }); }); \ No newline at end of file From 0fd22a65d981d4bbb61c6cb17b267118ae65bdf5 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Mon, 9 May 2016 13:30:34 +0200 Subject: [PATCH 075/157] Fix build errors --- src/models/databaseModel.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index c957e70..4b75605 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -88,7 +88,7 @@ export class DatabaseModel extends Model { * * @return // To choose */ - public getDatabase ( identifier : number ) : m.Promise { + public getDatabase ( identifier : number ) : m.Promise { return this.model /* From ddb65abd109545e0dd1468a87f23b24ac2173102 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Mon, 9 May 2016 15:13:55 +0200 Subject: [PATCH 076/157] Add mongo parameters from json file --- .gitignore | 1 + src/config/index.ts | 16 +++++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 4950956..c8facce 100644 --- a/.gitignore +++ b/.gitignore @@ -8,6 +8,7 @@ npm-debug.log **/tsconfig.json *.js.* +/src/config/mongoParameters.json *.js test/**/*.d.ts example/**/*.d.ts diff --git a/src/config/index.ts b/src/config/index.ts index 5b914cf..b73969e 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -3,6 +3,8 @@ import Configuration from "./configuration"; import DevConfiguration from "./devConfiguration"; import TestConfiguration from "./testConfiguration"; import ProdConfiguration from "./prodConfiguration"; +import * as fs from "fs"; +import {readFileSync} from "fs"; /** * @description Class used for get the necessary configuration. @@ -24,12 +26,16 @@ class ChooseConfiguration { */ public static getConfig() : Configuration { /** @todo parameters */ + let params : JSON = JSON.parse(readFileSync( + "mongoParameters.json", + "utf-8" + )); let connection : MongoConnection = new MongoConnection( - "admin", - "admin", - "ds013250.mlab.com", - 13250, - "mongocbtest" + params["username"], + params["password"], + params["host"], + params["port"], + params["name"] ); let serverSecret : string = "serverSecret"; let config : Configuration; From cfa6298b846e58c68b78edd671ad6ce1f75a9f14 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 9 May 2016 15:46:49 +0200 Subject: [PATCH 077/157] Compliance syntax with the linter See issue #19 --- src/lib/dslChecker.ts | 70 +++++++++++++++++------------ test/lib/dslCheckerTest.ts | 91 +++++++++++++++++++------------------- 2 files changed, 86 insertions(+), 75 deletions(-) diff --git a/src/lib/dslChecker.ts b/src/lib/dslChecker.ts index 1c754d7..27dac24 100644 --- a/src/lib/dslChecker.ts +++ b/src/lib/dslChecker.ts @@ -23,35 +23,47 @@ class DSLChecker { constructor() { this.flowControl = {}; // Initialize - this.flowControl["cell"] = - (struct : Object, id : string) : boolean => { - return this.checkLeaf(struct, id); - }; - - this.flowControl["collection"] = - (struct : Object, id : string) : boolean => { - return this.checkCollection(struct, id); - } - - this.flowControl["dashboard"] = - (struct : Object, id : string) : boolean => { - return this.checkDashboard(struct, id); - } - - this.flowControl["document"] = - (struct : Object, id : string) : boolean => { - return this.checkDocument(struct, id); - } - - this.flowControl["index"] = - (struct : Object, id : string) : boolean => { - return this.checkIndex(struct, id); - } - - this.flowControl["leaf"] = - (struct : Object, id : string) : boolean => { - return this.checkLeaf(struct, id); - } + this.flowControl["cell"] = ( + struct : Object, + id : string + ) : boolean => { + return this.checkLeaf(struct, id); + }; + + this.flowControl["collection"] = ( + struct : Object, + id : string + ) : boolean => { + return this.checkCollection(struct, id); + }; + + this.flowControl["dashboard"] = ( + struct : Object, + id : string + ) : boolean => { + return this.checkDashboard(struct, id); + }; + + this.flowControl["document"] = ( + struct : Object, + id : string + ) : boolean => { + return this.checkDocument(struct, id); + }; + + this.flowControl["index"] = ( + struct : Object, + id : string + ) : boolean => { + return this.checkIndex(struct, id); + }; + + this.flowControl["leaf"] = ( + struct : Object, + id : string + ) : boolean => { + return this.checkLeaf(struct, id); + }; } /** diff --git a/test/lib/dslCheckerTest.ts b/test/lib/dslCheckerTest.ts index 1184065..1aa5789 100644 --- a/test/lib/dslCheckerTest.ts +++ b/test/lib/dslCheckerTest.ts @@ -1,5 +1,4 @@ import DSLChecker from "../../src/lib/dslChecker" -import * as mocha from "mocha" import * as Chai from "chai" describe("DSLCheckTest", () => { @@ -26,53 +25,53 @@ describe("DSLCheckTest", () => { })).to.equal(true); }); - it("Collection", () => { - Chai.expect(toTest.check({ - root: "1", - "1": { - type: "collection", - pModel: { - action: ["2"], - index: "3", - document: "4" - } - }, + it("Collection", () => { + Chai.expect(toTest.check({ + root: "1", + "1": { + type: "collection", + pModel: { + action: ["2"], + index: "3", + document: "4" + } + }, + + "2": { + type: "action", + pModel: {} + }, + + "3": { + type: "index", + pModel: { + column: ["5"] + } + }, - "2": { - type: "action", - pModel: {} - }, + "4": { + type: "document", + pModel: { + action: ["6"], + row: ["7"] + } + }, - "3": { - type: "index", - pModel: { - column: ["5"] - } - }, + "5": { + type: "column", + pModel: {} + }, - "4": { - type: "document", - pModel: { - action: ["6"], - row: ["7"] - } - }, - - "5": { - type: "column", - pModel: {} - }, + "6": { + type: "action", + pModel: {} + }, - "6": { - type: "action", - pModel: {} - }, - - "7": { - type: "row", - pModel: {} - } - })).to.equal(true); - }); + "7": { + type: "row", + pModel: {} + } + })).to.equal(true); + }); }); -}); \ No newline at end of file +}); From 27de9faadbfb5095288e3168a2322ee5c852481f Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 10 May 2016 09:10:59 +0200 Subject: [PATCH 078/157] Write getDatabase. Add notes for tests --- src/models/databaseModel.ts | 10 ++++++---- test/models/databaseModelTest.ts | 8 ++++++++ 2 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 4b75605..ced7aed 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -50,7 +50,7 @@ export class DatabaseModel extends Model { /** * Schema of the collection in the MongoDB database. It follows the - * definition declared in the DSLDocument interface. + * definition declared in the DatabaseDocument interface. */ private static schema : m.Schema = new m.Schema({ name: String, @@ -58,13 +58,15 @@ export class DatabaseModel extends Model { }); /** - * Model's dsl + * Model's Database */ private model : m.Model; /** - * @description Call the super constructor. + * @description + *

This constructor calls his super constructor. After it gets the + * database connection and puts it in model.

* * @return {DatabaseModel} * This @@ -86,7 +88,7 @@ export class DatabaseModel extends Model { * * @param identifier * - * @return // To choose + * @return {m.Promise} */ public getDatabase ( identifier : number ) : m.Promise { diff --git a/test/models/databaseModelTest.ts b/test/models/databaseModelTest.ts index 195d2f8..24cfb24 100644 --- a/test/models/databaseModelTest.ts +++ b/test/models/databaseModelTest.ts @@ -19,6 +19,14 @@ import * as Chai from "chai"; */ describe("DatabaseModel", () => { + + /* + * //TODO + * Things to test: + * 1 - Return a list of databases of a company (getDatabase) + * 2 - Try to get a list of databases of a company da doesn't + * exist (getDatabase) + */ /* let toTest:someThing; // Name of the object to test From b3343bdc58e1898de40dfaa18efa40a9099a67b8 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 10 May 2016 09:41:13 +0200 Subject: [PATCH 079/157] Add method createDb. Add on the TODO list new tests to do. --- src/models/databaseModel.ts | 24 ++++++++++++++++++++---- test/models/databaseModelTest.ts | 1 + 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index ced7aed..4eb48fa 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -86,7 +86,7 @@ export class DatabaseModel extends Model { /** * @description Return a database from the identifier * - * @param identifier + * @param identifier {number} * * @return {m.Promise} */ @@ -94,17 +94,33 @@ export class DatabaseModel extends Model { return this.model /* - Get all relative DSL document where the user is show in the - permissions table + * Get all relative Database document of a company */ .find({ idOwner: identifier }) /* - Exec query + * Exec query */ .exec(); } + + /** + * @description + *

Add a database to the model. You need a DatabaseDocument. + * This class create a local copy and insert the Database name and the + * owner id.

+ * + * @param db {DatabaseDocument} + */ + public createDb ( db : DatabaseDocument ) : void { + + let copy : DatabaseDocument = new this.model({ + name: db.name, + idOwner: db.idOwner + }); + copy.save(); + } } export default DatabaseModel; diff --git a/test/models/databaseModelTest.ts b/test/models/databaseModelTest.ts index 24cfb24..133fbb2 100644 --- a/test/models/databaseModelTest.ts +++ b/test/models/databaseModelTest.ts @@ -26,6 +26,7 @@ describe("DatabaseModel", () => { * 1 - Return a list of databases of a company (getDatabase) * 2 - Try to get a list of databases of a company da doesn't * exist (getDatabase) + * 3 - Add a database to a company. */ /* From 314ce947cf578e4dd792de0e9cfe8e506ee74b18 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 10:08:51 +0200 Subject: [PATCH 080/157] "no-string-literal" and "no-any" set to false --- tslint.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tslint.json b/tslint.json index 06aca6e..418dd61 100644 --- a/tslint.json +++ b/tslint.json @@ -6,7 +6,7 @@ "public-before-private", "variables-before-functions" ], - "no-any": true, + "no-any": false, "no-inferrable-types": false, "no-internal-module": true, "no-var-requires": true, @@ -44,7 +44,7 @@ "no-eval": true, "no-null-keyword": true, "no-shadowed-variable": false, - "no-string-literal": true, + "no-string-literal": false, "no-switch-case-fall-through": true, "no-unreachable": true, "no-unused-expression": true, From ebe73dd3f19e33a6099bde96cfefe8baa5ef04b9 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 10 May 2016 10:17:22 +0200 Subject: [PATCH 081/157] Add new methods and new todos --- src/models/databaseModel.ts | 90 +++++++++++++++++++++++++++----- test/models/databaseModelTest.ts | 6 ++- 2 files changed, 83 insertions(+), 13 deletions(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 4eb48fa..f31130b 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -24,7 +24,11 @@ export interface DatabaseDocument extends m.Document { /** * @description Represent the owner id. */ - idOwner : string; + idOwner : string, + /** + * @description Represent the database id. + */ + idDatabase: string; } @@ -54,7 +58,8 @@ export class DatabaseModel extends Model { */ private static schema : m.Schema = new m.Schema({ name: String, - idOwner: String + idOwner: String, + idDatabase: String }); /** @@ -84,13 +89,13 @@ export class DatabaseModel extends Model { } /** - * @description Return a database from the identifier + * @description Return a list of databases from a company identifier * - * @param identifier {number} + * @param identifier {string} The company identifier * * @return {m.Promise} */ - public getDatabase ( identifier : number ) : m.Promise { + public getDatabase ( identifier : string ) : m.Promise { return this.model /* @@ -105,21 +110,82 @@ export class DatabaseModel extends Model { .exec(); } + /** + * @description + *

Return a single database from the company identifier and from the id + * of the database

+ * + * @param idCompany {string} The id of the company + * @param idReqDatabase {string} The id of the request database + * + * @return {m.Promise} + */ + public getDatabaseById ( + idCompany : string, + idReqDatabase : string + ) : m.Promise { + + return this.model + /* + * Get a single database + */ + .findOne({ + idOwner: idCompany, + idDatabase: idReqDatabase + }) + .exec(); + } + /** * @description *

Add a database to the model. You need a DatabaseDocument. * This class create a local copy and insert the Database name and the * owner id.

* - * @param db {DatabaseDocument} + * @param db {DatabaseDocument} The document to create + * + * @return {m.Promise<(data : Result)>} */ - public createDb ( db : DatabaseDocument ) : void { - - let copy : DatabaseDocument = new this.model({ - name: db.name, - idOwner: db.idOwner + public createDb( db : DatabaseDocument) : + m.Promise<(data : Result) => void> { + return new m.Promise<(data : Result) => void>(( + reject : (err : Object) => void, // Object is better than any + resolve : (data : Result) => void + ) => { + let copy : DatabaseDocument = new this.model({ + name: db.name, + idOwner: db.idOwner + }); + + // Save Document + copy.save((err : Object, data : Result) => { + if (err !== undefined) { + reject(err); + } else { + resolve(data); + } + }); }); - copy.save(); + } + + /** + * @description This method update a database with a new DatabaseDocument + * + * @param idDb {string} The id of the database to update + * @param newInfo {DatabaseDocument} The new information to insert + * + * @returns {Promise} + */ + public updateDb ( + idDb : string, + newInfo : DatabaseDocument + ) : m.Promise { + + return this.model.update({idOwner: idDb}, { + name: newInfo.name, + idOwner: newInfo.idOwner, + idDatabase: newInfo.idDatabase + }).exec(); } } diff --git a/test/models/databaseModelTest.ts b/test/models/databaseModelTest.ts index 133fbb2..a574821 100644 --- a/test/models/databaseModelTest.ts +++ b/test/models/databaseModelTest.ts @@ -25,8 +25,12 @@ describe("DatabaseModel", () => { * Things to test: * 1 - Return a list of databases of a company (getDatabase) * 2 - Try to get a list of databases of a company da doesn't - * exist (getDatabase) + * exists (getDatabase) * 3 - Add a database to a company. + * 4 - Try to get a single database of a company + * 5 - Try to get a single database of a company tha doesn't exists + * 6 - Try to update a database + * 7 - Try to update a database da doesn't exists */ /* From 365d0a94dfb7c31bf2bc53e3f1a3ef35d31ef93f Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 10 May 2016 10:19:37 +0200 Subject: [PATCH 082/157] Fix lint issues --- src/models/databaseModel.ts | 2 +- test/models/databaseModelTest.ts | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index f31130b..1b92d79 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -28,7 +28,7 @@ export interface DatabaseDocument extends m.Document { /** * @description Represent the database id. */ - idDatabase: string; + idDatabase : string; } diff --git a/test/models/databaseModelTest.ts b/test/models/databaseModelTest.ts index a574821..2d31bfc 100644 --- a/test/models/databaseModelTest.ts +++ b/test/models/databaseModelTest.ts @@ -19,7 +19,6 @@ import * as Chai from "chai"; */ describe("DatabaseModel", () => { - /* * //TODO * Things to test: From 2cbfb96c910fd4b9c7c726b02fa460d031e4b2c6 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 10:33:09 +0200 Subject: [PATCH 083/157] Reset no-any to true --- test/{ => config}/devConfigurationTest.ts | 4 ++-- test/{ => config}/indexTest.ts | 2 +- test/{ => config}/mongoConnectionTest.ts | 2 +- test/{ => config}/prodConfigurationTest.ts | 4 ++-- test/{ => config}/testConfigurationTest.ts | 4 ++-- tslint.json | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) rename test/{ => config}/devConfigurationTest.ts (91%) rename test/{ => config}/indexTest.ts (95%) rename test/{ => config}/mongoConnectionTest.ts (95%) rename test/{ => config}/prodConfigurationTest.ts (91%) rename test/{ => config}/testConfigurationTest.ts (91%) diff --git a/test/devConfigurationTest.ts b/test/config/devConfigurationTest.ts similarity index 91% rename from test/devConfigurationTest.ts rename to test/config/devConfigurationTest.ts index a001d16..228e0e1 100644 --- a/test/devConfigurationTest.ts +++ b/test/config/devConfigurationTest.ts @@ -4,8 +4,8 @@ */ import * as Chai from "chai"; -import DevConfiguration from "../src/config/devConfiguration"; -import MongoConnection from "../src/config/mongoConnection"; +import DevConfiguration from "../../src/config/devConfiguration"; +import MongoConnection from "../../src/config/mongoConnection"; describe("DevConfigurationTest", () => { diff --git a/test/indexTest.ts b/test/config/indexTest.ts similarity index 95% rename from test/indexTest.ts rename to test/config/indexTest.ts index d2c9def..c344733 100644 --- a/test/indexTest.ts +++ b/test/config/indexTest.ts @@ -2,7 +2,7 @@ * This is a test for the ChooseConfiguration class. */ -import ChooseConfiguration from "../src/config/index"; +import ChooseConfiguration from "../../src/config/index"; import * as Chai from "chai"; // You need assertions. Trust me. describe("IndexTest", () => { diff --git a/test/mongoConnectionTest.ts b/test/config/mongoConnectionTest.ts similarity index 95% rename from test/mongoConnectionTest.ts rename to test/config/mongoConnectionTest.ts index 4ecb88a..01ff57f 100644 --- a/test/mongoConnectionTest.ts +++ b/test/config/mongoConnectionTest.ts @@ -3,7 +3,7 @@ * getter methods work correctly. */ -import MongoConnection from "../src/config/mongoConnection"; +import MongoConnection from "../../src/config/mongoConnection"; import * as Chai from "chai"; // You need assertions. Trust me. describe("MongoConnectionTest", () => { diff --git a/test/prodConfigurationTest.ts b/test/config/prodConfigurationTest.ts similarity index 91% rename from test/prodConfigurationTest.ts rename to test/config/prodConfigurationTest.ts index 1460041..34d9667 100644 --- a/test/prodConfigurationTest.ts +++ b/test/config/prodConfigurationTest.ts @@ -4,8 +4,8 @@ */ import * as Chai from "chai"; -import ProdConfiguration from "../src/config/prodConfiguration"; -import MongoConnection from "../src/config/mongoConnection"; +import ProdConfiguration from "../../src/config/prodConfiguration"; +import MongoConnection from "../../src/config/mongoConnection"; describe("ProdConfigurationTest", () => { diff --git a/test/testConfigurationTest.ts b/test/config/testConfigurationTest.ts similarity index 91% rename from test/testConfigurationTest.ts rename to test/config/testConfigurationTest.ts index 2241d0c..76f861c 100644 --- a/test/testConfigurationTest.ts +++ b/test/config/testConfigurationTest.ts @@ -4,8 +4,8 @@ */ import * as Chai from "chai"; -import TestConfiguration from "../src/config/testConfiguration"; -import MongoConnection from "../src/config/mongoConnection"; +import TestConfiguration from "../../src/config/testConfiguration"; +import MongoConnection from "../../src/config/mongoConnection"; describe("TestConfigurationTest", () => { diff --git a/tslint.json b/tslint.json index 418dd61..c1baeba 100644 --- a/tslint.json +++ b/tslint.json @@ -6,7 +6,7 @@ "public-before-private", "variables-before-functions" ], - "no-any": false, + "no-any": true, "no-inferrable-types": false, "no-internal-module": true, "no-var-requires": true, From 92d859492b9b482e3839b81c0479ec16f5f0fe36 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 10:33:57 +0200 Subject: [PATCH 084/157] Add external configuration support --- src/config/index.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/config/index.ts b/src/config/index.ts index b73969e..8a54dee 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -3,7 +3,6 @@ import Configuration from "./configuration"; import DevConfiguration from "./devConfiguration"; import TestConfiguration from "./testConfiguration"; import ProdConfiguration from "./prodConfiguration"; -import * as fs from "fs"; import {readFileSync} from "fs"; /** @@ -26,16 +25,16 @@ class ChooseConfiguration { */ public static getConfig() : Configuration { /** @todo parameters */ - let params : JSON = JSON.parse(readFileSync( - "mongoParameters.json", + let params : MongoConnection = JSON.parse(readFileSync( + "src/config/mongoParameters.json", "utf-8" )); let connection : MongoConnection = new MongoConnection( - params["username"], + params["user"], params["password"], params["host"], params["port"], - params["name"] + params["dbName"] ); let serverSecret : string = "serverSecret"; let config : Configuration; From 05a11f37ee7f1437298e536c7f7b70bad10a96e3 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 10:34:16 +0200 Subject: [PATCH 085/157] Add a test for check the correct file reading --- test/config/indexTest.ts | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/test/config/indexTest.ts b/test/config/indexTest.ts index c344733..a9fc787 100644 --- a/test/config/indexTest.ts +++ b/test/config/indexTest.ts @@ -4,6 +4,8 @@ import ChooseConfiguration from "../../src/config/index"; import * as Chai from "chai"; // You need assertions. Trust me. +import {readFileSync} from "fs"; +import MongoConnection from "../../src/config/mongoConnection"; describe("IndexTest", () => { @@ -38,4 +40,21 @@ describe("IndexTest", () => { equal("production"); }); }); + + describe("#correctParameters", () => { + it ("Should read the right parameters", () => { + let params : MongoConnection = JSON.parse(readFileSync( + "src/config/mongoParameters.json", + "utf-8" + )); + let connection : MongoConnection = ChooseConfiguration.getConfig(). + getMongoConnection(); + Chai.expect(connection.getUser()).to.equal(params["user"]); + Chai.expect(connection.getPassword()).to.equal(params["password"]); + Chai.expect(connection.getHost()).to.equal(params["host"]); + Chai.expect(connection.getDatabasePort()).to.equal(params["port"]); + Chai.expect(connection.getDatabaseName()).to. + equal(params["dbName"]); + }) + }) }); From 72be2c36f08a7a0a16b5b54c33fbf67c8a391dc7 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 10 May 2016 10:34:51 +0200 Subject: [PATCH 086/157] First draft of 'deleteDb' method --- src/models/databaseModel.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 1b92d79..c4fbb51 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -187,6 +187,18 @@ export class DatabaseModel extends Model { idDatabase: newInfo.idDatabase }).exec(); } + + + public deleteDb ( + idCompany : string, + idReqDatabase : string + ) : m.Promise { + + return this.model.remove({ + idOwner: idCompany, + idDatabase: idReqDatabase + }).exec(); + } } export default DatabaseModel; From 2b5de8de9ca8d66cb110fc50beb0645bdbc9d054 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 10:35:18 +0200 Subject: [PATCH 087/157] Update getConfig description --- src/config/index.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/config/index.ts b/src/config/index.ts index 8a54dee..6a23547 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -21,6 +21,8 @@ class ChooseConfiguration { * @description Return the right configuration according to the Node.js * environment variable. It may be: 'development', 'test' or 'production'. * The default configuration is the 'production' one. + * The connection's parameters are read fro an external json file named + * mongoParameters.json. * @returns {Configuration} The configuration. */ public static getConfig() : Configuration { From 131bb03a5831cc554de2ab045611675c563f623b Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 10:40:21 +0200 Subject: [PATCH 088/157] Add mongoParameters.json. It is necessary to pass some tests --- .gitignore | 1 - src/config/mongoParameters.json | 7 +++++++ 2 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 src/config/mongoParameters.json diff --git a/.gitignore b/.gitignore index c8facce..4950956 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,6 @@ npm-debug.log **/tsconfig.json *.js.* -/src/config/mongoParameters.json *.js test/**/*.d.ts example/**/*.d.ts diff --git a/src/config/mongoParameters.json b/src/config/mongoParameters.json new file mode 100644 index 0000000..e025176 --- /dev/null +++ b/src/config/mongoParameters.json @@ -0,0 +1,7 @@ +{ + "user" : "admin", + "password" : "admin", + "host" : "ds013250.mlab.com", + "port" : 13250, + "dbName" : "mongocbtest" +} From 608baabe6dd845fa2f142c50ed582de1728b3e78 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 10:50:05 +0200 Subject: [PATCH 089/157] Remove @todo --- src/config/index.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/config/index.ts b/src/config/index.ts index 6a23547..7a79084 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -26,7 +26,6 @@ class ChooseConfiguration { * @returns {Configuration} The configuration. */ public static getConfig() : Configuration { - /** @todo parameters */ let params : MongoConnection = JSON.parse(readFileSync( "src/config/mongoParameters.json", "utf-8" From 4a64226d3d9c98fd996b3eafe8be51829e7e88b4 Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 10 May 2016 10:53:40 +0200 Subject: [PATCH 090/157] Write documentation --- src/models/databaseModel.ts | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index c4fbb51..98bd6ce 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -188,7 +188,13 @@ export class DatabaseModel extends Model { }).exec(); } - + /** + * @description This method delete the selected database + * + * @param idCompany {string} The id of the company + * @param idReqDatabase {string} The id of the database to delete + * @returns {Promise<{}>|Promise} + */ public deleteDb ( idCompany : string, idReqDatabase : string From 0dd184e918a355b9f62072795d477180e0ea87ef Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Tue, 10 May 2016 10:54:58 +0200 Subject: [PATCH 091/157] Add more tests to do --- test/models/databaseModelTest.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/test/models/databaseModelTest.ts b/test/models/databaseModelTest.ts index 2d31bfc..b9f480e 100644 --- a/test/models/databaseModelTest.ts +++ b/test/models/databaseModelTest.ts @@ -27,9 +27,11 @@ describe("DatabaseModel", () => { * exists (getDatabase) * 3 - Add a database to a company. * 4 - Try to get a single database of a company - * 5 - Try to get a single database of a company tha doesn't exists + * 5 - Try to get a single database of a company that doesn't exists * 6 - Try to update a database - * 7 - Try to update a database da doesn't exists + * 7 - Try to update a database that doesn't exists + * 8 - Remove a database + * 9 - Remove a database that doesn't exists */ /* From 1689cd755b423962da852ed57bba9645ebefc3d7 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 15:32:43 +0200 Subject: [PATCH 092/157] Working on tests --- test/models/companyModelTest.ts | 19 +++---------------- 1 file changed, 3 insertions(+), 16 deletions(-) diff --git a/test/models/companyModelTest.ts b/test/models/companyModelTest.ts index df593c6..00b0a12 100644 --- a/test/models/companyModelTest.ts +++ b/test/models/companyModelTest.ts @@ -17,19 +17,6 @@ import * as Chai from "chai" * */ -describe("DatabaseModel", () => { - - /* - let toTest:someThing; // Name of the object to test - // Call one of the many function that are in the Mocha framework - beforeEach(function ():void { - toTest = new someThing(); // You can do something before every test - }); - // This function starts a single test - describe("#nameOfWhatYouAreTesting", () => { - it("should ", () => { - // Your code here - Chai.expect(toTest.sayHello(name)).to.equal("Hello Derp"); - }); - */ -}); \ No newline at end of file +describe("CompanyModel", () => { +/* */ +}); From 8dd3bd3ec3efcf3fd9dba6a2784c351cc95723ac Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 15:35:02 +0200 Subject: [PATCH 093/157] Remove constructor parameters --- src/models/companyModel.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index 21f752a..008083b 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -31,10 +31,8 @@ export class CompanyModel extends Model { /** * @description Complete constructor. - * @param name The name of the Company - * @param idOwner The id of the Company's owner */ - constructor (name : string, idOwner : string) { + constructor () { super(); this.model = this.getConnection().getRawConnection(). model("Company", CompanyModel.schema); From 62926feb2cc0f84cc3aab94b175a2a1978b9d898 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 16:10:01 +0200 Subject: [PATCH 094/157] Start writing tests --- src/models/companyModel.ts | 5 ++++ test/models/companyModelTest.ts | 43 ++++++++++++++++++++++++++++++--- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index 008083b..15fac7c 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -95,6 +95,8 @@ export class CompanyModel extends Model { idOwner: company.idOwner }); + // @todo Must create the owner + // Save Document copy.save((err : Object, data : Result) => { if (err !== undefined) { @@ -106,3 +108,6 @@ export class CompanyModel extends Model { }); } } + +export default CompanyModel; + diff --git a/test/models/companyModelTest.ts b/test/models/companyModelTest.ts index 00b0a12..1a51ac1 100644 --- a/test/models/companyModelTest.ts +++ b/test/models/companyModelTest.ts @@ -1,5 +1,7 @@ -import * as CompanyModel from "../../src/models/companyModel"; -import * as Chai from "chai" +import CompanyModel from "../../src/models/companyModel"; +import CompanyDocument from "../../src/models/companyDocument"; +import * as Chai from "chai"; +import * as mongoose from "mongoose"; /** * CompanyModel implements the company business logic. It contains model and @@ -18,5 +20,40 @@ import * as Chai from "chai" */ describe("CompanyModel", () => { -/* */ + let toTest : CompanyModel = new CompanyModel(); + let testID : string = ""; + + describe("#Add", () => { + it("Should create a company and the owner", () => { + // TODO + }); + }); + + describe("#Find", () => { + it("Should find a company", () => { + toTest.getCompanyById(testID).then( + function(doc : CompanyDocument) : void { + Chai.expect(doc._id).to.equal(testID); + }); + }); + }); + + describe("#Update", () => { + /*toTest.update(testID, new CompanyDocument("AnotherName", + "")). + + then(function );*/ + }); + + describe("#Remove", () => { + it("Should remove a company given its id", () => { + let promise : mongoose.Promise = toTest.delete(testID); + promise.then(function(doc : CompanyDocument) : void { + toTest.getCompanyById(doc._id).then( + function(doc2 : CompanyDocument) : void { + Chai.expect(doc2).null; + }) + }); + }) + }); }); From 79a01d48b6e222c3a0f26697b1824305c9ca162c Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 16:25:36 +0200 Subject: [PATCH 095/157] Add getCompanies method --- src/models/companyModel.ts | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index 15fac7c..32553b6 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -107,6 +107,15 @@ export class CompanyModel extends Model { }); }); } + + /** + * @description Return a list of all the MaaS companies + * @return {Promise} A promise which contains the + * companies + */ + public getCompany () : Promise { + return this.model.find({}).exec(); + } } export default CompanyModel; From 92b0ae2b048a67970194c02a5ca8139aaad42260 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 16:39:25 +0200 Subject: [PATCH 096/157] Add test for getCompanies --- src/models/companyModel.ts | 4 ++-- test/models/companyModelTest.ts | 11 ++++++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index 32553b6..a1a4f20 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -111,9 +111,9 @@ export class CompanyModel extends Model { /** * @description Return a list of all the MaaS companies * @return {Promise} A promise which contains the - * companies + * companies. */ - public getCompany () : Promise { + public getCompanies () : Promise { return this.model.find({}).exec(); } } diff --git a/test/models/companyModelTest.ts b/test/models/companyModelTest.ts index 1a51ac1..96de67a 100644 --- a/test/models/companyModelTest.ts +++ b/test/models/companyModelTest.ts @@ -21,7 +21,8 @@ import * as mongoose from "mongoose"; describe("CompanyModel", () => { let toTest : CompanyModel = new CompanyModel(); - let testID : string = ""; + let testID : string = ""; + let anotherTestID : string = ""; describe("#Add", () => { it("Should create a company and the owner", () => { @@ -36,6 +37,14 @@ describe("CompanyModel", () => { Chai.expect(doc._id).to.equal(testID); }); }); + + it("Should find all companies", () => { + toTest.getCompanies().then( + function(docs : CompanyDocument[]) : void { + Chai.expect(docs[0]._id).to.equal(testID); + Chai.expect(docs[1]._id).to.equal(anotherTestID); + }) + }) }); describe("#Update", () => { From bb2522985216aa43821a40e72c09be7b8118fc2d Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Tue, 10 May 2016 16:56:01 +0200 Subject: [PATCH 097/157] Add some routes --- src/routes/companyRouter.ts | 75 ++++++++++++++++++++++++++++++++++++- 1 file changed, 74 insertions(+), 1 deletion(-) diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index cd6310a..feaf251 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -1,3 +1,5 @@ +import CompanyModel from "../models/companyModel"; +import CompanyDocument from "../models/companyDocument"; import * as express from "express"; import * as promise from "es6-promise"; @@ -55,7 +57,76 @@ class CompanyRouter { * If > MEMBER I query the database. * * // If something goes wrong, call next() - * // next(/*new Error("description")*/); + * // next(/*new Error("description"));*/ + let model : CompanyModel = new CompanyModel(); + model.getCompany(req.company_id).then( + function (doc : CompanyDocument) : void { + if (doc != undefined) { + res.json({ + "code" : 200, + "message" : "Success", + "data" : doc + }); + } else { + res.json({ + "code" : 404, + "message" : "Company not found. Please try" + + " with a different ID. If this error persist" + + " please contact the owner of your company" + }); + } + } + ) + }); + + this.routerRef.put("/api/companies/:company_id", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + let model : CompanyModel = new CompanyModel(); + model.update(req.company_id, + new CompanyDocument(req.body.name, req.body.ownerId)).then( + function (doc : CompanyDocument) : void { + /* */ + } + ) + }); + + this.routerRef.delete("/api/companies/:company_id", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + let model : CompanyModel = new CompanyModel(); + model.delete(req.company_id).then( + function (doc : CompanyDocument) : void { + /* */ + } + ) + }); + + this.routerRef.put("/api/admin/companies", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + let model : CompanyModel = new CompanyModel(); + model.getCompanies().then( + function (docs : CompanyDocument) : void { + if (docs != undefined) { + res.json({ + "code" : 200, + "message" : "Success", + "data" : docs + }); + } else { + res.json({ + "code" : 404, + "message" : "Company not found. Please try" + + " with a different ID. If this error persist" + + " please contact the owner of your company" + }); + } + } + ) }); } @@ -69,3 +140,5 @@ class CompanyRouter { return this.routerRef; } } + +export default CompanyRouter; From 0f29c75ea0f7b041f44b2627a4255fd461c32494 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Tue, 10 May 2016 18:43:01 +0200 Subject: [PATCH 098/157] Use onReject and onFulfill to resolve the promise See issue #4 --- src/models/dslModel.ts | 61 +++++++++++++++++++++---------------- test/models/dslModelTest.ts | 33 ++++++++++++++++++++ 2 files changed, 67 insertions(+), 27 deletions(-) create mode 100644 test/models/dslModelTest.ts diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index 0e953c7..bb12dbc 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -1,7 +1,11 @@ import * as mongoose from "mongoose"; -import Model from "./model.ts"; +import Model from "./model"; type Promise = mongoose.Promise; +type DSLSchema = { + permission: [{user: String, read: Boolean, exec: Boolean}], + content: String +}; /** * Define the form of a permission of a user on the DSL. @@ -106,9 +110,12 @@ export class DSLModel extends Model { * This. */ constructor() { - this.model = this.getConnection().model( - "DSL", - DSLModel.schema + super(); + + this.model = + this.getConnection().getRawConnection().model( + "DSL", + DSLModel.schema ); } @@ -177,30 +184,30 @@ export class DSLModel extends Model { * template param *Result* defines the param type when the promise * has resolved. */ - public add(dsl : DSLDocument) : - Promise<(data : Result) => void> { - return new mongoose.Promise<(data : Result) => void>(( - reject : (err : Object) => void, // Object is better than any - resolve : (data : Result) => void - ) => { - /* - Create an other document within the value of param dsl. - In this way, there isn't any problem with the real content of dsl. - */ - let doc : DSLDocument = new this.model({ - permission: dsl.permission, - content: dsl.content - }); - - // Save dsl - doc.save((err : Object, data : Result) => { - if (err !== undefined) { - reject(err); - } else { - resolve(data); - } - }); + public add(dsl : DSLSchema) : Promise { + let promise : Promise = new mongoose.Promise(); + + /* + Create an other document within the value of param dsl. + In this way, there isn't any problem with the real content of dsl. + */ + let doc : DSLDocument = new this.model({ + permission: dsl.permission, + content: dsl.content + }); + + // Save dsl + doc.save((err : Object, data : Result) => { + console.log("Mai"); + + if (err !== undefined) { + promise.reject(err); + } else { + promise.fulfill(data); + } }); + + return promise; } /** diff --git a/test/models/dslModelTest.ts b/test/models/dslModelTest.ts new file mode 100644 index 0000000..45d4a6b --- /dev/null +++ b/test/models/dslModelTest.ts @@ -0,0 +1,33 @@ +import * as Chai from "chai" +import * as mongoose from "mongoose" +import * as model from "../../src/models/dslModel" + +describe("DSLModel", () => { + let dsl : model.DSLModel; + + beforeEach(() => { + dsl = new model.DSLModel(); + }); + + describe("#loadADSLOnDatabase", () => { + it("should exec the callback", () => { + dsl.add({ + permission: [{user: "bo", read: true, exec: true}], + content: "this is unsafe" + }); + + let promise : mongoose.Promise<(data : Object) => void> = + dsl.add({ + permission: [{user: "bo", read: true, exec: true}], + content: "this is unsafe" + }); + + promise.onFulfill((data : Object) => { + console.log("Hello world!"); + + }).onReject((error : Object) => { + console.log("Errore"); + }); + }); + }); +}); From 720c0b8cca031938613d8d71a7e31a8bc1c01421 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Tue, 10 May 2016 18:51:02 +0200 Subject: [PATCH 099/157] Remove useless methedo See issue #4 --- test/models/dslModelTest.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/test/models/dslModelTest.ts b/test/models/dslModelTest.ts index 45d4a6b..430fc82 100644 --- a/test/models/dslModelTest.ts +++ b/test/models/dslModelTest.ts @@ -11,11 +11,6 @@ describe("DSLModel", () => { describe("#loadADSLOnDatabase", () => { it("should exec the callback", () => { - dsl.add({ - permission: [{user: "bo", read: true, exec: true}], - content: "this is unsafe" - }); - let promise : mongoose.Promise<(data : Object) => void> = dsl.add({ permission: [{user: "bo", read: true, exec: true}], From b299abd4239f4379d8a7faaa744218f1e1ad6de4 Mon Sep 17 00:00:00 2001 From: EmanueleC Date: Tue, 10 May 2016 19:06:52 +0200 Subject: [PATCH 100/157] Create class DSLRouter (to be implemented) --- package.json | 9 ++-- src/routes/dslRouter.ts | 94 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 99 insertions(+), 4 deletions(-) create mode 100644 src/routes/dslRouter.ts diff --git a/package.json b/package.json index 21c6c3d..64e3e82 100644 --- a/package.json +++ b/package.json @@ -19,7 +19,7 @@ "test": "rimraf ./{src,test}/**/*.d.ts && mocha ./test/**/*.js", "lint": "tslint ./{src,test}/**/*.ts", "typings": "typings install", - "start": "node ./dist/maas.js", + "start": "node ./dist/wwwrtt.js", "postinstall": "npm run burstmake && npm run typings" }, "engines": { @@ -40,7 +40,8 @@ "author": "BugBusters bugbusterswe@gmail.com", "license": "MIT", "dependencies": { - "express": "^4.13.1" + "express": "^4.13.1", + "promise": "^7.1.1" }, "devDependencies": { "apidoc": "^0.15.1", @@ -50,8 +51,8 @@ "mocha": "^2.4.5", "rimraf": "^2.5.2", "tslint": "^3.5.0", - "typedoc": "^0.3.12", + "typedoc": "latest", "typescript": "^1.8.7", - "typings": "^0.7.9" + "typings": "latest" } } diff --git a/src/routes/dslRouter.ts b/src/routes/dslRouter.ts new file mode 100644 index 0000000..bdf8fa6 --- /dev/null +++ b/src/routes/dslRouter.ts @@ -0,0 +1,94 @@ +import * as express from "express"; + +/** + * This class contains endpoint definition about companies. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | + * + * @author Emanuele Carraro + * @license MIT + * + */ + +export default class DSLRouter { + + private routerRef : express.Router; + + constructor() { + this.routerRef = express.Router(); + this.createGetRouter(); + } + + /** + * @description Return the router + * + * @returns {express.Router} + */ + public getRouter() : express.Router { + return this.routerRef; + } + + private createGetRouter () : void { + + this.routerRef.get("/api/companies/:company_id/DSLs", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + // GetDSL + // To be implemented + }); + + this.routerRef.get("/api/companies/:company_id/DSLs/:dsl_id", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + // GetDSLbyId + // To be implemented + }); + + this.routerRef.post("/api/companies/:company_id/DSLs", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + // Create(dsl) + // To be implemented + }); + + this.routerRef.put("/api/companies/:company_id/DSLs/:dsl_id", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + // Create(dsl) + // To be implemented + }); + + this.routerRef.delete("/api/companies/:company_id/DSLs/:dsl_id", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + // Delete() + // To be implemented + }); + + this.routerRef.get("/api/companies/:company_id/" + + "users/:user_id/dashboard", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + // GetDashboard(user) + // To be implemented + }); + + this.routerRef.get("/api/companies/:company_id/DSLs/:dsl_id/execute", + (req : express.Request, + res : express.Response, + next : express.NextFunction) => { + // ExecuteDSL(id) + // To be implemented + }); + } + +} From b9e63f97d481967485e1c1facfd5e84ccf029085 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Tue, 10 May 2016 19:09:11 +0200 Subject: [PATCH 101/157] Remove log printer See issue #4 --- src/models/dslModel.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index bb12dbc..b42532b 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -198,8 +198,6 @@ export class DSLModel extends Model { // Save dsl doc.save((err : Object, data : Result) => { - console.log("Mai"); - if (err !== undefined) { promise.reject(err); } else { From 0f8cc27cb61f07705ee3ca75d54234cd907e3d44 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Tue, 10 May 2016 19:15:17 +0200 Subject: [PATCH 102/157] Correct syntax for the linter's rule See issue #4 --- src/models/dslModel.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index b42532b..f4742f6 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -3,8 +3,8 @@ import Model from "./model"; type Promise = mongoose.Promise; type DSLSchema = { - permission: [{user: String, read: Boolean, exec: Boolean}], - content: String + permission : [{user : String, read : Boolean, exec : Boolean}], + content : String }; /** From e563a663d95e499ccdc03c615722d530c7c7a2db Mon Sep 17 00:00:00 2001 From: EmanueleC Date: Tue, 10 May 2016 19:16:57 +0200 Subject: [PATCH 103/157] Add test file (to be implemented) --- test/routes/dslRouterTest.ts | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 test/routes/dslRouterTest.ts diff --git a/test/routes/dslRouterTest.ts b/test/routes/dslRouterTest.ts new file mode 100644 index 0000000..adff1aa --- /dev/null +++ b/test/routes/dslRouterTest.ts @@ -0,0 +1,32 @@ +import * as DSLRouter from "../../src/routes/dslRouter"; +import * as express from "express"; +import * as Chai from "chai"; + +/** + * This is the test for DatabaseRouter class + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | + * + * @author Emanuele Carraro + * @copyright MIT + * + */ +describe("DSLRouter", () => { + + /* nothing to test for now + let toTest : DSLRouter; + let dummyExpress : express.Express = express(); + beforeEach(function () : void { + toTest = new DSLRouter(dummyExpress); + }); + describe("#nameOfWhatYouAreTesting", () => { + it ("should ", () => { + // Your code here + }); + }); + */ + +}); From eb852b2e958ddbdb557ee5f980f521e80fb547ab Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Wed, 11 May 2016 11:25:49 +0200 Subject: [PATCH 104/157] Add Helmet --- package.json | 3 ++- typings.json | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index bf430e9..23872df 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,8 @@ "license": "MIT", "dependencies": { "body-parser": "^1.15.1", - "express": "^4.13.1" + "express": "^4.13.1", + "helmet": "^2.0.0" }, "devDependencies": { "apidoc": "^0.15.1", diff --git a/typings.json b/typings.json index c1eb762..d564040 100644 --- a/typings.json +++ b/typings.json @@ -4,6 +4,7 @@ "chai": "registry:dt/chai#3.4.0+20160317120654", "express": "registry:dt/express#4.0.0+20160317120654", "express-serve-static-core": "registry:dt/express-serve-static-core#0.0.0+20160322035842", + "helmet": "registry:dt/helmet#0.0.0+20160501161936", "mime": "registry:dt/mime#0.0.0+20160316155526", "mocha": "registry:dt/mocha#2.2.5+20160317120654", "node": "registry:dt/node#4.0.0+20160330064709", From fb3a21a92a6193dcf5309738c7aab90faf29c1f5 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Wed, 11 May 2016 11:26:18 +0200 Subject: [PATCH 105/157] Add helment and cross platform --- src/maas.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/maas.ts b/src/maas.ts index 961a728..b5e6b97 100644 --- a/src/maas.ts +++ b/src/maas.ts @@ -1,6 +1,7 @@ import * as express from "express"; import * as bodyParser from "body-parser"; import * as http from "http"; +import * as helmet from "helmet"; import ConfigurationChooser from "./config/configurationChooser"; import Configuration from "./config/configuration"; import * as routes from "./routes/routerFacade"; @@ -13,6 +14,18 @@ let configuration : Configuration = ConfigurationChooser.getConfig(); app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); +// Set helmet for security checks +app.use(helmet()); + +app.use(function (req : express.Request, + res : express.Response, + next : express.NextFunction) : void { + res.header("Access-Control-Allow-Origin", "*"); + res.header("Access-Control-Allow-Headers", + "Origin, X-Requested-With, Content-Type, Accept"); + next(); +}); + // Routes' require app.use("/api", routes); From 899cd068a2e8488b03bd59d0eda3e5b847bcd5d7 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Wed, 11 May 2016 17:57:54 +0200 Subject: [PATCH 106/157] Added methods to the abstract class and ctreated ModelInterface --- src/models/customModelInterface.ts | 14 +++ src/models/model.ts | 139 ++++++++++++++++++++++++++++- src/models/userModel.ts | 31 +++---- src/routes/routerFacade.ts | 13 +-- 4 files changed, 173 insertions(+), 24 deletions(-) create mode 100644 src/models/customModelInterface.ts diff --git a/src/models/customModelInterface.ts b/src/models/customModelInterface.ts new file mode 100644 index 0000000..938675c --- /dev/null +++ b/src/models/customModelInterface.ts @@ -0,0 +1,14 @@ +import * as mongoose from "mongoose"; +/** + * This is the base models class and contains some useful methods to perform + * basic operations with MongoDB. + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Luca Bianco | Created interface | 10/05/2016 | + * + * @author Luca Bianco + * @license MIT + */ + +export interface CustomModel extends mongoose.Document {} diff --git a/src/models/model.ts b/src/models/model.ts index 24ac96e..20266de 100644 --- a/src/models/model.ts +++ b/src/models/model.ts @@ -1,8 +1,6 @@ import MongooseConnection from "./mongooseConnection"; -import MongoConnection from "../config/mongoConnection"; import * as mongoose from "mongoose"; -import {connection} from "mongoose"; - +import {CustomModel} from "./customModelInterface" /** * This is the base models class and contains some useful methods to perform * basic operations with MongoDB. @@ -10,21 +8,37 @@ import {connection} from "mongoose"; * | Author | Action Performed | Data | * | --- | --- | --- | * | Matteo Di Pirro | Create class | 04/05/2016 | + * | Luca Bianco | Fixed methods | 10/05/2016 | * * @author Matteo Di Pirro * @license MIT */ + + abstract class Model { + + /** + * @description Model representing the data in mongoose + */ + protected model : mongoose.Model; + /** * @description Mongoose connection */ private connection : MongooseConnection; + /** + * @description Schema of the model + */ + private schema : mongoose.Schema; + /** * @description Complete constructor. */ - constructor () { + constructor() { this.connection = MongooseConnection.getInstance(); + this.schema = this.getSchema(); + this.model = this.getModel(); } /** @@ -34,6 +48,123 @@ abstract class Model { public getConnection() : MongooseConnection { return this.connection; } + + /** + * @description Creates a new document into the database + * @param jsonData{Object} is the object that contains the information to + * create the object + * @returns {Promise|Promise} with the error or the saved data + */ + public create(jsonData : Object) : Promise { + let concreteModel : mongoose.Document = new this.model(jsonData); + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + concreteModel.save((error : Object, data : Object) => { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + }); + } + + public update(_id : string, jsonData : Object) : Promise { + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + this.model.findOneAndUpdate( + {_id: _id}, + { + $set: jsonData, + $inc: {__v: 1} + }, + (error : Object, data : Object) => { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + }); + } + + /** + * @description remove the document specified by the id + * + * @param _id + * + * @returns {Promise|Promise} + */ + public remove(_id : string) : Promise { + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + this.model.findOneAndRemove( + {_id: _id}, + (error : Object, data : Object) => { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + }); + } + + /** + * @description get the document specified by the id + * + * @param _id id of the document to return + * + * @returns {Promise|Promise} + */ + public getOne(_id : string) : Promise { + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + this.model.findOne({_id: _id}, + (error : Object, data : Object) => { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + }) + } + + /** + * @description get all the documents for the model of the data + * + * @returns {Promise|Promise} + */ + public getAll() : Promise { + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + this.model.find({}, + (error : Object, data : Object) => { + if (error) { + reject(error); + } else { + resolve(data); + } + }) + }) + } + + /** + * @description Builds the schema of data using mongoose Schema. + * @returns {mongoose.Schema} the schema built + */ + protected abstract getSchema() : mongoose.Schema; + + /** + * @description Returns the mongoose model representing the data into the + * database + * @returns {mongoose.Model} the model to use to manage data into the + * database + */ + protected abstract getModel() : mongoose.Model; + + } export default Model; diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 4bfd6b0..7606244 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -1,6 +1,6 @@ import * as mongoose from "mongoose"; import * as crypto from "crypto"; - +import * as Model from "./model"; /** * This is the model to represent users in MaaS. Extends model class. * @@ -18,7 +18,7 @@ class UserModel extends Model { private PWD_DEFAULT_ITERATIONS : number = 1000; private PWD_LENGHT : number = 50; - private USER_TYPES : Array = [ + private USER_TYPES : Array = [ "BASE", "ADMIN", "OWNER", @@ -30,7 +30,7 @@ class UserModel extends Model { } protected getSchema() : mongoose.Schema { - schema : mongoose.Schema = new mongoose.Schema({ + let schema : mongoose.Schema = new mongoose.Schema({ username: { type: String, required: true, @@ -72,25 +72,26 @@ class UserModel extends Model { } private setSchemaMethods(schema : mongoose.Schema) : void { - schema.methods = { - - authenticate: function (passwordText : string) : boolean { + schema.method( + "authenticate", + function (passwordText : string) : boolean { return this.hashPassword(passwordText) === this.hashed_pwd; - }, - - generateSalt: function () : string { + }); + schema.method( + "generateSalt", + function () : string { return crypto.randomBytes(16).toString("base64"); - }, - - hashPassword: function (password) : string { + }); + schema.method( + "hashPassword", + function (password : string) : string { return crypto .pbkdf2Sync(password, this.passwordSalt, this.passwordIterations, this.PWD_LENGTH) .toString("base64"); - } - }; + }); } protected getModel() : mongoose.model { @@ -100,7 +101,7 @@ class UserModel extends Model { public login(username: string, password: string) : Promise { return new Promise( function (resolve, reject) { - model.findOne( + this.model.findOne( {username: username}, function (error, user : mongoose.model) { if (error) { diff --git a/src/routes/routerFacade.ts b/src/routes/routerFacade.ts index ab34d58..76c7ab9 100644 --- a/src/routes/routerFacade.ts +++ b/src/routes/routerFacade.ts @@ -15,8 +15,11 @@ import UserRouter from "./userRouter"; import DatabaseRouter from "./databaseRouter"; import CompanyRouter from "./companyRouter"; -// Export the routes -export {default as DatabaseRouter} from "./databaseRouter"; -export {default as DSLRouter} from "./dslRouter"; -export {default as UserRouter} from "./userRouter"; -export {default as CompanyRouter} from "./companyRouter"; +let RouterFacade : express.Router = express.Router; + +RouterFacade.use(new DSLRouter().getRouter()); +RouterFacade.use(new UserRouter().getRouter()); +RouterFacade.use(new DatabaseRouter().getRouter()); +RouterFacade.use(new CompanyRouter().getRouter()); + +export default RouterFacade; From 25ab5ea5c4def83c4f1dfcc9745cef03e3829638 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Thu, 12 May 2016 13:22:01 +0200 Subject: [PATCH 107/157] Things changed --- src/models/companyModel.ts | 123 +-------------------- src/models/databaseModel.ts | 142 ++++-------------------- src/models/dslModel.ts | 144 ++----------------------- src/models/model.ts | 7 +- src/models/userModel.ts | 55 +++++----- src/routes/companyRouter.ts | 202 ++++++++++++++++------------------- src/routes/databaseRouter.ts | 94 ++++++++++++++-- src/routes/routerFacade.ts | 4 +- 8 files changed, 240 insertions(+), 531 deletions(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index a1a4f20..515d035 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -1,122 +1 @@ -import * as mongoose from "mongoose"; -import Model from "./model"; -import CompanyDocument from "./companyDocument"; - -type Promise = mongoose.Promise; - -/** - * CompanyModel implements the company business logic. It contains model and - * schema defined by MongooseJS. - * - * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Davide Rigoni | Create class | 03/05/2016 | - * - * @author Davide Rigoni - * @license MIT - * - */ -export class CompanyModel extends Model { - /** - * @description Company's schema - */ - private static schema : mongoose.Schema = - new mongoose.Schema({name: String, idOwner: String}); - - /** - * @description Company's model - */ - private model : mongoose.Model; - - /** - * @description Complete constructor. - */ - constructor () { - super(); - this.model = this.getConnection().getRawConnection(). - model("Company", CompanyModel.schema); - } - - /** - * @description Return the company's name and the id of the owner - * @param name The name of the company - * @return {Promise} - * The promise for the Company's document. - */ - public getCompanyById(companyId : string) : Promise { - return this.model.findById(companyId).exec(); - }; - - /** - * @description Update the data of the company - * @param id The id of the company to update - * @param company The new company's data - * @return {Promise} - * Promise to the returned document after the operation. To more - * information about the structure of document refer to the official - * documentation: [Update#Output - MongoDB](http://bit.ly/1Ygx5UW) - */ - public update(id : string, company : CompanyDocument) : Promise { - return this.model.update({_id : id}, { - name : company.name, - idOwner : company.idOwner - }).exec(); - }; - - /** - * Delete the company represented by the id - * @param id The id of the company to remove - * @returns {Promise} Promise to the null returned document. - * Define **only** the *onReject* function. - */ - public delete(id : string) : Promise { - return this.model.remove({_id : id}).exec(); - }; - - /** - * @description Create a new company - * @param name Company's name - * @param email Owner's email - * @param password Owner's password - * @returns {Promise} - * Promise of the request to save the document into the database. The - * template param *Result* defines the param type when the promise - * has resolved. - */ - public createCompany(company : CompanyDocument) : - Promise<(data : Result) => void> { - return new mongoose.Promise<(data : Result) => void>(( - reject : (err : Object) => void, // Object is better than any - resolve : (data : Result) => void - ) => { - let copy : CompanyDocument = new this.model({ - name : company.name, - idOwner: company.idOwner - }); - - // @todo Must create the owner - - // Save Document - copy.save((err : Object, data : Result) => { - if (err !== undefined) { - reject(err); - } else { - resolve(data); - } - }); - }); - } - - /** - * @description Return a list of all the MaaS companies - * @return {Promise} A promise which contains the - * companies. - */ - public getCompanies () : Promise { - return this.model.find({}).exec(); - } -} - -export default CompanyModel; - +import * as mongoose from "mongoose"; import Model from "./model"; import CompanyDocument from "./companyDocument"; type Promise = mongoose.Promise; /** * CompanyModel implements the company business logic. It contains model and * schema defined by MongooseJS. * * @history * | Author | Action Performed | Data | * | --- | --- | --- | * | Davide Rigoni | Create class | 03/05/2016 | * * @author Davide Rigoni * @license MIT * */ export class CompanyModel extends Model { constructor() { super(); } protected getSchema() : mongoose.Schema { return new mongoose.Schema({name: String, idOwner: String}); } protected getModel() : mongoose.Model { return mongoose.model("Company", this.getSchema()); } } export default CompanyModel; \ No newline at end of file diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 98bd6ce..c63edf6 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -6,9 +6,9 @@ import Model from "./model"; * DatabaseModel is a interface that represent the document on MongoDB. * * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Davide Polonio | Create interface| 09/05/2016 | + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Polonio | Create interface | 09/05/2016 | * * @author Davide Polonio * @copyright MIT @@ -38,7 +38,7 @@ export interface DatabaseDocument extends m.Document { * * This model represent a connection to a company. * - * + * * @history * | Author | Action Performed | Data | * | --- | --- | --- | @@ -69,141 +69,35 @@ export class DatabaseModel extends Model { /** - * @description + * @description *

This constructor calls his super constructor. After it gets the * database connection and puts it in model.

- * + * * @return {DatabaseModel} * This */ - constructor () { + constructor() { super(); this.model = this.getConnection() .getRawConnection() .model( - "Database", - DatabaseModel.schema - ); + "Database", + DatabaseModel.schema + ); } - /** - * @description Return a list of databases from a company identifier - * - * @param identifier {string} The company identifier - * - * @return {m.Promise} - */ - public getDatabase ( identifier : string ) : m.Promise { - - return this.model - /* - * Get all relative Database document of a company - */ - .find({ - idOwner: identifier - }) - /* - * Exec query - */ - .exec(); - } - - /** - * @description - *

Return a single database from the company identifier and from the id - * of the database

- * - * @param idCompany {string} The id of the company - * @param idReqDatabase {string} The id of the request database - * - * @return {m.Promise} - */ - public getDatabaseById ( - idCompany : string, - idReqDatabase : string - ) : m.Promise { - - return this.model - /* - * Get a single database - */ - .findOne({ - idOwner: idCompany, - idDatabase: idReqDatabase - }) - .exec(); - } - - /** - * @description - *

Add a database to the model. You need a DatabaseDocument. - * This class create a local copy and insert the Database name and the - * owner id.

- * - * @param db {DatabaseDocument} The document to create - * - * @return {m.Promise<(data : Result)>} - */ - public createDb( db : DatabaseDocument) : - m.Promise<(data : Result) => void> { - return new m.Promise<(data : Result) => void>(( - reject : (err : Object) => void, // Object is better than any - resolve : (data : Result) => void - ) => { - let copy : DatabaseDocument = new this.model({ - name: db.name, - idOwner: db.idOwner - }); - - // Save Document - copy.save((err : Object, data : Result) => { - if (err !== undefined) { - reject(err); - } else { - resolve(data); - } - }); + protected getSchema() : m.Schema { + return new m.Schema({ + name: String, + idOwner: String, + idDatabase: String }); } - - /** - * @description This method update a database with a new DatabaseDocument - * - * @param idDb {string} The id of the database to update - * @param newInfo {DatabaseDocument} The new information to insert - * - * @returns {Promise} - */ - public updateDb ( - idDb : string, - newInfo : DatabaseDocument - ) : m.Promise { - - return this.model.update({idOwner: idDb}, { - name: newInfo.name, - idOwner: newInfo.idOwner, - idDatabase: newInfo.idDatabase - }).exec(); - } - - /** - * @description This method delete the selected database - * - * @param idCompany {string} The id of the company - * @param idReqDatabase {string} The id of the database to delete - * @returns {Promise<{}>|Promise} - */ - public deleteDb ( - idCompany : string, - idReqDatabase : string - ) : m.Promise { - - return this.model.remove({ - idOwner: idCompany, - idDatabase: idReqDatabase - }).exec(); + + protected getModel() : m.Model { + return mongoose.model("Database", this.getSchema()); } } diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index f4742f6..83d3913 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -11,9 +11,9 @@ type DSLSchema = { * Define the form of a permission of a user on the DSL. * * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Andrea Mantovani | Create interface | 07/05/2016 | + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Andrea Mantovani | Create interface | 07/05/2016 | * * @author Andrea Mantovani * @license MIT @@ -90,19 +90,6 @@ export interface DSLDocument extends mongoose.Document { * @license MIT */ export class DSLModel extends Model { - /** - * Schema of the collection in the MongoDB database. It follows the - * definition declared in the DSLDocument interface. - */ - private static schema : mongoose.Schema = new mongoose.Schema({ - permission: [{user: String, read: Boolean, exec: Boolean}], - content: String - }); - - /** - * Model's dsl - */ - private model : mongoose.Model; /** * Default constructor. @@ -111,129 +98,16 @@ export class DSLModel extends Model { */ constructor() { super(); - - this.model = - this.getConnection().getRawConnection().model( - "DSL", - DSLModel.schema - ); } - /** - * Get the DLSs that the user have access it. - * @param user {string} - * Id user - * @return {Promise} - * The promise for the set of DSL documents with only the attribute - * content. - */ - public getAll(user : string) : Promise { - return this.model - /* - Get all relative DSL document where the user is show in the - permissions table - */ - .find({ - permission: { - $elemMatch: { // Necessary for multiple conditions - user: user, - read: true - } - } - }) - /* - Select only the code of the DSL - */ - .select("content") - /* - Exec query - */ - .exec(); - } - - /** - * Get the DSL with the id specified and the user is able to access - * @param user {string} - * Id of the user - * @param id {string} - * Id of the DSL - * @return {Promise} - * The promise for the DSL document with only the attribute content. - */ - public get(user : string, id : string) : Promise { - // Take the only one matching result - return this.model.findOne({ - _id: id, // Univocal key assigned by MongoDB - permission: { - $elemMatch: { - user: user, - read: true - } - } - }) - .select("content") - .exec(); - } - - /** - * Save DSLDocument in the database. - * @param dsl {DSLDocument} - * Any compliant object at the DSLDocument interface - * @returns {Promise} - * Promise of the request to save the document into the database. The - * template param *Result* defines the param type when the promise - * has resolved. - */ - public add(dsl : DSLSchema) : Promise { - let promise : Promise = new mongoose.Promise(); - - /* - Create an other document within the value of param dsl. - In this way, there isn't any problem with the real content of dsl. - */ - let doc : DSLDocument = new this.model({ - permission: dsl.permission, - content: dsl.content - }); - - // Save dsl - doc.save((err : Object, data : Result) => { - if (err !== undefined) { - promise.reject(err); - } else { - promise.fulfill(data); - } + protected getSchema() : mongoose.Schema { + return new mongoose.Schema({ + permission: [{user: String, read: Boolean, exec: Boolean}], + content: String }); - - return promise; } - /** - * Udpate the dsl'code with the id specified - * @param id {string} - * Id of the dsl - * @param content {string} - * Code to insert in the the dsl - * @return {Promise} - * Promise to the returned document after the operation. To more - * information about the structure of document refer to the official - * documentation: [Update#Output - MongoDB](http://bit.ly/1Ygx5UW) - */ - public update(id : string, content : string) : Promise { - // Update specified dsl and return the mongoose.Promise - return this.model.update({_id: id}, {content: content}).exec(); - } - - /** - * Delete the dsl with id specified. - * @param id {string} - * Id of the dsl - * @returns {Promise} - * Promise to the null returned document. Define **only** the - * *onReject* function. - */ - public delete(id : string) : Promise<{}> { - // Remove specified dsl and return the mongoose.Promise - return this.model.remove({_id: id}).exec(); + protected getModel() : mongoose.Model { + return mongoose.model("DSL", this.getSchema()); } } diff --git a/src/models/model.ts b/src/models/model.ts index 20266de..e58a12b 100644 --- a/src/models/model.ts +++ b/src/models/model.ts @@ -1,6 +1,7 @@ import MongooseConnection from "./mongooseConnection"; import * as mongoose from "mongoose"; -import {CustomModel} from "./customModelInterface" +import {CustomModel} from "./customModelInterface"; + /** * This is the base models class and contains some useful methods to perform * basic operations with MongoDB. @@ -130,7 +131,7 @@ abstract class Model { }); }) } - + /** * @description get all the documents for the model of the data * @@ -149,7 +150,7 @@ abstract class Model { }) }) } - + /** * @description Builds the schema of data using mongoose Schema. * @returns {mongoose.Schema} the schema built diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 7606244..43808e9 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -1,6 +1,8 @@ import * as mongoose from "mongoose"; import * as crypto from "crypto"; import * as Model from "./model"; +import {CustomModel} from "./customModelInterface"; + /** * This is the model to represent users in MaaS. Extends model class. * @@ -13,6 +15,8 @@ import * as Model from "./model"; * @license MIT */ +class ModelUser implements CustomModel { } + class UserModel extends Model { private PWD_DEFAULT_ITERATIONS : number = 1000; @@ -29,6 +33,31 @@ class UserModel extends Model { super(); } + public login(username : string, password : string) : Promise { + return new Promise(function (resolve, reject) { + this.model.findOne( + {username: username}, + function (error, user : mongoose.Model) : void { + if (error) { + reject(err); + } else { + if (!user.authenticate(password)) { + reject(new Error("Password non valida")); + } else { + delete user.passwordHashed; + delete user.passwordSalt; + delete user.passwordIterations; + resolve(user); + } + } + }) + }); + } + + protected getModel() : mongoose.Model { + return mongoose.model("User", this.getSchema()); + } + protected getSchema() : mongoose.Schema { let schema : mongoose.Schema = new mongoose.Schema({ username: { @@ -93,32 +122,6 @@ class UserModel extends Model { .toString("base64"); }); } - - protected getModel() : mongoose.model { - return mongoose.model ("User", this.getSchema()); - } - - - public login(username: string, password: string) : Promise { - return new Promise( function (resolve, reject) { - this.model.findOne( - {username: username}, - function (error, user : mongoose.model) { - if (error) { - reject(err); - } else { - if ( !user.authenticate(password)) { - reject( new Error("Password non valida")); - } else { - delete user.passwordHashed; - delete user.passwordSalt; - delete user.passwordIterations; - resolve(user); - } - } - }) - }); - } } export default UserModel; diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index feaf251..890d735 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -15,130 +15,108 @@ import * as promise from "es6-promise"; * @license MIT * */ -class CompanyRouter { +export default class CompanyRouter { - /** - * @description Ref for express router. - */ - private routerRef : express.Router; + private router : express.Router = express.Router(); + private companyModel : CompanyModel = new CompanyModel(); - /** - * @description Public constructor. It need a express router ref. - * - * @param expressRef {express.Router} - * Reference to the express application - * - * @return {CompanyRouter} - */ constructor() { - this.routerRef = express.Router(); - this.createGetRouter(); + this.router.get("/companies", this.getAllCompanies); + this.router.get("/companies/:company_id", this.getOneCompany); + this.router.post("/companies", this.createCompany); + this.router.put("/companies/:company_id", this.updateCompany); + this.router.delete("/companies/:company_id", this.remove); } - /** - * @description Create company router - */ - private createGetRouter () : void { - this.routerRef.get("/api/companies/:company_id", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - /* - * Here I use authentication checker and I need to check - * the user level. - * 1 - Call authentication checker as class .authenticate - * authenticationChecker.authenticate() -> returns a boolean - * - * If the boolean returned is `false` the user - * hasn't right permission and so I raise a error and - * I have to call next with the error. - * - * 2 - See 1 but with level checker. The minimum is MEMBER. - * If > MEMBER I query the database. - * - * // If something goes wrong, call next() - * // next(/*new Error("description"));*/ - let model : CompanyModel = new CompanyModel(); - model.getCompany(req.company_id).then( - function (doc : CompanyDocument) : void { - if (doc != undefined) { - res.json({ - "code" : 200, - "message" : "Success", - "data" : doc - }); - } else { - res.json({ - "code" : 404, - "message" : "Company not found. Please try" + - " with a different ID. If this error persist" + - " please contact the owner of your company" - }); - } - } - ) - }); + public getRouter() : express.Router { + return this.router; + } - this.routerRef.put("/api/companies/:company_id", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - let model : CompanyModel = new CompanyModel(); - model.update(req.company_id, - new CompanyDocument(req.body.name, req.body.ownerId)).then( - function (doc : CompanyDocument) : void { - /* */ - } - ) - }); + private getOneCompany(request : express.Request, result : express.Result) { + this.companyModel + .getOne(request.params.company_id) + .then(function (data : Object) : void { + result + .status(200) + .json(data); + }, function (error : Object) : void { + result + .status(404) + .json({ + done: false, + message: "Cannot find the request company" + }); + }) + } - this.routerRef.delete("/api/companies/:company_id", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - let model : CompanyModel = new CompanyModel(); - model.delete(req.company_id).then( - function (doc : CompanyDocument) : void { - /* */ - } - ) + private getAllCompanies(request : express.Request, result : express.Result) : void { + this.companyModel + .getAll() + .then(function (data : Object) : void { + result + .status(200) + .json(data); + }, function (error : Object) : void { + // Todo: che status? + result + .status(400) + .json({ + done: false, + message: "Cannot get companies data" + }) }); + } - this.routerRef.put("/api/admin/companies", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - let model : CompanyModel = new CompanyModel(); - model.getCompanies().then( - function (docs : CompanyDocument) : void { - if (docs != undefined) { - res.json({ - "code" : 200, - "message" : "Success", - "data" : docs - }); - } else { - res.json({ - "code" : 404, - "message" : "Company not found. Please try" + - " with a different ID. If this error persist" + - " please contact the owner of your company" - }); - } - } - ) + private createCompany(request : express.Request, result : express.Result) : void { + this.companyModel + .create(request.body) + .then(function (data : Object) : void { + result + .status(200) + .json(data); + }, function (error : Object) : void { + result + // Not acceptable + .status(406) + .json({ + done: false, + message: "Cannot save the company" + }) }); } + private updateCompany(request : express.Request, result : express.Result) : void { + this.companyModel + .update(request.params.company_id, request.body) + .then(function (data : Object) : void { + result + .status(200) + .json(data); + }, function (error : Object) { + result + .status(406) + .json({ + done: false, + message: "Cannot modify the data" + }); + }) + } - /** - * @description Return the express.Router param - * - * @returns {express.Router} - */ - public getRouter(): express.Router{ - return this.routerRef; + private remove(request : express.Request, result : express.Result) : void { + this.companyModel + .remove(request.params) + .then(function (data : Object) : void { + result + .status(200) + .json(data); + }, function (error : Object) { + result + // Todo set the status + .status(400) + .json({ + done: false, + message: "Impossible to remove the Company" + }); + }); } } - -export default CompanyRouter; diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index b9e4c94..a22dc84 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -1,12 +1,13 @@ import * as express from "express"; +import {DatabaseModel} from "../models/databaseModel"; /* import authentication checker */ /** * This class contains API definitions for companies database connections. - * + * * @history * | Author | Action Performed | Data | - * | --- | --- | --- | + * | --- | --- | --- | * | Davide Polonio | Create class | 03/05/2016 | * * @author Davide Polonio @@ -14,9 +15,86 @@ import * as express from "express"; * * * @todo Missing reference to the DatabaseModel object - * + * */ -class DatabaseRouter { + +export default class DatabaseRouter { + + private router : express +: + express +. + Router = express.Router(); + private databaseModel = new DatabaseModel(); + + constructor() { + + } + + public getRouter() : express.Router { + return this.router; + } + + private getOneDatabase(request : express.Request, result : express.Result) : void { + this.databaseModel + .getOne(reqest.params.database_id) + .then(function (data : Object) : void { + result + .status(200) + .json(data); + }, function (error : Object) : void { + result + .status(404) + .json({ + done: false, + message: "Cannot find the request database" + }); + }); + } + + private getAllDatabases(request : express.Request, result : express.Result) : void { + this.databaseModel + .getAll() + .then(function (data : Object) : void { + result + .status(200) + .json(data); + }, function (error : Object) : void { + result + .status(404) + .json({ + done: false, + message: "Cannot find the databases" + }); + }); + } + + + private updateDatabase(request : express.Request, response : express.Response) : void { + this.databaseModel + .update(request.params.database_id, request.body) + .then(function (data : Object) : void { + result + .status(200) + .json(data); + }, function (error : Object) : void { + result + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot modify the databases" + }); + }); + } + + private removeDatabase( request : express.Request, response : express.Resolve ) : void { + + } + +} + +class DatabaseRouterX { /** * @description Personal router for the class. The class load request here. @@ -25,7 +103,7 @@ class DatabaseRouter { /** * @description Public constructor. - * + * * @return {DatabaseRouter} */ constructor() { @@ -35,12 +113,12 @@ class DatabaseRouter { this.createGetRouter(); } - public getRouter () : express.Router { + public getRouter() : express.Router { return this.routerRef; } - private createGetRouter () : void { + private createGetRouter() : void { this.routerRef.get("/api/companies/:company_id/databases", (req : express.Request, @@ -73,7 +151,7 @@ class DatabaseRouter { // If something goes wrong, call next() next(/*new Error("description")*/); - }); + }); } } diff --git a/src/routes/routerFacade.ts b/src/routes/routerFacade.ts index 76c7ab9..1046dc3 100644 --- a/src/routes/routerFacade.ts +++ b/src/routes/routerFacade.ts @@ -1,3 +1,5 @@ +import * as express from "express"; + /** * Here we export all route files. You need only to import this file. * @history @@ -15,7 +17,7 @@ import UserRouter from "./userRouter"; import DatabaseRouter from "./databaseRouter"; import CompanyRouter from "./companyRouter"; -let RouterFacade : express.Router = express.Router; +let RouterFacade : express.Router = express.Router(); RouterFacade.use(new DSLRouter().getRouter()); RouterFacade.use(new UserRouter().getRouter()); From c635522cc9134247b5d4f3c0872c3e9dd22eddd3 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Thu, 12 May 2016 14:10:00 +0200 Subject: [PATCH 108/157] Things done on models --- src/models/databaseModel.ts | 17 +--- src/models/model.ts | 5 +- src/models/userModel.ts | 19 ++-- src/routes/companyRouter.ts | 6 +- src/routes/databaseRouter.ts | 114 ++++++++++-------------- src/routes/dslRouter.ts | 162 ++++++++++++++++++++++------------- src/routes/userRouter.ts | 138 +++++++++++++++++++++++++++++ 7 files changed, 306 insertions(+), 155 deletions(-) create mode 100644 src/routes/userRouter.ts diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index c63edf6..3da170e 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -51,22 +51,7 @@ export interface DatabaseDocument extends m.Document { */ export class DatabaseModel extends Model { - - /** - * Schema of the collection in the MongoDB database. It follows the - * definition declared in the DatabaseDocument interface. - */ - private static schema : m.Schema = new m.Schema({ - name: String, - idOwner: String, - idDatabase: String - }); - - /** - * Model's Database - */ - private model : m.Model; - + /** * @description diff --git a/src/models/model.ts b/src/models/model.ts index e58a12b..c9836d6 100644 --- a/src/models/model.ts +++ b/src/models/model.ts @@ -54,7 +54,7 @@ abstract class Model { * @description Creates a new document into the database * @param jsonData{Object} is the object that contains the information to * create the object - * @returns {Promise|Promise} with the error or the saved data + * @returns {Promise|Promise} with the error or the saved data */ public create(jsonData : Object) : Promise { let concreteModel : mongoose.Document = new this.model(jsonData); @@ -135,7 +135,7 @@ abstract class Model { /** * @description get all the documents for the model of the data * - * @returns {Promise|Promise} + * @returns {Promise|Promise} */ public getAll() : Promise { return new Promise((resolve : (data : Object) => void, @@ -165,7 +165,6 @@ abstract class Model { */ protected abstract getModel() : mongoose.Model; - } export default Model; diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 43808e9..723c4cd 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -1,7 +1,7 @@ import * as mongoose from "mongoose"; import * as crypto from "crypto"; -import * as Model from "./model"; -import {CustomModel} from "./customModelInterface"; +import Model from "./model"; +import CustomModel from "./customModelInterface"; /** * This is the model to represent users in MaaS. Extends model class. @@ -15,9 +15,16 @@ import {CustomModel} from "./customModelInterface"; * @license MIT */ -class ModelUser implements CustomModel { } +interface UserDocument extends CustomModel { + username : string, + passwordHashed : string, + passwordSalt : string, + passwordIterations : number, + level : string, + authenticate : any +} -class UserModel extends Model { +export default class UserModel extends Model { private PWD_DEFAULT_ITERATIONS : number = 1000; private PWD_LENGHT : number = 50; @@ -37,7 +44,7 @@ class UserModel extends Model { return new Promise(function (resolve, reject) { this.model.findOne( {username: username}, - function (error, user : mongoose.Model) : void { + function (error, user : mongoose.Model) : void { if (error) { reject(err); } else { @@ -123,5 +130,3 @@ class UserModel extends Model { }); } } - -export default UserModel; diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index 890d735..24c1b71 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -7,9 +7,9 @@ import * as promise from "es6-promise"; * This class contains endpoint definition about companies. * * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Davide Rigoni | Create class | 03/05/2016 | + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Rigoni | Create class | 03/05/2016 | * * @author Davide Rigoni * @license MIT diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index a22dc84..462e58f 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -20,15 +20,25 @@ import {DatabaseModel} from "../models/databaseModel"; export default class DatabaseRouter { - private router : express -: - express -. - Router = express.Router(); + private router : express.Router = express.Router(); private databaseModel = new DatabaseModel(); constructor() { - + this.router.get( + "/companies/:company_id/databases", + this.getAllDatabases); + this.router.get( + "/companies/:company_id/databases/:database_id", + this.getOneDatabase); + this.router.post( + "/companies/:company_id/databases", + this.createDatabase); + this.router.put( + "/companies/:company_id/database/:database_id", + this.updateDatabase); + this.router.delete( + "/companies/:company_id/database/:database_id", + this.removeDatabase); } public getRouter() : express.Router { @@ -87,71 +97,41 @@ export default class DatabaseRouter { }); }); } - - private removeDatabase( request : express.Request, response : express.Resolve ) : void { - - } - -} - -class DatabaseRouterX { - - /** - * @description Personal router for the class. The class load request here. - */ - private routerRef : express.Router; - - /** - * @description Public constructor. - * - * @return {DatabaseRouter} - */ - constructor() { - - this.routerRef = express.Router(); - - this.createGetRouter(); - } - public getRouter() : express.Router { - - return this.routerRef; + private removeDatabase(request : express.Request, response : express.Resolve) : void { + this.databaseModel + .remove(request.params.database_id) + .then(function (data : Object) : void { + result + .status(200) + .json(data); + }, function (error : Object) : void { + result + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot remove the databases" + }); + }); } - private createGetRouter() : void { - - this.routerRef.get("/api/companies/:company_id/databases", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - - let idUser : number = req.body[0]; - - /* - * Here I use authentication checker and I need to check - * the user level. - * 1 - Call authentication checker as class .authenticate - * authenticationChecker.authenticate() -> returns a boolean - * - * If the boolean returned is `false` the user - * hasn't right permission and so I raise a error and - * I have to call next with the error. - * - * 2 - See 1 but with level checker. The minimum is MEMBER. - * If > MEMBER I query the database. - */ - - /* Get the id of the database to query - * This need noImplicitAny: false - */ - let companyId : number = req.param[0]; - - // Query the database - - // If something goes wrong, call next() - next(/*new Error("description")*/); + private createDatabase(request : express.Request, response : express.Response) : void { + this.databaseModel + .create(request.body) + .then(function (data : Object) : void { + result + .status(200) + .json(data); + }, function (error : Object) : void { + result + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot create the databases" + }); }); } - } diff --git a/src/routes/dslRouter.ts b/src/routes/dslRouter.ts index bdf8fa6..9d6219d 100644 --- a/src/routes/dslRouter.ts +++ b/src/routes/dslRouter.ts @@ -1,4 +1,5 @@ import * as express from "express"; +import {DSLModel} from "../models/dslModel"; /** * This class contains endpoint definition about companies. @@ -12,83 +13,126 @@ import * as express from "express"; * @license MIT * */ +export default class DslRouter { -export default class DSLRouter { - - private routerRef : express.Router; + private router : express.Router = express.Router(); + private dslModel = new DSLModel(); constructor() { - this.routerRef = express.Router(); - this.createGetRouter(); + this.router.get( + "/companies/:company_id/dsl", + this.getAllDSL); + this.router.get( + "/companies/:company_id/dsl/:dsl_id", + this.getOneDSL); + this.router.post( + "/companies/:company_id/dsl", + this.createDSL); + this.router.put( + "/companies/:company_id/dsl/:dsl_id", + this.updateDSL); + this.router.delete( + "/companies/:company_id/dsl/:dsl_id", + this.removeDSL); } - /** - * @description Return the router - * - * @returns {express.Router} - */ public getRouter() : express.Router { - return this.routerRef; + return this.router; } - private createGetRouter () : void { - - this.routerRef.get("/api/companies/:company_id/DSLs", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - // GetDSL - // To be implemented + private getOneDSL(request : express.Request, + response : express.Response) : void { + this.dslModel + .getOne(request.params.dsl_id) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + .status(404) + .json({ + done: false, + message: "Cannot find the request dsl" + }); }); + } - this.routerRef.get("/api/companies/:company_id/DSLs/:dsl_id", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - // GetDSLbyId - // To be implemented + private getAllDSL(request : express.Request, + response : express.Response) : void { + this.dslModel + .getAll() + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + .status(404) + .json({ + done: false, + message: "Cannot find the dsl" + }); }); + } - this.routerRef.post("/api/companies/:company_id/DSLs", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - // Create(dsl) - // To be implemented - }); - this.routerRef.put("/api/companies/:company_id/DSLs/:dsl_id", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - // Create(dsl) - // To be implemented + private updateDSL(request : express.Request, + response : express.Response) : void { + this.dslModel + .update(request.params.database_id, request.body) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot modify the dsl" + }); }); + } - this.routerRef.delete("/api/companies/:company_id/DSLs/:dsl_id", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - // Delete() - // To be implemented + private removeDSL(request : express.Request, + response : express.Response) : void { + this.dslModel + .remove(request.params.database_id) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot remove the databases" + }); }); + } - this.routerRef.get("/api/companies/:company_id/" + - "users/:user_id/dashboard", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - // GetDashboard(user) - // To be implemented - }); - this.routerRef.get("/api/companies/:company_id/DSLs/:dsl_id/execute", - (req : express.Request, - res : express.Response, - next : express.NextFunction) => { - // ExecuteDSL(id) - // To be implemented + private createDSL(request : express.Request, + response : express.Response) : void { + this.dslModel + .create(request.body) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot create the databases" + }); }); } - } + diff --git a/src/routes/userRouter.ts b/src/routes/userRouter.ts new file mode 100644 index 0000000..11105eb --- /dev/null +++ b/src/routes/userRouter.ts @@ -0,0 +1,138 @@ +import * as express from "express"; +import {UserModel} from "../models/userModel"; + +/** + * This class contains endpoint definition about companies. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | + * + * @author Emanuele Carraro + * @license MIT + * + */ +export default class UserRouter { + + private router : express.Router = express.Router(); + private userModel = new UserModel(); + + constructor() { + this.router.get( + "/users", + this.getAllUsers); + this.router.get( + "/users/:user_id", + this.getOneUser); + this.router.post( + "/users/:user_id", + this.createUser); + this.router.put( + "/users/:user_id", + this.updateUser); + this.router.delete( + "/users/:user_id", + this.removeUser); + } + + public getRouter() : express.Router { + return this.router; + } + + private getOneUser(request : express.Request, + response : express.Response) : void { + this.userModel + .getOne(request.params.user_id) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + .status(404) + .json({ + done: false, + message: "Cannot find the request dsl" + }); + }); + } + + private getAllUsers(request : express.Request, + response : express.Response) : void { + this.userModel + .getAll() + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + .status(404) + .json({ + done: false, + message: "Cannot find the dsl" + }); + }); + } + + + private updateUser(request : express.Request, + response : express.Response) : void { + this.userModel + .update(request.params.user_id, request.body) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot modify the dsl" + }); + }); + } + + private removeUser(request : express.Request, + response : express.Response) : void { + this.userModel + .remove(request.params.user_id) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot remove the databases" + }); + }); + } + + + private createUser(request : express.Request, + response : express.Response) : void { + this.userModel + .create(request.body) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot create the databases" + }); + }); + } +} + From fd8cbc1e06f0d3df066f97a7c04c37de191f8f6a Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Thu, 12 May 2016 16:24:46 +0200 Subject: [PATCH 109/157] Worked on models --- src/models/companyModel.ts | 32 +++++++++++- src/models/customModelInterface.ts | 2 +- src/models/databaseModel.ts | 79 +++++++++++++++++++++++++++--- src/models/userModel.ts | 79 +++++++++++++++++++++++------- 4 files changed, 164 insertions(+), 28 deletions(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index 515d035..5f64f02 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -1 +1,31 @@ -import * as mongoose from "mongoose"; import Model from "./model"; import CompanyDocument from "./companyDocument"; type Promise = mongoose.Promise; /** * CompanyModel implements the company business logic. It contains model and * schema defined by MongooseJS. * * @history * | Author | Action Performed | Data | * | --- | --- | --- | * | Davide Rigoni | Create class | 03/05/2016 | * * @author Davide Rigoni * @license MIT * */ export class CompanyModel extends Model { constructor() { super(); } protected getSchema() : mongoose.Schema { return new mongoose.Schema({name: String, idOwner: String}); } protected getModel() : mongoose.Model { return mongoose.model("Company", this.getSchema()); } } export default CompanyModel; \ No newline at end of file +import * as mongoose from "mongoose"; +import Model from "./model"; +import CompanyDocument from "./companyDocument"; + +/** + * CompanyModel implements the company business logic. It contains model and + * schema defined by MongooseJS. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Rigoni | Create class | 03/05/2016 | + * + * @author Davide Rigoni + * @license MIT + * + */ +export default class CompanyModel extends Model { + + constructor() { + super(); + } + + protected getSchema() : mongoose.Schema { + return new mongoose.Schema({name: String, idOwner: String}); + } + + protected getModel() : mongoose.Model { + return mongoose.model("Company", this.getSchema()); + } +} diff --git a/src/models/customModelInterface.ts b/src/models/customModelInterface.ts index 938675c..c47d97f 100644 --- a/src/models/customModelInterface.ts +++ b/src/models/customModelInterface.ts @@ -11,4 +11,4 @@ import * as mongoose from "mongoose"; * @license MIT */ -export interface CustomModel extends mongoose.Document {} +export default interface CustomModel extends mongoose.Document { } diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 3da170e..2ee4f42 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -25,10 +25,14 @@ export interface DatabaseDocument extends m.Document { * @description Represent the owner id. */ idOwner : string, - /** - * @description Represent the database id. - */ - idDatabase : string; + + username : string, + + password : string, + + host : string, + + dbName : string } @@ -51,7 +55,6 @@ export interface DatabaseDocument extends m.Document { */ export class DatabaseModel extends Model { - /** * @description @@ -73,17 +76,79 @@ export class DatabaseModel extends Model { ); } + public create(jsonData : Object) : void { + this + .getCollections( + jsonData.port, + jsonData.host, + jsonData.username, + jsonData.password, + jsonData.dbName + ) + .then(function (collections : Array) { + jsonData.collections = collections; + super.create(jsonData); + }) + } + + public update(_id : string, jsonData : Object) : void { + this + .getCollections( + jsonData.port, + jsonData.host, + jsonData.username, + jsonData.password, + jsonData.dbName + ) + .then(function (collections : Array) { + jsonData.collections = collections; + super.update(_id, jsonData); + }) + } + protected getSchema() : m.Schema { return new m.Schema({ name: String, idOwner: String, - idDatabase: String + idDatabase: String, + collections: [] }); } - + protected getModel() : m.Model { return mongoose.model("Database", this.getSchema()); } + + private getCollections(port : string, host : string, + username : string, password : string, + dbName : string) : Array { + + let connectionString : string = + "mongodb://" + username + + ":" + password + + "@" + host + + ":" + port + + "/" + dbName; + + let mongooseTemporaryConnection : mongoose.Connection = + mongoose.connect(connectionString); + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + + // Richiedo i nomi delle connessioni + + mongooseTemporaryConnection.db.collectionNames( + function (err : Object, names : Array) : void { + if (err) { + reject(err); + } else { + resolve(names); + } + }); + }); + + + } } export default DatabaseModel; diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 723c4cd..3a28600 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -20,14 +20,13 @@ interface UserDocument extends CustomModel { passwordHashed : string, passwordSalt : string, passwordIterations : number, - level : string, - authenticate : any + level : string } export default class UserModel extends Model { - private PWD_DEFAULT_ITERATIONS : number = 1000; - private PWD_LENGHT : number = 50; + private static PWD_DEFAULT_ITERATIONS : number = 1000; + private static PWD_LENGHT : number = 50; private USER_TYPES : Array = [ "BASE", @@ -41,21 +40,62 @@ export default class UserModel extends Model { } public login(username : string, password : string) : Promise { - return new Promise(function (resolve, reject) { - this.model.findOne( - {username: username}, - function (error, user : mongoose.Model) : void { - if (error) { - reject(err); - } else { - if (!user.authenticate(password)) { - reject(new Error("Password non valida")); + return new Promise( + function (resolve : (data : Object) => void, + reject : (error : Object) => void) : void { + this.model.findOne( + {username: username}, + function (error : Object, + user : mongoose.Model) : void { + if (error) { + reject(err); } else { - delete user.passwordHashed; - delete user.passwordSalt; - delete user.passwordIterations; - resolve(user); + if (!user.authenticate(password)) { + reject(new Error("Password non valida")); + } else { + delete user.passwordHashed; + delete user.passwordSalt; + delete user.passwordIterations; + resolve(user); + } } + }) + }); + } + + public getOne(_id : string) : Promise { + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + this.model.findOne({_id: _id}, + { + passwordHased: false, + passwordSalt: false, + passwordIterations: false + }, + (error : Object, data : Object) => { + if (error) { + reject(error); + } else { + resolve(data); + } + }); + }) + } + + public getAll() : Promise { + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + this.model.find({}, + { + passwordHased: false, + passwordSalt: false, + passwordIterations: false + }, + (error : Object, data : Object) => { + if (error) { + reject(error); + } else { + resolve(data); } }) }); @@ -93,7 +133,7 @@ export default class UserModel extends Model { }); schema.virtual("password") - .set(function (password) : void { + .set(function (password : string) : void { this._password = password; this.passwordSalt = this.generateSalt(); this.passwordHashed = this.hashPassword(this._password); @@ -125,8 +165,9 @@ export default class UserModel extends Model { .pbkdf2Sync(password, this.passwordSalt, this.passwordIterations, - this.PWD_LENGTH) + UserModel.PWD_LENGTH) .toString("base64"); }); } + } From 2516d6705d8d4712f9c8b89f4fb3e5e598e360a3 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Thu, 12 May 2016 21:57:56 +0200 Subject: [PATCH 110/157] changes on Model to fix interface --- src/lib/AuthenticationChecker.ts | 36 +++++++++++++++++------------- src/models/customModelInterface.ts | 4 +++- src/models/databaseModel.ts | 12 +++++----- src/models/userModel.ts | 10 +++++---- src/routes/userRouter.ts | 16 ++++++++----- tslint.json | 2 +- typings.json | 1 + 7 files changed, 48 insertions(+), 33 deletions(-) diff --git a/src/lib/AuthenticationChecker.ts b/src/lib/AuthenticationChecker.ts index d180a7c..3b540d5 100644 --- a/src/lib/AuthenticationChecker.ts +++ b/src/lib/AuthenticationChecker.ts @@ -1,3 +1,7 @@ +import * as jwt from "jsonwebtoken"; +import UserModel from "../models/userModel"; +import * as express from "express"; + /** * This class is used to check the authentication for the requests * @@ -13,7 +17,6 @@ class AuthenticationChecker { private secret : string; - private authenticateFunction : any; private DEFAULT_EXPIRE_TIME : number = 60 * 24 * 7; @@ -24,17 +27,18 @@ class AuthenticationChecker { } - public login(request, response) : void { + public login(request : express.Request, + response : express.Response) : void { let username : string = request.body[this.USERNAME_BODY_FIELD]; let password : string = request.body[this.PASSWORD_BODY_FIELD]; - + UserModel .login(username, password) .then(function (error, user) { - if ( error || !user ) { + if (error || !user) { this.loginFailed(response); } else { - let userToken : string = this.createToken( user ); + let userToken : string = this.createToken(user); response.status(200); response.json({ done: true, @@ -46,16 +50,16 @@ class AuthenticationChecker { }) } - public authenticate (request, response, next) { - let token : string = request.body.token || - request.query.token || - request.headers["x-access-token"]; + public authenticate(request, response, next) { + let token : string = request.body.token || + request.query.token || + request.headers["x-access-token"]; - if ( !token ) { + if (!token) { this.responseTokenNotFound(response); } else { - jwt.verify(token, this.secret, function(err, decoded) { - if ( err ) { + jwt.verify(token, this.secret, function (err, decoded) { + if (err) { this.responseAuthenticationFailed(response); } else { request.user = decoded; @@ -65,14 +69,14 @@ class AuthenticationChecker { } } - private createToken( data : any ) { + private createToken(data : any) { return jwt.sign({ data: data, expireTime: this.DEFAULT_EXPIRE_TIME }); } - private responseTokenNotFound( response ) : void { + private responseTokenNotFound(response) : void { response.status(403); response.json({ done: false, @@ -80,7 +84,7 @@ class AuthenticationChecker { }); } - private responseAuthenticationFailed( response ) : void { + private responseAuthenticationFailed(response) : void { response.status(403); response.json({ done: false, @@ -88,7 +92,7 @@ class AuthenticationChecker { }); } - private loginFailed( response ) : void { + private loginFailed(response) : void { response.status(401); response.json({ done: false, diff --git a/src/models/customModelInterface.ts b/src/models/customModelInterface.ts index c47d97f..e59d16d 100644 --- a/src/models/customModelInterface.ts +++ b/src/models/customModelInterface.ts @@ -11,4 +11,6 @@ import * as mongoose from "mongoose"; * @license MIT */ -export default interface CustomModel extends mongoose.Document { } +interface CustomModel extends mongoose.Document { } + +export default CustomModel diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 2ee4f42..c188baf 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -1,6 +1,6 @@ -import * as m from "mongoose"; +import * as mongoose from "mongoose"; import Model from "./model"; - +import CustomModel from "./customModelInterface"; /** * DatabaseModel is a interface that represent the document on MongoDB. @@ -16,7 +16,7 @@ import Model from "./model"; * */ -export interface DatabaseDocument extends m.Document { +export interface DatabaseDocument extends CustomModel { /** * @description Represent the company name. */ @@ -72,7 +72,7 @@ export class DatabaseModel extends Model { .getRawConnection() .model( "Database", - DatabaseModel.schema + this.getSchema() ); } @@ -130,8 +130,8 @@ export class DatabaseModel extends Model { ":" + port + "/" + dbName; - let mongooseTemporaryConnection : mongoose.Connection = - mongoose.connect(connectionString); + let mongooseTemporaryConnection : mongoose = + mongoose.connection(connectionString); return new Promise((resolve : (data : Object) => void, reject : (error : Object) => void) => { diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 3a28600..946f1b5 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -20,10 +20,10 @@ interface UserDocument extends CustomModel { passwordHashed : string, passwordSalt : string, passwordIterations : number, - level : string + level : string, } -export default class UserModel extends Model { +class UserModel extends Model { private static PWD_DEFAULT_ITERATIONS : number = 1000; private static PWD_LENGHT : number = 50; @@ -101,8 +101,8 @@ export default class UserModel extends Model { }); } - protected getModel() : mongoose.Model { - return mongoose.model("User", this.getSchema()); + protected getModel() : mongoose.Model { + return mongoose.model("User", this.getSchema()); } protected getSchema() : mongoose.Schema { @@ -171,3 +171,5 @@ export default class UserModel extends Model { } } + +export default new UserModel(); \ No newline at end of file diff --git a/src/routes/userRouter.ts b/src/routes/userRouter.ts index 11105eb..7ec3ebf 100644 --- a/src/routes/userRouter.ts +++ b/src/routes/userRouter.ts @@ -40,8 +40,14 @@ export default class UserRouter { return this.router; } + private login(request : express.Request, + response : express.Response) : void { + + } + + private getOneUser(request : express.Request, - response : express.Response) : void { + response : express.Response) : void { this.userModel .getOne(request.params.user_id) .then(function (data : Object) : void { @@ -59,7 +65,7 @@ export default class UserRouter { } private getAllUsers(request : express.Request, - response : express.Response) : void { + response : express.Response) : void { this.userModel .getAll() .then(function (data : Object) : void { @@ -78,7 +84,7 @@ export default class UserRouter { private updateUser(request : express.Request, - response : express.Response) : void { + response : express.Response) : void { this.userModel .update(request.params.user_id, request.body) .then(function (data : Object) : void { @@ -97,7 +103,7 @@ export default class UserRouter { } private removeUser(request : express.Request, - response : express.Response) : void { + response : express.Response) : void { this.userModel .remove(request.params.user_id) .then(function (data : Object) : void { @@ -117,7 +123,7 @@ export default class UserRouter { private createUser(request : express.Request, - response : express.Response) : void { + response : express.Response) : void { this.userModel .create(request.body) .then(function (data : Object) : void { diff --git a/tslint.json b/tslint.json index c1baeba..fee8e7d 100644 --- a/tslint.json +++ b/tslint.json @@ -47,7 +47,7 @@ "no-string-literal": false, "no-switch-case-fall-through": true, "no-unreachable": true, - "no-unused-expression": true, + //"no-unused-expression": true, "no-unused-variable": false, "no-use-before-declare": true, "no-var-keyword": true, diff --git a/typings.json b/typings.json index 2ab0826..b09e92f 100644 --- a/typings.json +++ b/typings.json @@ -5,6 +5,7 @@ "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", "express": "registry:dt/express#4.0.0+20160317120654", "express-serve-static-core": "registry:dt/express-serve-static-core#0.0.0+20160322035842", + "jsonwebtoken": "registry:dt/jsonwebtoken#0.0.0+20160505173617", "mime": "registry:dt/mime#0.0.0+20160316155526", "mocha": "registry:dt/mocha#2.2.5+20160317120654", "mongoose": "registry:dt/mongoose#3.8.5+20160505185535", From 1b7836fdc96d5476795af219ce614e6253529083 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Thu, 12 May 2016 23:19:33 +0200 Subject: [PATCH 111/157] Some fixing action See issue #22 --- src/models/companyDocument.ts | 19 ------------------- 1 file changed, 19 deletions(-) delete mode 100644 src/models/companyDocument.ts diff --git a/src/models/companyDocument.ts b/src/models/companyDocument.ts deleted file mode 100644 index 1497082..0000000 --- a/src/models/companyDocument.ts +++ /dev/null @@ -1,19 +0,0 @@ -/** - * CompanyDocument defines an interface which stores the Company attributes. - * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Davide Rigoni | Create class | 10/05/2016 | - * - * @author Davide Rigoni - * @license MIT - * - */ -import * as mongoose from "mongoose"; - -interface CompanyDocument extends mongoose.Document { - name : string, - idOwner : string; -} - -export default CompanyDocument; From 7b246770371950b5837258b8d5b5b545bfc58619 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Thu, 12 May 2016 23:21:44 +0200 Subject: [PATCH 112/157] Some corrective action See issue #22 --- src/models/companyModel.ts | 48 ++++++++++++++++++++++-- src/models/customModelInterface.ts | 4 +- src/models/databaseModel.ts | 37 +++++++------------ src/models/model.ts | 59 ++++++++++++++++++++++++------ 4 files changed, 108 insertions(+), 40 deletions(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index 5f64f02..a8ebf22 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -1,6 +1,29 @@ import * as mongoose from "mongoose"; import Model from "./model"; -import CompanyDocument from "./companyDocument"; + +/** + * CompanyDocument defines an interface which stores the Company attributes. + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Andrea Mantovani | Insert comment above properties | 12/05/2016 | + * | Davide Rigoni | Create class | 10/05/2016 | + * + * @author Davide Rigoni + * @license MIT + */ +export interface CompanyDocument extends mongoose.Document { + /** + * @description + * Company name + */ + name : string, + /** + * @description + * Id of company's owner + */ + idOwner : string; +} /** * CompanyModel implements the company business logic. It contains model and @@ -15,16 +38,35 @@ import CompanyDocument from "./companyDocument"; * @license MIT * */ -export default class CompanyModel extends Model { - +export class CompanyModel extends Model { + /** + * @description + * Default constructor. + * @return {CompanyModel} + * This. + */ constructor() { super(); } + /** + * @description + * Get the schema of the company model. + * @returns {"mongoose".Schema} + * The schema of the Company. + * @override + */ protected getSchema() : mongoose.Schema { return new mongoose.Schema({name: String, idOwner: String}); } + /** + * @description + * Get the model of the company model instantiated by Company's schema + * @returns {Model} + * The model of the Company + * @override + */ protected getModel() : mongoose.Model { return mongoose.model("Company", this.getSchema()); } diff --git a/src/models/customModelInterface.ts b/src/models/customModelInterface.ts index c47d97f..b0e1c04 100644 --- a/src/models/customModelInterface.ts +++ b/src/models/customModelInterface.ts @@ -5,10 +5,12 @@ import * as mongoose from "mongoose"; * @history * | Author | Action Performed | Data | * | --- | --- | --- | + * | Andrea Mantovani | Use export default | 12/05/2016 | * | Luca Bianco | Created interface | 10/05/2016 | * * @author Luca Bianco * @license MIT */ +interface CustomModel extends mongoose.Document {} -export default interface CustomModel extends mongoose.Document { } +export default CustomModel; \ No newline at end of file diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 2ee4f42..a481139 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -1,7 +1,6 @@ import * as m from "mongoose"; import Model from "./model"; - /** * DatabaseModel is a interface that represent the document on MongoDB. * @@ -12,10 +11,7 @@ import Model from "./model"; * * @author Davide Polonio * @copyright MIT - * - * */ - export interface DatabaseDocument extends m.Document { /** * @description Represent the company name. @@ -25,13 +21,21 @@ export interface DatabaseDocument extends m.Document { * @description Represent the owner id. */ idOwner : string, - + /** + * @description Represent the username to access to the database. + */ username : string, - + /** + * @description Represent the password to access to the database. + */ password : string, - + /** + * @description Represent the address host where is install the database. + */ host : string, - + /** + * @description Represent the name of database. + */ dbName : string } @@ -50,30 +54,17 @@ export interface DatabaseDocument extends m.Document { * * @author Davide Polonio * @copyright MIT - * - * */ - export class DatabaseModel extends Model { - /** * @description *

This constructor calls his super constructor. After it gets the * database connection and puts it in model.

- * * @return {DatabaseModel} - * This + * This. */ constructor() { - super(); - - this.model = this.getConnection() - .getRawConnection() - .model( - "Database", - DatabaseModel.schema - ); } public create(jsonData : Object) : void { @@ -146,8 +137,6 @@ export class DatabaseModel extends Model { } }); }); - - } } diff --git a/src/models/model.ts b/src/models/model.ts index c9836d6..4635633 100644 --- a/src/models/model.ts +++ b/src/models/model.ts @@ -1,6 +1,30 @@ import MongooseConnection from "./mongooseConnection"; import * as mongoose from "mongoose"; -import {CustomModel} from "./customModelInterface"; +import CustomModel from "./customModelInterface"; + +/** + * Result document after any update. For more information about the meaning of + * any attributes refer at the official documentation: + * [Update#Output - MongoDB](http://bit.ly/1Ygx5UW) + */ +type MongoDBUpdate = { + ok: Number, + n: Number, + nModified: Number, + upserted: [{ + index: Number, + _id: mongoose.Types.ObjectId + }], + writeErrors: [{ + index: Number, + code: Number, + errmsg: String + }], + writeConcernError: [{ + code: Number, + errmsg: String + }] +}; /** * This is the base models class and contains some useful methods to perform @@ -14,10 +38,7 @@ import {CustomModel} from "./customModelInterface"; * @author Matteo Di Pirro * @license MIT */ - - abstract class Model { - /** * @description Model representing the data in mongoose */ @@ -52,12 +73,13 @@ abstract class Model { /** * @description Creates a new document into the database - * @param jsonData{Object} is the object that contains the information to - * create the object - * @returns {Promise|Promise} with the error or the saved data + * @param jsonData{Object} + * The object that contains the information to create the object + * @returns {Promise} + * Promise with the error or the saved data. */ public create(jsonData : Object) : Promise { - let concreteModel : mongoose.Document = new this.model(jsonData); + let concreteModel : CustomModel = new this.model(jsonData); return new Promise((resolve : (data : Object) => void, reject : (error : Object) => void) => { concreteModel.save((error : Object, data : Object) => { @@ -70,16 +92,29 @@ abstract class Model { }); } - public update(_id : string, jsonData : Object) : Promise { - return new Promise((resolve : (data : Object) => void, - reject : (error : Object) => void) => { + /** + * @description + * Update the document specified by id with the data, in json format, + * passed. + * @param _id {string} Id of the document + * @param jsonData {Object} + * The content of data. The classes derived from *Model* apply the override + * specify the structure of *jsonData* + * @returns {Promise} + * + */ + public update(_id : string, jsonData : Object) : Promise { + return new Promise(( + resolve : (data : MongoDBUpdate) => void, + reject : (error : Object) => void + ) => { this.model.findOneAndUpdate( {_id: _id}, { $set: jsonData, $inc: {__v: 1} }, - (error : Object, data : Object) => { + (error : Object, data : MongoDBUpdate) => { if (error) { reject(error); } else { From 1379aa8dfe22753f57e05143cb42d615176336ca Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Fri, 13 May 2016 08:52:45 +0200 Subject: [PATCH 113/157] Some fixes for authorization --- src/lib/AuthenticationChecker.ts | 34 +++++--- src/lib/LevelChecker.ts | 35 +++++++- src/routes/companyRouter.ts | 33 +++++-- src/routes/dslRouter.ts | 1 + src/routes/userRouter.ts | 145 +------------------------------ 5 files changed, 83 insertions(+), 165 deletions(-) diff --git a/src/lib/AuthenticationChecker.ts b/src/lib/AuthenticationChecker.ts index 3b540d5..e461fe4 100644 --- a/src/lib/AuthenticationChecker.ts +++ b/src/lib/AuthenticationChecker.ts @@ -1,7 +1,8 @@ import * as jwt from "jsonwebtoken"; import UserModel from "../models/userModel"; import * as express from "express"; - +import ConfigurationChooser from "../config/configurationChooser"; +import * as mongoose from "mongoose"; /** * This class is used to check the authentication for the requests * @@ -14,7 +15,7 @@ import * as express from "express"; * @license MIT */ -class AuthenticationChecker { +export default class AuthenticationChecker { private secret : string; @@ -27,14 +28,15 @@ class AuthenticationChecker { } - public login(request : express.Request, + public login(request : express.Request, response : express.Response) : void { let username : string = request.body[this.USERNAME_BODY_FIELD]; let password : string = request.body[this.PASSWORD_BODY_FIELD]; + // TODO: sistemare inclusione del modello utente UserModel .login(username, password) - .then(function (error, user) { + .then(function (error : Object, user : mongoose.Model) : void { if (error || !user) { this.loginFailed(response); } else { @@ -50,7 +52,10 @@ class AuthenticationChecker { }) } - public authenticate(request, response, next) { + public authenticate( + request : express.Request, + response : express.Response, + next : express.NextFunction) : void { let token : string = request.body.token || request.query.token || request.headers["x-access-token"]; @@ -69,14 +74,17 @@ class AuthenticationChecker { } } - private createToken(data : any) { - return jwt.sign({ - data: data, - expireTime: this.DEFAULT_EXPIRE_TIME - }); + private createToken(data : Object) : string { + return jwt.sign( + { + data: data, + expireTime: this.DEFAULT_EXPIRE_TIME + }, + ConfigurationChooser.getServerSecret() + ); } - private responseTokenNotFound(response) : void { + private responseTokenNotFound(response : express.Response) : void { response.status(403); response.json({ done: false, @@ -84,7 +92,7 @@ class AuthenticationChecker { }); } - private responseAuthenticationFailed(response) : void { + private responseAuthenticationFailed(response : express.Response) : void { response.status(403); response.json({ done: false, @@ -92,7 +100,7 @@ class AuthenticationChecker { }); } - private loginFailed(response) : void { + private loginFailed(response : express.Response) : void { response.status(401); response.json({ done: false, diff --git a/src/lib/LevelChecker.ts b/src/lib/LevelChecker.ts index caf1a25..a4d960d 100644 --- a/src/lib/LevelChecker.ts +++ b/src/lib/LevelChecker.ts @@ -1,3 +1,4 @@ +import * as express from "express"; /** * This class checks the level of the user from the request * @@ -11,7 +12,7 @@ * */ -class LevelChecker { +export default class LevelChecker { private levelsAllowed : Array; @@ -19,7 +20,17 @@ class LevelChecker { this.levelsAllowed = levelsAllowed; } - public check(request, response, next ) : void { + /** + * @description method to check the level of the user if is allowed + * + * @param request + * @param response + * @param next + */ + public check( + request : express.Request, + response : express.Response, + next : express.NextFunction) : void { let user : Object = request.user || undefined; @@ -35,6 +46,26 @@ class LevelChecker { } } + /** + * @description this is a middleware to check the level of account + * and skipping this check if the id of the user is the same with that is + * defined on the request + * + * @param request + * @param response + * @param next + */ + public checkWithIDSkip( + request : express.Request, + response : express.Response, + next : express.NextFunction) : void { + if (request.params.user_id == request.user._id ) { + next(); + } else { + this.check(request, response, next); + } + } + private accessDenied(response) : void { response.status(400); response.json({ diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index 24c1b71..4700007 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -2,6 +2,7 @@ import CompanyModel from "../models/companyModel"; import CompanyDocument from "../models/companyDocument"; import * as express from "express"; import * as promise from "es6-promise"; +import LevelChecker from "../lib/LevelChecker"; /** * This class contains endpoint definition about companies. @@ -20,19 +21,39 @@ export default class CompanyRouter { private router : express.Router = express.Router(); private companyModel : CompanyModel = new CompanyModel(); + private checkAdmin = new LevelChecker(["ADMIN", "OWNER", "SUPERADMIN"]); + private checkOwner = new LevelChecker(["OWNER", "SUPERADMIN"]); + constructor() { - this.router.get("/companies", this.getAllCompanies); - this.router.get("/companies/:company_id", this.getOneCompany); - this.router.post("/companies", this.createCompany); - this.router.put("/companies/:company_id", this.updateCompany); - this.router.delete("/companies/:company_id", this.remove); + + this.router.get( + "/companies", + this.getAllCompanies); + + this.router.get( + "/companies/:company_id", + this.getOneCompany); + + this.router.post( + "/companies", + this.createCompany); + + this.router.put( + "/companies/:company_id", + this.checkAdmin.check, + this.updateCompany); + + this.router.delete( + "/companies/:company_id", + this.checkOwner.check, + this.remove); } public getRouter() : express.Router { return this.router; } - private getOneCompany(request : express.Request, result : express.Result) { + private getOneCompany(request : express.Request, result : express.Result) : void { this.companyModel .getOne(request.params.company_id) .then(function (data : Object) : void { diff --git a/src/routes/dslRouter.ts b/src/routes/dslRouter.ts index 9d6219d..8575a5d 100644 --- a/src/routes/dslRouter.ts +++ b/src/routes/dslRouter.ts @@ -1,5 +1,6 @@ import * as express from "express"; import {DSLModel} from "../models/dslModel"; +import /** * This class contains endpoint definition about companies. diff --git a/src/routes/userRouter.ts b/src/routes/userRouter.ts index 7ec3ebf..3bac7fa 100644 --- a/src/routes/userRouter.ts +++ b/src/routes/userRouter.ts @@ -1,144 +1 @@ -import * as express from "express"; -import {UserModel} from "../models/userModel"; - -/** - * This class contains endpoint definition about companies. - * - * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | - * - * @author Emanuele Carraro - * @license MIT - * - */ -export default class UserRouter { - - private router : express.Router = express.Router(); - private userModel = new UserModel(); - - constructor() { - this.router.get( - "/users", - this.getAllUsers); - this.router.get( - "/users/:user_id", - this.getOneUser); - this.router.post( - "/users/:user_id", - this.createUser); - this.router.put( - "/users/:user_id", - this.updateUser); - this.router.delete( - "/users/:user_id", - this.removeUser); - } - - public getRouter() : express.Router { - return this.router; - } - - private login(request : express.Request, - response : express.Response) : void { - - } - - - private getOneUser(request : express.Request, - response : express.Response) : void { - this.userModel - .getOne(request.params.user_id) - .then(function (data : Object) : void { - response - .status(200) - .json(data); - }, function (error : Object) : void { - response - .status(404) - .json({ - done: false, - message: "Cannot find the request dsl" - }); - }); - } - - private getAllUsers(request : express.Request, - response : express.Response) : void { - this.userModel - .getAll() - .then(function (data : Object) : void { - response - .status(200) - .json(data); - }, function (error : Object) : void { - response - .status(404) - .json({ - done: false, - message: "Cannot find the dsl" - }); - }); - } - - - private updateUser(request : express.Request, - response : express.Response) : void { - this.userModel - .update(request.params.user_id, request.body) - .then(function (data : Object) : void { - response - .status(200) - .json(data); - }, function (error : Object) : void { - response - // Todo : set the status - .status(404) - .json({ - done: false, - message: "Cannot modify the dsl" - }); - }); - } - - private removeUser(request : express.Request, - response : express.Response) : void { - this.userModel - .remove(request.params.user_id) - .then(function (data : Object) : void { - response - .status(200) - .json(data); - }, function (error : Object) : void { - response - // Todo : set the status - .status(404) - .json({ - done: false, - message: "Cannot remove the databases" - }); - }); - } - - - private createUser(request : express.Request, - response : express.Response) : void { - this.userModel - .create(request.body) - .then(function (data : Object) : void { - response - .status(200) - .json(data); - }, function (error : Object) : void { - response - // Todo : set the status - .status(404) - .json({ - done: false, - message: "Cannot create the databases" - }); - }); - } -} - +import * as express from "express"; import {UserModel} from "../models/userModel"; import {AuthenticationChecker} from "../lib/AuthenticationChecker"; import {LevelChecker} from "../lib/LevelChecker"; /** * This class contains endpoint definition about companies. * * @history * | Author | Action Performed | Data | * | --- | --- | --- | * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | * * @author Emanuele Carraro * @license MIT * */ export default class UserRouter { private router : express.Router = express.Router(); private userModel = new UserModel(); private authCheck = new AuthenticationChecker(); private checkOwner = new LevelChecker( ["OWNER", "SUPERADMIN"]); constructor() { this.router.get( "/companies/:company_id/users", this.checkOwner.check, this.getAllUsers); this.router.get( "/companies/:company_id/users/:user_id", this.getOneUser); // FIXME: che tipo di check deve essere fatto qui? this.router.post( "/users/:user_id", this.createUser); this.router.put( "/companies/:companies_id/users/:user_id", this.checkOwner.checkWithIDSkip, this.updateUser); this.router.delete( "/companies/:companies_id/users/:user_id", this.checkOwner.checkWithIDSkip, this.removeUser); } public getRouter() : express.Router { return this.router; } private login(request : express.Request, response : express.Response) : void { this.authCheck .login(request, response) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response .status(404) .json({ done: false, message: "Cannot login" }); }); } private getOneUser(request : express.Request, response : express.Response) : void { this.userModel .getOne(request.params.user_id) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response .status(404) .json({ done: false, message: "Cannot find the request dsl" }); }); } private getAllUsers(request : express.Request, response : express.Response) : void { this.userModel .getAll() .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response .status(404) .json({ done: false, message: "Cannot find the dsl" }); }); } private updateUser(request : express.Request, response : express.Response) : void { this.userModel .update(request.params.user_id, request.body) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot modify the dsl" }); }); } private removeUser(request : express.Request, response : express.Response) : void { this.userModel .remove(request.params.user_id) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot remove the databases" }); }); } private createUser(request : express.Request, response : express.Response) : void { this.userModel .create(request.body) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot create the databases" }); }); } } \ No newline at end of file From b72ced0242a05b8c11e5743649b8b8d762e0fa25 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Fri, 13 May 2016 10:48:34 +0200 Subject: [PATCH 114/157] Rename lib's files and add dcumentation --- src/lib/LevelChecker.ts | 76 -------------- ...ionChecker.ts => authenticationChecker.ts} | 81 ++++++++++++--- src/lib/levelChecker.ts | 98 +++++++++++++++++++ 3 files changed, 165 insertions(+), 90 deletions(-) delete mode 100644 src/lib/LevelChecker.ts rename src/lib/{AuthenticationChecker.ts => authenticationChecker.ts} (52%) create mode 100644 src/lib/levelChecker.ts diff --git a/src/lib/LevelChecker.ts b/src/lib/LevelChecker.ts deleted file mode 100644 index a4d960d..0000000 --- a/src/lib/LevelChecker.ts +++ /dev/null @@ -1,76 +0,0 @@ -import * as express from "express"; -/** - * This class checks the level of the user from the request - * - * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Luca Bianco | Create class | 07/05/2016 | - * - * @author Luca Bianco - * @license MIT - * - */ - -export default class LevelChecker { - - private levelsAllowed : Array; - - constructor (levelsAllowed : Array) { - this.levelsAllowed = levelsAllowed; - } - - /** - * @description method to check the level of the user if is allowed - * - * @param request - * @param response - * @param next - */ - public check( - request : express.Request, - response : express.Response, - next : express.NextFunction) : void { - - let user : Object = request.user || undefined; - - if ( !user ) { - this.accessDenied(response); - } else { - if ( this.levelsAllowed.indexOf(user.level) ) { - // Level is inside of allowed so go to next middleware - next(); - } else { - this.accessDenied(response); - } - } - } - - /** - * @description this is a middleware to check the level of account - * and skipping this check if the id of the user is the same with that is - * defined on the request - * - * @param request - * @param response - * @param next - */ - public checkWithIDSkip( - request : express.Request, - response : express.Response, - next : express.NextFunction) : void { - if (request.params.user_id == request.user._id ) { - next(); - } else { - this.check(request, response, next); - } - } - - private accessDenied(response) : void { - response.status(400); - response.json({ - done: false, - message: "Unauthorized" - }); - } -} diff --git a/src/lib/AuthenticationChecker.ts b/src/lib/authenticationChecker.ts similarity index 52% rename from src/lib/AuthenticationChecker.ts rename to src/lib/authenticationChecker.ts index e461fe4..a6564af 100644 --- a/src/lib/AuthenticationChecker.ts +++ b/src/lib/authenticationChecker.ts @@ -3,8 +3,10 @@ import UserModel from "../models/userModel"; import * as express from "express"; import ConfigurationChooser from "../config/configurationChooser"; import * as mongoose from "mongoose"; + /** - * This class is used to check the authentication for the requests + * This class is used to check if the current user is correctly authenticate + * to the MaaS application. * * @history * | Author | Action Performed | Data | @@ -15,28 +17,47 @@ import * as mongoose from "mongoose"; * @license MIT */ -export default class AuthenticationChecker { +class AuthenticationChecker { + /** + * @description Server's secret string, used for encode the JWT tokens. + */ private secret : string; - private DEFAULT_EXPIRE_TIME : number = 60 * 24 * 7; - - private USERNAME_BODY_FIELD : string = "username"; - private PASSWORD_BODY_FIELD : string = "username"; + /** + * @description Request's expire time. By default it is 60*24*7. + */ + private const DEFAULT_EXPIRE_TIME : number = 60 * 24 * 7; - constructor() { + /** + * @description Default name of the 'username' field in every request. + */ + private const USERNAME_BODY_FIELD : string = "username"; - } + /** + * @description Default name of the 'password' field in every request. + */ + private const PASSWORD_BODY_FIELD : string = "password"; + /** + * Login the user. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ public login(request : express.Request, response : express.Response) : void { let username : string = request.body[this.USERNAME_BODY_FIELD]; let password : string = request.body[this.PASSWORD_BODY_FIELD]; - + // TODO: sistemare inclusione del modello utente UserModel - .login(username, password) - .then(function (error : Object, user : mongoose.Model) : void { + .login(username, password) // Call the login method... + .then(function (error : Object, user : mongoose.Model) : + void { // ...when done, let's say it to the client if (error || !user) { this.loginFailed(response); } else { @@ -52,6 +73,16 @@ export default class AuthenticationChecker { }) } + /** + * Authenticate the user. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + * @param next Function which invokes the next route handler in framework. + */ public authenticate( request : express.Request, response : express.Response, @@ -60,13 +91,13 @@ export default class AuthenticationChecker { request.query.token || request.headers["x-access-token"]; - if (!token) { + if (!token) { // Token not found this.responseTokenNotFound(response); } else { jwt.verify(token, this.secret, function (err, decoded) { - if (err) { + if (err) { // Authentication failed this.responseAuthenticationFailed(response); - } else { + } else { // Success! request.user = decoded; next(); } @@ -74,6 +105,11 @@ export default class AuthenticationChecker { } } + /** + * Create the JWT token for the current user. + * @param data User's data. + * @returns {string} A string which represents the JWT token created. + */ private createToken(data : Object) : string { return jwt.sign( { @@ -84,6 +120,11 @@ export default class AuthenticationChecker { ); } + /** + * Create a parametrized response for the token not found situation. + * @param response The generated response with an error message which + * represents the "token not found" situation. + */ private responseTokenNotFound(response : express.Response) : void { response.status(403); response.json({ @@ -92,6 +133,11 @@ export default class AuthenticationChecker { }); } + /** + * Create a parametrized response for the authentication failed situation. + * @param response The generated response with an error message which + * represents the "authentication failed" situation. + */ private responseAuthenticationFailed(response : express.Response) : void { response.status(403); response.json({ @@ -100,6 +146,11 @@ export default class AuthenticationChecker { }); } + /** + * Create a parametrized response for the login failed situation. + * @param response The generated response with an error message which + * represents the "login failed" situation. + */ private loginFailed(response : express.Response) : void { response.status(401); response.json({ @@ -108,3 +159,5 @@ export default class AuthenticationChecker { }); } } + +export default AuthenticationChecker; diff --git a/src/lib/levelChecker.ts b/src/lib/levelChecker.ts new file mode 100644 index 0000000..f95aa17 --- /dev/null +++ b/src/lib/levelChecker.ts @@ -0,0 +1,98 @@ +import * as express from "express"; +/** + * This class checks the level of the user from the request + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Luca Bianco | Create class | 07/05/2016 | + * + * @author Luca Bianco + * @license MIT + * + */ + +class LevelChecker { + + /** + * @description Array which contains all the possible users' levels. + */ + private levelsAllowed : Array; + + /** + * Complete constructor. + * @param levelsAllowed An array which contains all the possible users' + * levels. + */ + constructor (levelsAllowed : Array) { + this.levelsAllowed = levelsAllowed; + } + + /** + * @description Method to check the level of the user. It allows to + * check if the current user is allowed to do the invoked operation. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + * @param next Function which invokes the next route handler in framework. + */ + public check( + request : express.Request, + response : express.Response, + next : express.NextFunction) : void { + + let user : Object = request.user || undefined; + + if ( !user ) { // There's no user to check + this.accessDenied(response); + } else { + if ( this.levelsAllowed.indexOf(user.level) ) { + // Level is inside of allowed so go to next middleware + next(); + } else { + this.accessDenied(response); + } + } + } + + /** + * @description This is a middleware to check the level of an user. This + * check is skipped if the id of the user is the same that is defined on the + * request. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + * @param next Function which invokes the next route handler in framework. + */ + public checkWithIDSkip( + request : express.Request, + response : express.Response, + next : express.NextFunction) : void { + if (request.params.user_id == request.user._id ) { + next(); + } else { + this.check(request, response, next); + } + } + + /** + * Create a parametrized response for the access denied situation. + * @param response The generated response with an error message which + * represents the "access denied" situation. + */ + private accessDenied(response : express.Response) : void { + response.status(400); + response.json({ + done: false, + message: "Unauthorized" + }); + } +} + +export default LevelChecker; From 28967d6107fd87ca621f6a74f6b16cb1c03b669c Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Fri, 13 May 2016 11:16:54 +0200 Subject: [PATCH 115/157] Add documentation --- src/models/companyModel.ts | 21 ++++----- src/models/databaseModel.ts | 48 +++++++++++++++---- src/models/dslModel.ts | 12 ++++- src/models/model.ts | 54 +++++++++++----------- src/models/userModel.ts | 91 +++++++++++++++++++++++++++++++------ 5 files changed, 163 insertions(+), 63 deletions(-) diff --git a/src/models/companyModel.ts b/src/models/companyModel.ts index a8ebf22..0b86140 100644 --- a/src/models/companyModel.ts +++ b/src/models/companyModel.ts @@ -14,13 +14,11 @@ import Model from "./model"; */ export interface CompanyDocument extends mongoose.Document { /** - * @description - * Company name + * @description Company's name */ name : string, /** - * @description - * Id of company's owner + * @description Id of company's owner */ idOwner : string; } @@ -38,22 +36,17 @@ export interface CompanyDocument extends mongoose.Document { * @license MIT * */ -export class CompanyModel extends Model { +class CompanyModel extends Model { /** - * @description - * Default constructor. - * @return {CompanyModel} - * This. + * @description Default constructor. */ constructor() { super(); } /** - * @description - * Get the schema of the company model. - * @returns {"mongoose".Schema} - * The schema of the Company. + * @description Get the schema of the company model. + * @returns {"mongoose".Schema} The schema of the Company. * @override */ protected getSchema() : mongoose.Schema { @@ -71,3 +64,5 @@ export class CompanyModel extends Model { return mongoose.model("Company", this.getSchema()); } } + +export default CompanyModel; diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index c56a0b1..440f736 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -56,7 +56,7 @@ export interface DatabaseDocument extends CustomModel { * @author Davide Polonio * @copyright MIT */ -export class DatabaseModel extends Model { +class DatabaseModel extends Model { /** * @description *

This constructor calls his super constructor. After it gets the @@ -68,6 +68,10 @@ export class DatabaseModel extends Model { super(); } + /** + * @description Create a new database for the stated Company. + * @param jsonData data of the new database. + */ public create(jsonData : Object) : void { this .getCollections( @@ -83,6 +87,11 @@ export class DatabaseModel extends Model { }) } + /** + * @description Update the stated Company databases. + * @param _id The id of the Company. + * @param jsonData Data of the new database. + */ public update(_id : string, jsonData : Object) : void { this .getCollections( @@ -98,8 +107,13 @@ export class DatabaseModel extends Model { }) } - protected getSchema() : m.Schema { - return new m.Schema({ + /** + * @description Get the database's schema. + * @returns {"mongoose".Schema} The schema. + * @override + */ + protected getSchema() : mongoose.Schema { + return new mongoose.Schema({ name: String, idOwner: String, idDatabase: String, @@ -107,14 +121,30 @@ export class DatabaseModel extends Model { }); } - protected getModel() : m.Model { - return mongoose.model("Database", this.getSchema()); + /** + * @description Return the database's model. + * @returns {Model} The model. + * @override + */ + protected getModel() : mongoose.Model { + return mongoose.model("Database", this.getSchema()); } + /** + * @description Return the collection's list of the stated database. + * @param port Database's port. + * @param host Database's host. + * @param username Database's user username. + * @param password Database's user password. + * @param dbName Database's name. + * @returns {Promise|Promise} Promise generated by a mongoose's query. + */ private getCollections(port : string, host : string, username : string, password : string, - dbName : string) : Array { + dbName : string) : Promise { + // Connect to the database: + // Create the string let connectionString : string = "mongodb://" + username + ":" + password + @@ -122,13 +152,13 @@ export class DatabaseModel extends Model { ":" + port + "/" + dbName; + // And use it to connect let mongooseTemporaryConnection : mongoose = - mongoose.connection(connectionString); + mongoose.connect(connectionString); return new Promise((resolve : (data : Object) => void, reject : (error : Object) => void) => { - // Richiedo i nomi delle connessioni - + // Get connections' names mongooseTemporaryConnection.db.collectionNames( function (err : Object, names : Array) : void { if (err) { diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index 83d3913..c833be0 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -21,7 +21,7 @@ type DSLSchema = { export interface PermissionOnDSL { /** * @description - * Id user + * User's ID */ user : string; @@ -100,6 +100,11 @@ export class DSLModel extends Model { super(); } + /** + * @description Get the dsl's schema. + * @returns {"mongoose".Schema} The schema. + * @override + */ protected getSchema() : mongoose.Schema { return new mongoose.Schema({ permission: [{user: String, read: Boolean, exec: Boolean}], @@ -107,6 +112,11 @@ export class DSLModel extends Model { }); } + /** + * @description Get the dsl's model. + * @returns {"mongoose".Schema} The model. + * @override + */ protected getModel() : mongoose.Model { return mongoose.model("DSL", this.getSchema()); } diff --git a/src/models/model.ts b/src/models/model.ts index 4635633..d04eeac 100644 --- a/src/models/model.ts +++ b/src/models/model.ts @@ -8,21 +8,21 @@ import CustomModel from "./customModelInterface"; * [Update#Output - MongoDB](http://bit.ly/1Ygx5UW) */ type MongoDBUpdate = { - ok: Number, - n: Number, - nModified: Number, - upserted: [{ - index: Number, - _id: mongoose.Types.ObjectId + ok : Number, + n : Number, + nModified : Number, + upserted : [{ + index : Number, + _id : mongoose.Types.ObjectId }], - writeErrors: [{ - index: Number, - code: Number, - errmsg: String + writeErrors : [{ + index : Number, + code : Number, + errmsg : String }], - writeConcernError: [{ - code: Number, - errmsg: String + writeConcernError : [{ + code : Number, + errmsg : String }] }; @@ -125,11 +125,10 @@ abstract class Model { } /** - * @description remove the document specified by the id - * - * @param _id - * - * @returns {Promise|Promise} + * @description Remove the document specified by the id + * @param _id Remove the element with the stated _id. + * @returns {Promise|Promise} Promise generated by the + * mongoose's query. */ public remove(_id : string) : Promise { return new Promise((resolve : (data : Object) => void, @@ -147,11 +146,12 @@ abstract class Model { } /** - * @description get the document specified by the id + * @description Get the document specified by the id. * - * @param _id id of the document to return + * @param _id id of the document to return. * - * @returns {Promise|Promise} + * @returns {Promise|Promise} Promise generated by the + * mongoose's query. */ public getOne(_id : string) : Promise { return new Promise((resolve : (data : Object) => void, @@ -168,9 +168,9 @@ abstract class Model { } /** - * @description get all the documents for the model of the data - * - * @returns {Promise|Promise} + * @description Get all the documents for the model of the data + * @returns {Promise|Promise} Promise generated by the + * mongoose's query. */ public getAll() : Promise { return new Promise((resolve : (data : Object) => void, @@ -188,15 +188,15 @@ abstract class Model { /** * @description Builds the schema of data using mongoose Schema. - * @returns {mongoose.Schema} the schema built + * @returns {mongoose.Schema} The built schema. */ protected abstract getSchema() : mongoose.Schema; /** * @description Returns the mongoose model representing the data into the - * database + * database. * @returns {mongoose.Model} the model to use to manage data into the - * database + * database. */ protected abstract getModel() : mongoose.Model; diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 946f1b5..b8d30ed 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -16,29 +16,71 @@ import CustomModel from "./customModelInterface"; */ interface UserDocument extends CustomModel { - username : string, - passwordHashed : string, - passwordSalt : string, - passwordIterations : number, - level : string, + /** + * @description The user's username. + */ + username : string; + + /** + * @description The user's hashed password. + */ + passwordHashed : string; + + /** + * @description The user's salt password. + */ + passwordSalt : string; + + /** + * @description The user's password iteration. + */ + passwordIterations : number; + + /** + * @description The user's level. + */ + level : string; } +/** + * @description This class represents the user model. + */ class UserModel extends Model { - - private static PWD_DEFAULT_ITERATIONS : number = 1000; - private static PWD_LENGHT : number = 50; - + /** + * @description Default number of password iterations. + */ + private static const PWD_DEFAULT_ITERATIONS : number = 1000; + + /** + * Default password length. + */ + private static const PWD_LENGTH : number = 50; + + /** + * Array which represents the user's levels. + * @type {string[]} + */ private USER_TYPES : Array = [ - "BASE", + "GUEST", + "MEMBER", "ADMIN", "OWNER", "SUPERADMIN" ]; + /** + * Default constructor. + */ constructor() { super(); } + /** + * Login method. + * @param username User's username. + * @param password USer's password. + * @returns {Promise|Promise} Promise generated by the mongoose's query. + */ public login(username : string, password : string) : Promise { return new Promise( function (resolve : (data : Object) => void, @@ -48,10 +90,10 @@ class UserModel extends Model { function (error : Object, user : mongoose.Model) : void { if (error) { - reject(err); + reject(error); } else { if (!user.authenticate(password)) { - reject(new Error("Password non valida")); + reject(new Error("Invalid password!")); } else { delete user.passwordHashed; delete user.passwordSalt; @@ -63,6 +105,11 @@ class UserModel extends Model { }); } + /** + * Get the element represented by the _id ID. + * @param _id The ID of the element. + * @returns {Promise|Promise} Promise generated by the mongoose's query. + */ public getOne(_id : string) : Promise { return new Promise((resolve : (data : Object) => void, reject : (error : Object) => void) => { @@ -82,6 +129,10 @@ class UserModel extends Model { }) } + /** + * Get all the element of a collection. + * @returns {Promise|Promise} Promise generated by the mongoose's query. + */ public getAll() : Promise { return new Promise((resolve : (data : Object) => void, reject : (error : Object) => void) => { @@ -101,10 +152,20 @@ class UserModel extends Model { }); } + /** + * @description Return the user's model. + * @returns {Model} The model. + * @override + */ protected getModel() : mongoose.Model { return mongoose.model("User", this.getSchema()); } + /** + * @description Return the user's model. + * @returns {Model} The model. + * @override + */ protected getSchema() : mongoose.Schema { let schema : mongoose.Schema = new mongoose.Schema({ username: { @@ -147,6 +208,10 @@ class UserModel extends Model { return schema; } + /** + * Set the methods of the user's schema. + * @param schema The user's schema. + */ private setSchemaMethods(schema : mongoose.Schema) : void { schema.method( "authenticate", @@ -172,4 +237,4 @@ class UserModel extends Model { } -export default new UserModel(); \ No newline at end of file +export default new UserModel(); From 6253c80b9127366ac4a3efcdb8e90dad08dd3b37 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Fri, 13 May 2016 11:50:14 +0200 Subject: [PATCH 116/157] Fixed routes --- src/routes/companyRouter.ts | 5 +++-- src/routes/databaseRouter.ts | 13 ++++++++++++- src/routes/dslRouter.ts | 17 ++++++++++++----- 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index 4700007..650b4c5 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -23,11 +23,12 @@ export default class CompanyRouter { private checkAdmin = new LevelChecker(["ADMIN", "OWNER", "SUPERADMIN"]); private checkOwner = new LevelChecker(["OWNER", "SUPERADMIN"]); - + private checkSuperAdmin = new LevelChecker(["SUPERADMIN"]); constructor() { this.router.get( - "/companies", + "/admin/companies", + this.checkSuperAdmin.check, this.getAllCompanies); this.router.get( diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 462e58f..fd546f9 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -1,5 +1,6 @@ import * as express from "express"; import {DatabaseModel} from "../models/databaseModel"; +import LevelChecker from "../lib/LevelChecker"; /* import authentication checker */ /** @@ -22,22 +23,32 @@ export default class DatabaseRouter { private router : express.Router = express.Router(); private databaseModel = new DatabaseModel(); + private checkMember = new LevelChecker( + ["MEMBER", "ADMIN", "OWNER", "SUPERADMIN"]); + + private checkAdmin = new LevelChecker( + ["ADMIN", "OWNER", "SUPERADMIN"]); constructor() { this.router.get( "/companies/:company_id/databases", + this.checkMember.check, this.getAllDatabases); this.router.get( "/companies/:company_id/databases/:database_id", + this.checkMember.check, this.getOneDatabase); this.router.post( "/companies/:company_id/databases", + this.checkAdmin.check, this.createDatabase); this.router.put( "/companies/:company_id/database/:database_id", + this.checkAdmin.check, this.updateDatabase); this.router.delete( "/companies/:company_id/database/:database_id", + this.checkAdmin.check, this.removeDatabase); } @@ -47,7 +58,7 @@ export default class DatabaseRouter { private getOneDatabase(request : express.Request, result : express.Result) : void { this.databaseModel - .getOne(reqest.params.database_id) + .getOne(request.params.database_id) .then(function (data : Object) : void { result .status(200) diff --git a/src/routes/dslRouter.ts b/src/routes/dslRouter.ts index 8575a5d..31ec5df 100644 --- a/src/routes/dslRouter.ts +++ b/src/routes/dslRouter.ts @@ -1,6 +1,7 @@ import * as express from "express"; import {DSLModel} from "../models/dslModel"; -import +import LevelChecker from "../lib/LevelChecker"; + /** * This class contains endpoint definition about companies. @@ -18,22 +19,28 @@ export default class DslRouter { private router : express.Router = express.Router(); private dslModel = new DSLModel(); + private checkMember = new LevelChecker( + ["MEMBER", "ADMIN", "OWNER", "SUPERADMIN"]); constructor() { this.router.get( "/companies/:company_id/dsl", this.getAllDSL); this.router.get( - "/companies/:company_id/dsl/:dsl_id", + "/companies/:company_id/DSLs/:dsl_id", + this.checkMember.check, this.getOneDSL); this.router.post( - "/companies/:company_id/dsl", + "/companies/:company_id/DSLs/", + this.checkMember.check, this.createDSL); this.router.put( - "/companies/:company_id/dsl/:dsl_id", + "/companies/:company_id/DSLs/:dsl_id", + this.checkMember.check, this.updateDSL); this.router.delete( - "/companies/:company_id/dsl/:dsl_id", + "/companies/:company_id/DSLs/:dsl_id", + this.checkMember.check, this.removeDSL); } From 6151a61bfb07f907531f5be74fa51760792cda86 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Fri, 13 May 2016 16:06:00 +0200 Subject: [PATCH 117/157] Add documentation and resolve some compilation errors --- src/lib/authenticationChecker.ts | 20 +++--- src/lib/levelChecker.ts | 2 +- src/maas.ts | 4 +- src/models/databaseModel.ts | 74 ++++++++++++++------ src/models/dslModel.ts | 4 +- src/models/model.ts | 2 +- src/models/userModel.ts | 8 +-- src/routes/companyRouter.ts | 112 ++++++++++++++++++++++++++----- src/routes/databaseRouter.ts | 103 +++++++++++++++++++++++----- src/routes/dslRouter.ts | 87 +++++++++++++++++++++--- src/routes/userRouter.ts | 2 +- 11 files changed, 335 insertions(+), 83 deletions(-) diff --git a/src/lib/authenticationChecker.ts b/src/lib/authenticationChecker.ts index a6564af..1bb54a5 100644 --- a/src/lib/authenticationChecker.ts +++ b/src/lib/authenticationChecker.ts @@ -1,7 +1,8 @@ import * as jwt from "jsonwebtoken"; import UserModel from "../models/userModel"; +import UserDocument from "../models/userModel"; import * as express from "express"; -import ConfigurationChooser from "../config/configurationChooser"; +import ConfigurationChooser from "../config/index"; import * as mongoose from "mongoose"; /** @@ -27,17 +28,17 @@ class AuthenticationChecker { /** * @description Request's expire time. By default it is 60*24*7. */ - private const DEFAULT_EXPIRE_TIME : number = 60 * 24 * 7; + private DEFAULT_EXPIRE_TIME : number = 60 * 24 * 7; /** * @description Default name of the 'username' field in every request. */ - private const USERNAME_BODY_FIELD : string = "username"; + private USERNAME_BODY_FIELD : string = "username"; /** * @description Default name of the 'password' field in every request. */ - private const PASSWORD_BODY_FIELD : string = "password"; + private PASSWORD_BODY_FIELD : string = "password"; /** * Login the user. @@ -54,11 +55,12 @@ class AuthenticationChecker { let password : string = request.body[this.PASSWORD_BODY_FIELD]; // TODO: sistemare inclusione del modello utente - UserModel + let userModel : UserModel = new UserModel(); + userModel .login(username, password) // Call the login method... - .then(function (error : Object, user : mongoose.Model) : + .then(function (user : mongoose.Model) : void { // ...when done, let's say it to the client - if (error || !user) { + if (!user) { this.loginFailed(response); } else { let userToken : string = this.createToken(user); @@ -67,7 +69,7 @@ class AuthenticationChecker { done: true, message: "Authentication done", token: userToken, - user_id: user._id + user_id: user["_id"] }); } }) @@ -116,7 +118,7 @@ class AuthenticationChecker { data: data, expireTime: this.DEFAULT_EXPIRE_TIME }, - ConfigurationChooser.getServerSecret() + ConfigurationChooser.getConfig().getServerSecret() ); } diff --git a/src/lib/levelChecker.ts b/src/lib/levelChecker.ts index f95aa17..1be7205 100644 --- a/src/lib/levelChecker.ts +++ b/src/lib/levelChecker.ts @@ -49,7 +49,7 @@ class LevelChecker { if ( !user ) { // There's no user to check this.accessDenied(response); } else { - if ( this.levelsAllowed.indexOf(user.level) ) { + if ( this.levelsAllowed.indexOf(user["level"]) ) { // Level is inside of allowed so go to next middleware next(); } else { diff --git a/src/maas.ts b/src/maas.ts index 961a728..c92e4eb 100644 --- a/src/maas.ts +++ b/src/maas.ts @@ -1,7 +1,7 @@ import * as express from "express"; import * as bodyParser from "body-parser"; import * as http from "http"; -import ConfigurationChooser from "./config/configurationChooser"; +import ConfigurationChooser from "./config/index"; import Configuration from "./config/configuration"; import * as routes from "./routes/routerFacade"; @@ -14,7 +14,7 @@ app.use(bodyParser.urlencoded({extended: true})); app.use(bodyParser.json()); // Routes' require -app.use("/api", routes); +/* app.use("/api", routes); */ // Starting the server app.set("port", process.env.PORT || 3000); diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 440f736..82a0207 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -1,6 +1,7 @@ import * as mongoose from "mongoose"; import Model from "./model"; import CustomModel from "./customModelInterface"; +import MongoDBUpdate from "./model"; /** * DatabaseModel is a interface that represent the document on MongoDB. @@ -71,42 +72,73 @@ class DatabaseModel extends Model { /** * @description Create a new database for the stated Company. * @param jsonData data of the new database. + * @returns {Promise} + * Promise with the error or the saved data. + * @override */ - public create(jsonData : Object) : void { + public create(jsonData : Object) : Promise { + let self : DatabaseModel = this; this .getCollections( - jsonData.port, - jsonData.host, - jsonData.username, - jsonData.password, - jsonData.dbName + jsonData["port"], + jsonData["host"], + jsonData["username"], + jsonData["password"], + jsonData["dbName"] ) - .then(function (collections : Array) { - jsonData.collections = collections; - super.create(jsonData); - }) + .then(function (collections : Array) : Promise { + jsonData["collections"] = collections; + return self.superCreate(jsonData); + }); + } + + /** + * Method used for invoke the base class create method from a callback + * function. + * @param jsonData Data of the database. + * @returns {Promise} + * Promise with the error or the saved data + */ + private superCreate(jsonData : Object) : Promise { + return super.create(jsonData) } /** * @description Update the stated Company databases. * @param _id The id of the Company. * @param jsonData Data of the new database. + * @returns {Promise} + * Promise with the error or the saved data. */ - public update(_id : string, jsonData : Object) : void { + public update(_id : string, jsonData : Object) : Promise { + let self : DatabaseModel = this; this .getCollections( - jsonData.port, - jsonData.host, - jsonData.username, - jsonData.password, - jsonData.dbName + jsonData["port"], + jsonData["host"], + jsonData["username"], + jsonData["password"], + jsonData["dbName"] ) .then(function (collections : Array) { - jsonData.collections = collections; - super.update(_id, jsonData); + jsonData["collections"] = collections; + self.superUpdate(_id, jsonData); }) } + /** + * Method used for invoke the base class update method from a callback + * function. + * @param _id The id of the company + * @param jsonData Data of the database. + * @returns {Promise} + * Promise with the error or the saved data + */ + private superUpdate(_id : string, jsonData : Object) : + Promise { + return super.update(_id, jsonData); + } + /** * @description Get the database's schema. * @returns {"mongoose".Schema} The schema. @@ -141,7 +173,7 @@ class DatabaseModel extends Model { */ private getCollections(port : string, host : string, username : string, password : string, - dbName : string) : Promise { + dbName : string) : Promise { // Connect to the database: // Create the string @@ -153,8 +185,8 @@ class DatabaseModel extends Model { "/" + dbName; // And use it to connect - let mongooseTemporaryConnection : mongoose = - mongoose.connect(connectionString); + let mongooseTemporaryConnection : mongoose.Connection = + mongoose.createConnection(connectionString); return new Promise((resolve : (data : Object) => void, reject : (error : Object) => void) => { diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index c833be0..df18d87 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -89,7 +89,7 @@ export interface DSLDocument extends mongoose.Document { * @author Andrea Mantovani * @license MIT */ -export class DSLModel extends Model { +class DSLModel extends Model { /** * Default constructor. @@ -121,3 +121,5 @@ export class DSLModel extends Model { return mongoose.model("DSL", this.getSchema()); } } + +export default DSLModel; diff --git a/src/models/model.ts b/src/models/model.ts index d04eeac..d00f466 100644 --- a/src/models/model.ts +++ b/src/models/model.ts @@ -7,7 +7,7 @@ import CustomModel from "./customModelInterface"; * any attributes refer at the official documentation: * [Update#Output - MongoDB](http://bit.ly/1Ygx5UW) */ -type MongoDBUpdate = { +export type MongoDBUpdate = { ok : Number, n : Number, nModified : Number, diff --git a/src/models/userModel.ts b/src/models/userModel.ts index b8d30ed..6f8ad94 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -49,12 +49,12 @@ class UserModel extends Model { /** * @description Default number of password iterations. */ - private static const PWD_DEFAULT_ITERATIONS : number = 1000; + private static PWD_DEFAULT_ITERATIONS : number = 1000; /** * Default password length. */ - private static const PWD_LENGTH : number = 50; + private static PWD_LENGTH : number = 50; /** * Array which represents the user's levels. @@ -183,7 +183,7 @@ class UserModel extends Model { }, passwordIterations: { type: Number, - default: this.PWD_DEFAULT_ITERATIONS + default: UserModel.PWD_DEFAULT_ITERATIONS }, level: { type: String, @@ -237,4 +237,4 @@ class UserModel extends Model { } -export default new UserModel(); +export default UserModel; diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index 4700007..207c36e 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -1,8 +1,8 @@ import CompanyModel from "../models/companyModel"; -import CompanyDocument from "../models/companyDocument"; +import CompanyDocument from "../models/companyModel"; import * as express from "express"; import * as promise from "es6-promise"; -import LevelChecker from "../lib/LevelChecker"; +import LevelChecker from "../lib/levelChecker"; /** * This class contains endpoint definition about companies. @@ -16,16 +16,40 @@ import LevelChecker from "../lib/LevelChecker"; * @license MIT * */ -export default class CompanyRouter { +class CompanyRouter { - private router : express.Router = express.Router(); - private companyModel : CompanyModel = new CompanyModel(); + /** + * @description Express router. + */ + private router : express.Router; - private checkAdmin = new LevelChecker(["ADMIN", "OWNER", "SUPERADMIN"]); - private checkOwner = new LevelChecker(["OWNER", "SUPERADMIN"]); + /** + * @description Company model. + */ + private companyModel : CompanyModel; + /** + * @description Minimum level: ADMIN + */ + private checkAdmin : LevelChecker; + + /** + * @description Minimum level: OWNER + */ + private checkOwner : LevelChecker; + + /** + * Complete constructor. Here we initialize the company routes. + */ constructor() { + // Init fields. + this.router = express.Router(); + this.companyModel = new CompanyModel(); + this.checkAdmin = new LevelChecker(["ADMIN", "OWNER", "SUPERADMIN"]); + this.checkOwner = new LevelChecker(["OWNER", "SUPERADMIN"]); + + // Set the endpoints. this.router.get( "/companies", this.getAllCompanies); @@ -49,11 +73,25 @@ export default class CompanyRouter { this.remove); } + /** + * @description Return the Express router. + * @returns {express.Router} The Express router. + */ public getRouter() : express.Router { return this.router; } - private getOneCompany(request : express.Request, result : express.Result) : void { + /** + * @description Get a specific Company. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ + private getOneCompany(request : express.Request, + result : express.Response) : void { this.companyModel .getOne(request.params.company_id) .then(function (data : Object) : void { @@ -65,12 +103,22 @@ export default class CompanyRouter { .status(404) .json({ done: false, - message: "Cannot find the request company" + message: "Cannot find the requested company" }); }) } - private getAllCompanies(request : express.Request, result : express.Result) : void { + /** + * @description Get all the companies subscribed to MaaS. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ + private getAllCompanies(request : express.Request, + result : express.Response) : void { this.companyModel .getAll() .then(function (data : Object) : void { @@ -88,7 +136,17 @@ export default class CompanyRouter { }); } - private createCompany(request : express.Request, result : express.Result) : void { + /** + * @description Create a new Company. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ + private createCompany(request : express.Request, + result : express.Response) : void { this.companyModel .create(request.body) .then(function (data : Object) : void { @@ -106,14 +164,24 @@ export default class CompanyRouter { }); } - private updateCompany(request : express.Request, result : express.Result) : void { + /** + * Update a steted Company. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ + private updateCompany(request : express.Request, + result : express.Response) : void { this.companyModel .update(request.params.company_id, request.body) .then(function (data : Object) : void { result .status(200) .json(data); - }, function (error : Object) { + }, function (error : Object) : void { result .status(406) .json({ @@ -123,21 +191,33 @@ export default class CompanyRouter { }) } - private remove(request : express.Request, result : express.Result) : void { + /** + * Remove a stated company. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ + private remove(request : express.Request, + result : express.Response) : void { this.companyModel .remove(request.params) .then(function (data : Object) : void { result .status(200) .json(data); - }, function (error : Object) { + }, function (error : Object) : void { result // Todo set the status .status(400) .json({ done: false, - message: "Impossible to remove the Company" + message: "Can't remove the Company" }); }); } } + +export default CompanyRouter; diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 462e58f..3ceb652 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -1,6 +1,5 @@ import * as express from "express"; -import {DatabaseModel} from "../models/databaseModel"; -/* import authentication checker */ +import DatabaseModel from "../models/databaseModel"; /** * This class contains API definitions for companies database connections. @@ -18,12 +17,27 @@ import {DatabaseModel} from "../models/databaseModel"; * */ -export default class DatabaseRouter { +class DatabaseRouter { - private router : express.Router = express.Router(); - private databaseModel = new DatabaseModel(); + /** + * @description Express router. + */ + private router : express.Router; + /** + * @description Database model. + */ + private databaseModel : DatabaseModel; + + /** + * Complete constructor. Here we initialize databases routers. + */ constructor() { + + this.router = express.Router(); + this.databaseModel = new DatabaseModel(); + + this.router.get( "/companies/:company_id/databases", this.getAllDatabases); @@ -41,13 +55,28 @@ export default class DatabaseRouter { this.removeDatabase); } + /** + * @description Return the Express router. + * @returns {express.Router} The Express router. + */ public getRouter() : express.Router { return this.router; } - private getOneDatabase(request : express.Request, result : express.Result) : void { + /** + * @description Get the database represented by the id contained in + * the request. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ + private getOneDatabase(request : express.Request, + result : express.Response) : void { this.databaseModel - .getOne(reqest.params.database_id) + .getOne(request.params.database_id) .then(function (data : Object) : void { result .status(200) @@ -57,12 +86,22 @@ export default class DatabaseRouter { .status(404) .json({ done: false, - message: "Cannot find the request database" + message: "Cannot find the requested database" }); }); } - private getAllDatabases(request : express.Request, result : express.Result) : void { + /** + * @description Get all databases. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ + private getAllDatabases(request : express.Request, + result : express.Response) : void { this.databaseModel .getAll() .then(function (data : Object) : void { @@ -79,8 +118,18 @@ export default class DatabaseRouter { }); } - - private updateDatabase(request : express.Request, response : express.Response) : void { + /** + * @description Update the database represented by the id contained in + * the request. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ + private updateDatabase(request : express.Request, + result : express.Response) : void { this.databaseModel .update(request.params.database_id, request.body) .then(function (data : Object) : void { @@ -98,7 +147,18 @@ export default class DatabaseRouter { }); } - private removeDatabase(request : express.Request, response : express.Resolve) : void { + /** + * @description Remove the database represented by the id contained in + * the request. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ + private removeDatabase(request : express.Request, + result : express.Response) : void { this.databaseModel .remove(request.params.database_id) .then(function (data : Object) : void { @@ -111,13 +171,22 @@ export default class DatabaseRouter { .status(404) .json({ done: false, - message: "Cannot remove the databases" + message: "Cannot remove the database" }); }); } - - private createDatabase(request : express.Request, response : express.Response) : void { + /** + * @description Create a new database. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ + private createDatabase(request : express.Request, + result : express.Response) : void { this.databaseModel .create(request.body) .then(function (data : Object) : void { @@ -130,8 +199,10 @@ export default class DatabaseRouter { .status(404) .json({ done: false, - message: "Cannot create the databases" + message: "Cannot create the database" }); }); } } + +export default DatabaseRouter; diff --git a/src/routes/dslRouter.ts b/src/routes/dslRouter.ts index 8575a5d..fea3ddd 100644 --- a/src/routes/dslRouter.ts +++ b/src/routes/dslRouter.ts @@ -1,9 +1,8 @@ import * as express from "express"; -import {DSLModel} from "../models/dslModel"; -import +import DSLModel from "../models/dslModel"; /** - * This class contains endpoint definition about companies. + * This class contains endpoint definition about DSLs. * * @history * | Author | Action Performed | Data | @@ -14,12 +13,26 @@ import * @license MIT * */ -export default class DslRouter { +class DSLRouter { - private router : express.Router = express.Router(); - private dslModel = new DSLModel(); + /** + * @description Express router. + */ + private router : express.Router; + /** + * @description DSL' model. + */ + private dslModel : DSLModel; + + /** + * @description Complete constructor. + */ constructor() { + + this.router = express.Router(); + this.dslModel = new DSLModel(); + this.router.get( "/companies/:company_id/dsl", this.getAllDSL); @@ -37,10 +50,24 @@ export default class DslRouter { this.removeDSL); } + /** + * @description Return the Express router. + * @returns {express.Router} The Express router. + */ public getRouter() : express.Router { return this.router; } + /** + * @description Get the DSL represented by the id contained in + * the request. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ private getOneDSL(request : express.Request, response : express.Response) : void { this.dslModel @@ -54,11 +81,21 @@ export default class DslRouter { .status(404) .json({ done: false, - message: "Cannot find the request dsl" + message: "Cannot find the requested DSL" }); }); } + /** + * @description Get the database represented by the id contained in + * the request. + * @param request The express request. + * See the official + * documentation for more details. + * @param result The express response object. + * See the official + * documentation for more details. + */ private getAllDSL(request : express.Request, response : express.Response) : void { this.dslModel @@ -67,17 +104,26 @@ export default class DslRouter { response .status(200) .json(data); - }, function (error : Object) : void { + }, function (error : Error) : void { response .status(404) .json({ done: false, - message: "Cannot find the dsl" + message: "Cannot find the DSLs" }); }); } - + /** + * @description Update the dsl represented by the id contained in + * the request. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ private updateDSL(request : express.Request, response : express.Response) : void { this.dslModel @@ -97,6 +143,16 @@ export default class DslRouter { }); } + /** + * @description Remove the dsl represented by the id contained in + * the request. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ private removeDSL(request : express.Request, response : express.Response) : void { this.dslModel @@ -116,7 +172,15 @@ export default class DslRouter { }); } - + /** + * @description Create a new DSL. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ private createDSL(request : express.Request, response : express.Response) : void { this.dslModel @@ -137,3 +201,4 @@ export default class DslRouter { } } +export default DSLRouter; diff --git a/src/routes/userRouter.ts b/src/routes/userRouter.ts index 3bac7fa..ef7eb18 100644 --- a/src/routes/userRouter.ts +++ b/src/routes/userRouter.ts @@ -1 +1 @@ -import * as express from "express"; import {UserModel} from "../models/userModel"; import {AuthenticationChecker} from "../lib/AuthenticationChecker"; import {LevelChecker} from "../lib/LevelChecker"; /** * This class contains endpoint definition about companies. * * @history * | Author | Action Performed | Data | * | --- | --- | --- | * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | * * @author Emanuele Carraro * @license MIT * */ export default class UserRouter { private router : express.Router = express.Router(); private userModel = new UserModel(); private authCheck = new AuthenticationChecker(); private checkOwner = new LevelChecker( ["OWNER", "SUPERADMIN"]); constructor() { this.router.get( "/companies/:company_id/users", this.checkOwner.check, this.getAllUsers); this.router.get( "/companies/:company_id/users/:user_id", this.getOneUser); // FIXME: che tipo di check deve essere fatto qui? this.router.post( "/users/:user_id", this.createUser); this.router.put( "/companies/:companies_id/users/:user_id", this.checkOwner.checkWithIDSkip, this.updateUser); this.router.delete( "/companies/:companies_id/users/:user_id", this.checkOwner.checkWithIDSkip, this.removeUser); } public getRouter() : express.Router { return this.router; } private login(request : express.Request, response : express.Response) : void { this.authCheck .login(request, response) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response .status(404) .json({ done: false, message: "Cannot login" }); }); } private getOneUser(request : express.Request, response : express.Response) : void { this.userModel .getOne(request.params.user_id) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response .status(404) .json({ done: false, message: "Cannot find the request dsl" }); }); } private getAllUsers(request : express.Request, response : express.Response) : void { this.userModel .getAll() .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response .status(404) .json({ done: false, message: "Cannot find the dsl" }); }); } private updateUser(request : express.Request, response : express.Response) : void { this.userModel .update(request.params.user_id, request.body) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot modify the dsl" }); }); } private removeUser(request : express.Request, response : express.Response) : void { this.userModel .remove(request.params.user_id) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot remove the databases" }); }); } private createUser(request : express.Request, response : express.Response) : void { this.userModel .create(request.body) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot create the databases" }); }); } } \ No newline at end of file +import * as express from "express"; import UserModel from "../models/userModel"; import AuthenticationChecker from "../lib/authenticationChecker"; import LevelChecker from "../lib/levelChecker"; /** * This class contains endpoint definition about users. * * @history * | Author | Action Performed | Data | * | --- | --- | --- | * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | * * @author Emanuele Carraro * @license MIT * */ class UserRouter { /** * * @description Express router. */ private router : express.Router; /** * @description User's model. */ private userModel : UserModel; /** * @description Authentication checker. */ private authCheck : AuthenticationChecker; /** * @description Level checker * @type {LevelChecker} */ private checkOwner : LevelChecker; /** * @description Complete constructor. Here we initialize user's routes. */ constructor() { this.router = express.Router(); this.userModel = new UserModel(); this.authCheck = new AuthenticationChecker(); this.checkOwner = new LevelChecker( ["OWNER", "SUPERADMIN"]); this.router.get( "/companies/:company_id/users", this.checkOwner.check, this.getAllUsers); this.router.get( "/companies/:company_id/users/:user_id", this.getOneUser); // FIXME: che tipo di check deve essere fatto qui? this.router.post( "/users/:user_id", this.createUser); this.router.put( "/companies/:companies_id/users/:user_id", this.checkOwner.checkWithIDSkip, this.updateUser); this.router.delete( "/companies/:companies_id/users/:user_id", this.checkOwner.checkWithIDSkip, this.removeUser); } /** * @description Return the Express router. * @returns {express.Router} The Express router. */ public getRouter() : express.Router { return this.router; } /** * @description Perform the user's login. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private login(request : express.Request, response : express.Response) : void { this.authCheck .login(request, response) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Error) : void { response .status(404) .json({ done: false, message: "Cannot login" }); }); } /** * @description Get the user represented by the id contained in * the request. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private getOneUser(request : express.Request, response : express.Response) : void { this.userModel .getOne(request.params.user_id) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Error) : void { response .status(404) .json({ done: false, message: "Cannot find the requested user" }); }); } /** * @description Get all the users. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private getAllUsers(request : express.Request, response : express.Response) : void { this.userModel .getAll() .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response .status(404) .json({ done: false, message: "Cannot find the user" }); }); } /** * @description Update the user represented by the id contained in * the request. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private updateUser(request : express.Request, response : express.Response) : void { this.userModel .update(request.params.user_id, request.body) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot modify the user" }); }); } /** * @description Remove the user represented by the id contained in * the request. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private removeUser(request : express.Request, response : express.Response) : void { this.userModel .remove(request.params.user_id) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot remove the user" }); }); } /** * @description Create a new user. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private createUser(request : express.Request, response : express.Response) : void { this.userModel .create(request.body) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot create the user" }); }); } } export default UserRouter; \ No newline at end of file From 9ad03ce8af99fb488ecffdcaf528b1f42ca9afc5 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Fri, 13 May 2016 16:15:55 +0200 Subject: [PATCH 118/157] Resolve errors --- src/routes/databaseRouter.ts | 2 +- src/routes/dslRouter.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 177373f..6719bd4 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -1,6 +1,6 @@ import * as express from "express"; import DatabaseModel from "../models/databaseModel"; -import LevelChecker from "../lib/LevelChecker"; +import LevelChecker from "../lib/levelChecker"; /* import authentication checker */ /** diff --git a/src/routes/dslRouter.ts b/src/routes/dslRouter.ts index 2d299be..e9ed8c4 100644 --- a/src/routes/dslRouter.ts +++ b/src/routes/dslRouter.ts @@ -1,6 +1,6 @@ import * as express from "express"; import DSLModel from "../models/dslModel"; -import LevelChecker from "../lib/LevelChecker"; +import LevelChecker from "../lib/levelChecker"; /** * This class contains endpoint definition about DSLs. * From 0016bf11aafe29457d87c1bffc8f61146a153cf6 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Fri, 13 May 2016 16:21:21 +0200 Subject: [PATCH 119/157] Resolve Lint errors --- src/lib/authenticationChecker.ts | 3 +- src/models/databaseModel.ts | 50 ++++++++++++++++---------------- test/routes/companyRouterTest.ts | 3 +- 3 files changed, 29 insertions(+), 27 deletions(-) diff --git a/src/lib/authenticationChecker.ts b/src/lib/authenticationChecker.ts index 1bb54a5..f503261 100644 --- a/src/lib/authenticationChecker.ts +++ b/src/lib/authenticationChecker.ts @@ -96,7 +96,8 @@ class AuthenticationChecker { if (!token) { // Token not found this.responseTokenNotFound(response); } else { - jwt.verify(token, this.secret, function (err, decoded) { + jwt.verify(token, this.secret, + function (err : Error, decoded : Object) : void { if (err) { // Authentication failed this.responseAuthenticationFailed(response); } else { // Success! diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 82a0207..a2480a5 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -92,17 +92,6 @@ class DatabaseModel extends Model { }); } - /** - * Method used for invoke the base class create method from a callback - * function. - * @param jsonData Data of the database. - * @returns {Promise} - * Promise with the error or the saved data - */ - private superCreate(jsonData : Object) : Promise { - return super.create(jsonData) - } - /** * @description Update the stated Company databases. * @param _id The id of the Company. @@ -120,25 +109,12 @@ class DatabaseModel extends Model { jsonData["password"], jsonData["dbName"] ) - .then(function (collections : Array) { + .then(function (collections : Array) : void { jsonData["collections"] = collections; self.superUpdate(_id, jsonData); }) } - /** - * Method used for invoke the base class update method from a callback - * function. - * @param _id The id of the company - * @param jsonData Data of the database. - * @returns {Promise} - * Promise with the error or the saved data - */ - private superUpdate(_id : string, jsonData : Object) : - Promise { - return super.update(_id, jsonData); - } - /** * @description Get the database's schema. * @returns {"mongoose".Schema} The schema. @@ -201,6 +177,30 @@ class DatabaseModel extends Model { }); }); } + + /** + * Method used for invoke the base class create method from a callback + * function. + * @param jsonData Data of the database. + * @returns {Promise} + * Promise with the error or the saved data + */ + private superCreate(jsonData : Object) : Promise { + return super.create(jsonData) + } + + /** + * Method used for invoke the base class update method from a callback + * function. + * @param _id The id of the company + * @param jsonData Data of the database. + * @returns {Promise} + * Promise with the error or the saved data + */ + private superUpdate(_id : string, jsonData : Object) : + Promise { + return super.update(_id, jsonData); + } } export default DatabaseModel; diff --git a/test/routes/companyRouterTest.ts b/test/routes/companyRouterTest.ts index 8403d59..83ff772 100644 --- a/test/routes/companyRouterTest.ts +++ b/test/routes/companyRouterTest.ts @@ -29,4 +29,5 @@ describe("DatabaseRouter", () => { }); }); */ -}); \ No newline at end of file +}); + From 44d2cfd94bb1980070705a8ef8f6be9c324946cf Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Fri, 13 May 2016 16:58:59 +0200 Subject: [PATCH 120/157] Add documentation --- src/models/mongooseConnection.ts | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/models/mongooseConnection.ts b/src/models/mongooseConnection.ts index 86fd35e..10fcabd 100644 --- a/src/models/mongooseConnection.ts +++ b/src/models/mongooseConnection.ts @@ -16,7 +16,17 @@ import MongoConnection from "../config/mongoConnection"; import ConfigurationChooser from "../config/index"; import Configuration from "../config/configuration"; -export class MongooseConnection { +/** + * This is a class used for connect to the MongoDB database of the application. + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Matteo Di Pirro | Create class | 04/05/2016 | + * + * @author Matteo Di Pirro + * @license MIT + */ +class MongooseConnection { /** * @description Connection to the db */ From 953e18c69c276de4dde455e49cdcb75d26311f7f Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Fri, 13 May 2016 17:03:25 +0200 Subject: [PATCH 121/157] Resolve lint error --- src/routes/userRoute.ts | 251 +++++++++++++++++++++++++++++++++++++++ src/routes/userRouter.ts | 1 - 2 files changed, 251 insertions(+), 1 deletion(-) create mode 100644 src/routes/userRoute.ts delete mode 100644 src/routes/userRouter.ts diff --git a/src/routes/userRoute.ts b/src/routes/userRoute.ts new file mode 100644 index 0000000..277c1f4 --- /dev/null +++ b/src/routes/userRoute.ts @@ -0,0 +1,251 @@ +import * as express from "express"; +import UserModel from "../models/userModel"; +import AuthenticationChecker from "../lib/authenticationChecker"; +import LevelChecker from "../lib/levelChecker"; + +/** + * This class contains endpoint definition about users. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | + * + * @author Emanuele Carraro + * @license MIT + * + */ +class UserRouter { + + /** + * * @description Express router. + */ + private router : express.Router; + + /** + * @description User's model. + */ + private userModel : UserModel; + + /** + * @description Authentication checker. + */ + private authCheck : AuthenticationChecker; + + /** + * @description Level checker + * @type {LevelChecker} + */ + private checkOwner : LevelChecker; + + /** + * @description Complete constructor. Here we initialize user's routes. + */ + constructor() { + + this.router = express.Router(); + this.userModel = new UserModel(); + this.authCheck = new AuthenticationChecker(); + this.checkOwner = new LevelChecker( ["OWNER", "SUPERADMIN"]); + + this.router.get( + "/companies/:company_id/users", + this.checkOwner.check, + this.getAllUsers); + this.router.get( + "/companies/:company_id/users/:user_id", + this.getOneUser); + + // FIXME: che tipo di check deve essere fatto qui? + this.router.post( + "/users/:user_id", + this.createUser); + + this.router.put( + "/companies/:companies_id/users/:user_id", + this.checkOwner.checkWithIDSkip, + this.updateUser); + this.router.delete( + "/companies/:companies_id/users/:user_id", + this.checkOwner.checkWithIDSkip, + this.removeUser); + } + + /** + * @description Return the Express router. + * @returns {express.Router} The Express router. + */ + public getRouter() : express.Router { + return this.router; + } + + /** + * @description Perform the user's login. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ + private login(request : express.Request, + response : express.Response) : void { + this.authCheck + .login(request, response) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Error) : void { + response + .status(404) + .json({ + done: false, + message: "Cannot login" + }); + }); + } + + /** + * @description Get the user represented by the id contained in + * the request. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ + private getOneUser(request : express.Request, + response : express.Response) : void { + this.userModel + .getOne(request.params.user_id) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Error) : void { + response + .status(404) + .json({ + done: false, + message: "Cannot find the requested user" + }); + }); + } + + /** + * @description Get all the users. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ + private getAllUsers(request : express.Request, + response : express.Response) : void { + this.userModel + .getAll() + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + .status(404) + .json({ + done: false, + message: "Cannot find the user" + }); + }); + } + + /** + * @description Update the user represented by the id contained in + * the request. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ + private updateUser(request : express.Request, + response : express.Response) : void { + this.userModel + .update(request.params.user_id, request.body) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot modify the user" + }); + }); + } + + /** + * @description Remove the user represented by the id contained in + * the request. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ + private removeUser(request : express.Request, + response : express.Response) : void { + this.userModel + .remove(request.params.user_id) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot remove the user" + }); + }); + } + + /** + * @description Create a new user. + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ + private createUser(request : express.Request, + response : express.Response) : void { + this.userModel + .create(request.body) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + // Todo : set the status + .status(404) + .json({ + done: false, + message: "Cannot create the user" + }); + }); + } +} + +export default UserRouter; diff --git a/src/routes/userRouter.ts b/src/routes/userRouter.ts deleted file mode 100644 index ef7eb18..0000000 --- a/src/routes/userRouter.ts +++ /dev/null @@ -1 +0,0 @@ -import * as express from "express"; import UserModel from "../models/userModel"; import AuthenticationChecker from "../lib/authenticationChecker"; import LevelChecker from "../lib/levelChecker"; /** * This class contains endpoint definition about users. * * @history * | Author | Action Performed | Data | * | --- | --- | --- | * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | * * @author Emanuele Carraro * @license MIT * */ class UserRouter { /** * * @description Express router. */ private router : express.Router; /** * @description User's model. */ private userModel : UserModel; /** * @description Authentication checker. */ private authCheck : AuthenticationChecker; /** * @description Level checker * @type {LevelChecker} */ private checkOwner : LevelChecker; /** * @description Complete constructor. Here we initialize user's routes. */ constructor() { this.router = express.Router(); this.userModel = new UserModel(); this.authCheck = new AuthenticationChecker(); this.checkOwner = new LevelChecker( ["OWNER", "SUPERADMIN"]); this.router.get( "/companies/:company_id/users", this.checkOwner.check, this.getAllUsers); this.router.get( "/companies/:company_id/users/:user_id", this.getOneUser); // FIXME: che tipo di check deve essere fatto qui? this.router.post( "/users/:user_id", this.createUser); this.router.put( "/companies/:companies_id/users/:user_id", this.checkOwner.checkWithIDSkip, this.updateUser); this.router.delete( "/companies/:companies_id/users/:user_id", this.checkOwner.checkWithIDSkip, this.removeUser); } /** * @description Return the Express router. * @returns {express.Router} The Express router. */ public getRouter() : express.Router { return this.router; } /** * @description Perform the user's login. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private login(request : express.Request, response : express.Response) : void { this.authCheck .login(request, response) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Error) : void { response .status(404) .json({ done: false, message: "Cannot login" }); }); } /** * @description Get the user represented by the id contained in * the request. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private getOneUser(request : express.Request, response : express.Response) : void { this.userModel .getOne(request.params.user_id) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Error) : void { response .status(404) .json({ done: false, message: "Cannot find the requested user" }); }); } /** * @description Get all the users. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private getAllUsers(request : express.Request, response : express.Response) : void { this.userModel .getAll() .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response .status(404) .json({ done: false, message: "Cannot find the user" }); }); } /** * @description Update the user represented by the id contained in * the request. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private updateUser(request : express.Request, response : express.Response) : void { this.userModel .update(request.params.user_id, request.body) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot modify the user" }); }); } /** * @description Remove the user represented by the id contained in * the request. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private removeUser(request : express.Request, response : express.Response) : void { this.userModel .remove(request.params.user_id) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot remove the user" }); }); } /** * @description Create a new user. * @param request The express request. * See the official * documentation for more details. * @param response The express response object. * See the official * documentation for more details. */ private createUser(request : express.Request, response : express.Response) : void { this.userModel .create(request.body) .then(function (data : Object) : void { response .status(200) .json(data); }, function (error : Object) : void { response // Todo : set the status .status(404) .json({ done: false, message: "Cannot create the user" }); }); } } export default UserRouter; \ No newline at end of file From 47a2705ee0ac3788acb62cb3176a210f733917d3 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Sat, 14 May 2016 10:21:05 +0200 Subject: [PATCH 122/157] Add API's doc --- src/models/userModel.ts | 2 +- src/routes/userRoute.ts | 99 +++++++++++++++++++++++++++++++++++++++-- 2 files changed, 96 insertions(+), 5 deletions(-) diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 6f8ad94..2605b58 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -88,7 +88,7 @@ class UserModel extends Model { this.model.findOne( {username: username}, function (error : Object, - user : mongoose.Model) : void { + user : mongoose.Model) : void { if (error) { reject(error); } else { diff --git a/src/routes/userRoute.ts b/src/routes/userRoute.ts index 277c1f4..64568ac 100644 --- a/src/routes/userRoute.ts +++ b/src/routes/userRoute.ts @@ -48,25 +48,29 @@ class UserRouter { this.authCheck = new AuthenticationChecker(); this.checkOwner = new LevelChecker( ["OWNER", "SUPERADMIN"]); + // FIXME: QUESTA NON C'È NELLE API DEFINITE this.router.get( "/companies/:company_id/users", this.checkOwner.check, this.getAllUsers); + + // FIXME: QUESTA NON C'È NELLE API DEFINITE this.router.get( - "/companies/:company_id/users/:user_id", + "/companies/:company_id/users/:user_id/", this.getOneUser); // FIXME: che tipo di check deve essere fatto qui? this.router.post( - "/users/:user_id", + "/companies/:company_id/users", this.createUser); this.router.put( - "/companies/:companies_id/users/:user_id", + "/companies/:company_id/users/:user_id/credentials", this.checkOwner.checkWithIDSkip, this.updateUser); + this.router.delete( - "/companies/:companies_id/users/:user_id", + "/companies/:company_id/users/:user_id", this.checkOwner.checkWithIDSkip, this.removeUser); } @@ -249,3 +253,90 @@ class UserRouter { } export default UserRouter; + +/** + * @api {get} /api/companies/:company_id/users Read data of an User + * @apiVersion 0.1.0 + * @apiName createUser + * @apiGroup User + * @apiPermission OWNER + * + * @apiDescription Use this request to insert a new user in a stated company. + * + * @apiParam {Number} company_id The Company's ID. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/5741/users + * + * @apiSuccess {Number} id The User's ID. + * + * @apiError NoAccessRight Only authenticated Owners can access the data. + * @apiError CannotCreateTheUser It was impossible to create the user. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot create the user" + * } + */ + +/** + * @api {put} /api/companies/:company_id/users/:user_id/credentials + * Update credentials of an user. + * @apiVersion 0.1.0 + * @apiName updateUser + * @apiGroup User + * @apiPermission GUEST + * + * @apiDescription Use this request to update your access credentials. + * + * @apiParam {Number} company_id The Company's ID. + * @apiParam {Number} user_id The user's ID. + * @apiParam {string} username The new user's email address. + * @apiParam {string} password The new user's password. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/5741/users/12054/credentials + * + * @apiSuccess {Number} id The User's ID. + * @apiSuccess {string} username The user's new username. + * @apiSuccess {string} password The user's new password. + * + * @apiError CannotModifyTheUser It was impossible to update the user's data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot modify the user" + * } + */ + +/** + * @api {delete} /api//companies/:company_id/users/:user_id Remove an user. + * @apiVersion 0.1.0 + * @apiName removeUser + * @apiGroup User + * @apiPermission OWNER + * + * @apiDescription Use this request to remove an user from a stated Company. + * + * @apiParam {Number} company_id The Company's ID. + * @apiParam {Number} user_id The user's ID. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/5741/users/12054/ + * + * @apiSuccess {Number} id The User's ID. + * + * @apiError NoAccessRight Only authenticated Owners can access the data. + * @apiError CannotRemoveTheUser It was impossible to remove the user. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot remove the user" + * } + */ From dd7a846084d41a2a4cf2251fdd1c9ed18dafc66e Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Sat, 14 May 2016 11:09:03 +0200 Subject: [PATCH 123/157] Add API's docs --- src/routes/companyRouter.ts | 152 ++++++++++++++++++++++++++++++- src/routes/userRoute.ts | 175 ++++++++++++++++++------------------ 2 files changed, 239 insertions(+), 88 deletions(-) diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index a924a43..4bda6db 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -97,6 +97,34 @@ class CompanyRouter { * See the official * documentation for more details. */ + /** + * @api {get} /api/companies/:company_id + * Get the data of a stated Company. + * @apiVersion 0.1.0 + * @apiName getAllCompanies + * @apiGroup Company + * @apiPermission GUEST + * + * @apiDescription Use this request to get the data of a specific Company. + * + * @apiParam {Number} company_id The ID of the Company + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540 + * + * @apiSuccess {string} name The name of the company. + * @apiSuccess {string} owner The company owner's email address. + * + * @apiError CannotFindTheCompany It was impossible to find the requested + * Company. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot get the Company" + * } + */ private getOneCompany(request : express.Request, result : express.Response) : void { this.companyModel @@ -124,6 +152,38 @@ class CompanyRouter { * See the official * documentation for more details. */ + /** + * @api {get} /api/admin/companies + * Get the data of all the companies subscribed to MaaS. + * @apiVersion 0.1.0 + * @apiName getAllCompanies + * @apiGroup Company + * @apiPermission SUPERADMIN + * + * @apiDescription Use this request to get the data of all the companies + * subscribed to MaaS. They are stored in an array. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/company_id + * + * @apiSuccess {array} Please take note that the 'name' and 'owner' + * fields are + * stored in an array. Each element of this array represents a company + * subscribed to MaaS. + * @apiSuccess {string} name The name of the company. + * @apiSuccess {string} owner The company owner's email address. + * + * @apiError NoAccessRight Only authenticated Super admins can access + * the data. + * @apiError CannotFindAnyCompany It was impossible to find any Company. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot get companies data" + * } + */ private getAllCompanies(request : express.Request, result : express.Response) : void { this.companyModel @@ -152,6 +212,33 @@ class CompanyRouter { * See the official * documentation for more details. */ + /** + * @api {put} /api/companies + * Create a new Company. + * @apiVersion 0.1.0 + * @apiName updateCompany + * @apiGroup Company + * + * @apiDescription Use this request to create a new Company. + * + * @apiParam {string} name The name of the Company. + * @apiParam {string} owner The ID of the owner of the Company. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540 + * + * @apiSuccess {Number} id The id of the Company. + * + * @apiError CannotCreateTheCompany It was impossible to find the requested + * Company. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot save the Company" + * } + */ private createCompany(request : express.Request, result : express.Response) : void { this.companyModel @@ -172,7 +259,7 @@ class CompanyRouter { } /** - * Update a steted Company. + * Update a stated Company. * @param request The express request. * See the official * documentation for more details. @@ -180,6 +267,40 @@ class CompanyRouter { * See the official * documentation for more details. */ + /** + * @api {put} /api/companies/:company_id + * Update the data of a specific Company. + * @apiVersion 0.1.0 + * @apiName updateCompany + * @apiGroup Company + * @apiPermission ADMIN + * + * @apiDescription Use this request to update the data of a specific + * Company. + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {string} name The name of the Company. + * @apiParam {string} owner The ID of the owner of the Company. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540 + * + * @apiSuccess {Number} id The id of the Company. + * @apiSuccess {string} name The new name of the company. + * @apiSuccess {string} owner The new company owner's email address. + * + * @apiError CannotFindTheCompany It was impossible to find the requested + * Company. + * @apiError NoAccessRight Only authenticated Admins can access + * the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot update the Company" + * } + */ private updateCompany(request : express.Request, result : express.Response) : void { this.companyModel @@ -207,6 +328,35 @@ class CompanyRouter { * See the official * documentation for more details. */ + /** + * @api {delete} /api/companies/:company_id + * Delete the data of a specific Company. + * @apiVersion 0.1.0 + * @apiName removeCompany + * @apiGroup Company + * @apiPermission OWNER + * + * @apiDescription Use this request to remove a specific Company. + * + * @apiParam {Number} company_id The ID of the Company. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540 + * + * @apiSuccess {Number} id The id of the removed Company. + * + * @apiError CannotFindTheCompany It was impossible to find the requested + * Company. + * @apiError NoAccessRight Only authenticated Owners can access + * the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot remove the Company" + * } + */ private remove(request : express.Request, result : express.Response) : void { this.companyModel diff --git a/src/routes/userRoute.ts b/src/routes/userRoute.ts index 64568ac..bf16dd7 100644 --- a/src/routes/userRoute.ts +++ b/src/routes/userRoute.ts @@ -175,6 +175,38 @@ class UserRouter { * See the official * documentation for more details. */ + /** + * @api {put} /api/companies/:company_id/users/:user_id/credentials + * Update credentials of an user. + * @apiVersion 0.1.0 + * @apiName updateUser + * @apiGroup User + * @apiPermission GUEST + * + * @apiDescription Use this request to update your access credentials. + * + * @apiParam {Number} company_id The Company's ID. + * @apiParam {Number} user_id The user's ID. + * @apiParam {string} username The new user's email address. + * @apiParam {string} password The new user's password. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/5741/users/12054/credentials + * + * @apiSuccess {Number} id The User's ID. + * @apiSuccess {string} username The user's new username. + * @apiSuccess {string} password The user's new password. + * + * @apiError CannotModifyTheUser It was impossible to update the user's + * data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot modify the user" + * } + */ private updateUser(request : express.Request, response : express.Response) : void { this.userModel @@ -204,6 +236,34 @@ class UserRouter { * See the official * documentation for more details. */ + /** + * @api {delete} /api/companies/:company_id/users/:user_id Remove an user. + * @apiVersion 0.1.0 + * @apiName removeUser + * @apiGroup User + * @apiPermission OWNER + * + * @apiDescription Use this request to remove an user from a stated Company. + * + * @apiParam {Number} company_id The Company's ID. + * @apiParam {Number} user_id The user's ID. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/5741/users/12054/ + * + * @apiSuccess {Number} id The User's ID. + * + * @apiError NoAccessRight Only authenticated Owners can access the data. + * @apiError CannotRemoveTheUser It was impossible to remove the user. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot remove the user" + * } + */ + private removeUser(request : express.Request, response : express.Response) : void { this.userModel @@ -232,6 +292,34 @@ class UserRouter { * See the official * documentation for more details. */ + /** + * @api {get} /api/companies/:company_id/users Read data of an User + * @apiVersion 0.1.0 + * @apiName createUser + * @apiGroup User + * @apiPermission OWNER + * + * @apiDescription Use this request to insert a new user in a stated + * company. + * + * @apiParam {Number} company_id The Company's ID. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/5741/users + * + * @apiSuccess {Number} id The User's ID. + * + * @apiError NoAccessRight Only authenticated Owners can access the data. + * @apiError CannotCreateTheUser It was impossible to create the user. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot create the user" + * } + */ + private createUser(request : express.Request, response : express.Response) : void { this.userModel @@ -253,90 +341,3 @@ class UserRouter { } export default UserRouter; - -/** - * @api {get} /api/companies/:company_id/users Read data of an User - * @apiVersion 0.1.0 - * @apiName createUser - * @apiGroup User - * @apiPermission OWNER - * - * @apiDescription Use this request to insert a new user in a stated company. - * - * @apiParam {Number} company_id The Company's ID. - * - * @apiExample Example usage: - * curl -i http://maas.com/api/companies/5741/users - * - * @apiSuccess {Number} id The User's ID. - * - * @apiError NoAccessRight Only authenticated Owners can access the data. - * @apiError CannotCreateTheUser It was impossible to create the user. - * - * @apiErrorExample Response (example): - * HTTP/1.1 404 - * { - * "done": false, - * "error": "Cannot create the user" - * } - */ - -/** - * @api {put} /api/companies/:company_id/users/:user_id/credentials - * Update credentials of an user. - * @apiVersion 0.1.0 - * @apiName updateUser - * @apiGroup User - * @apiPermission GUEST - * - * @apiDescription Use this request to update your access credentials. - * - * @apiParam {Number} company_id The Company's ID. - * @apiParam {Number} user_id The user's ID. - * @apiParam {string} username The new user's email address. - * @apiParam {string} password The new user's password. - * - * @apiExample Example usage: - * curl -i http://maas.com/api/companies/5741/users/12054/credentials - * - * @apiSuccess {Number} id The User's ID. - * @apiSuccess {string} username The user's new username. - * @apiSuccess {string} password The user's new password. - * - * @apiError CannotModifyTheUser It was impossible to update the user's data. - * - * @apiErrorExample Response (example): - * HTTP/1.1 404 - * { - * "done": false, - * "error": "Cannot modify the user" - * } - */ - -/** - * @api {delete} /api//companies/:company_id/users/:user_id Remove an user. - * @apiVersion 0.1.0 - * @apiName removeUser - * @apiGroup User - * @apiPermission OWNER - * - * @apiDescription Use this request to remove an user from a stated Company. - * - * @apiParam {Number} company_id The Company's ID. - * @apiParam {Number} user_id The user's ID. - * - * @apiExample Example usage: - * curl -i http://maas.com/api/companies/5741/users/12054/ - * - * @apiSuccess {Number} id The User's ID. - * - * @apiError NoAccessRight Only authenticated Owners can access the data. - * @apiError CannotRemoveTheUser It was impossible to remove the user. - * - * @apiErrorExample Response (example): - * HTTP/1.1 404 - * { - * "done": false, - * "error": "Cannot remove the user" - * } - */ From a7f788b4e902a1f84dbad625a3536f512b50dd76 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Sat, 14 May 2016 12:00:57 +0200 Subject: [PATCH 124/157] Add more API's doc --- src/routes/companyRouter.ts | 2 +- src/routes/databaseRouter.ts | 207 +++++++++++++++++++++++++++++++++++ src/routes/userRoute.ts | 2 +- 3 files changed, 209 insertions(+), 2 deletions(-) diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index 4bda6db..b76ecac 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -213,7 +213,7 @@ class CompanyRouter { * documentation for more details. */ /** - * @api {put} /api/companies + * @api {post} /api/companies * Create a new Company. * @apiVersion 0.1.0 * @apiName updateCompany diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 6719bd4..b48e895 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -62,6 +62,7 @@ class DatabaseRouter { "/companies/:company_id/databases/:database_id", this.checkMember.check, this.getOneDatabase); + // TODO getCollections this.router.post( "/companies/:company_id/databases", this.checkAdmin.check, @@ -94,6 +95,47 @@ class DatabaseRouter { * See the official * documentation for more details. */ + /** + * @api {get} /api/companies/:company_id/databases/:database_id + * Get a stated database. + * @apiVersion 0.1.0 + * @apiName getOneDatabase + * @apiGroup Database + * @apiPermission ADMIN + * + * @apiDescription Use this request to get the data of an existing + * database. + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} database_id The ID of the database to return. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540/databases/5230 + * + * @apiSuccess {Number} company_id The ID of the Company. + * @apiSuccess {Number} database_id The ID of the database to update. + * @apiSuccess {string} username The username of the used used for read + * data from the database. + * @apiSuccess {string} password The password of the used used for read + * data from the database. + * @apiSuccess {string} host The host of the database. + * @apiSuccess {string} name The name of the database. + * @apiSuccess {Number} port The port of the database. + * + * @apiError CannotFindTheDatabase It was impossible to find the requested + * database. + * @apiError CannotFindTheCompany It was impossible to find the requested + * company. + * @apiError NoAccessRight Only authenticated admins can access + * the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot update the database" + * } + */ private getOneDatabase(request : express.Request, result : express.Response) : void { this.databaseModel @@ -121,6 +163,42 @@ class DatabaseRouter { * See the official * documentation for more details. */ + /** + * @api {put} /api/companies/:company_id/databases + * Return a list of all the Company's databases + * @apiVersion 0.1.0 + * @apiName getAllDatabase + * @apiGroup Database + * @apiPermission MEMBER + * + * @apiDescription Use this request to get a list of the accessible + * database of the stated Company + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} database_id The ID of the database to update. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540/databases/5230 + * + * @apiSuccess {JSON[]} databases Please take note that this request + * return an array which contains the requested data. + * @apiSuccess {Number} id Database's ID. + * @apiSuccess {string} Database's name. + * + * @apiError CannotFindTheDatabase It was impossible to find the requested + * database. + * @apiError CannotFindTheCompany It was impossible to find the requested + * company. + * @apiError NoAccessRight Only authenticated members can access + * the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot find the database" + * } + */ private getAllDatabases(request : express.Request, result : express.Response) : void { this.databaseModel @@ -149,6 +227,55 @@ class DatabaseRouter { * See the official * documentation for more details. */ + /** + * @api {put} /api/companies/:company_id/databases/:database_id + * Update a stated database. + * @apiVersion 0.1.0 + * @apiName updateDatabase + * @apiGroup Database + * @apiPermission ADMIN + * + * @apiDescription Use this request to update an existing database. + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} database_id The ID of the database to update. + * @apiParam {string} username The username of the used used for read + * data from the database. + * @apiParam {string} password The password of the used used for read + * data from the database. + * @apiParam {string} host The host of the database. + * @apiParam {string} name The name of the database. + * @apiParam {Number} port The port of the database. + * @apiParam {JSON[]} collections Array containing the collections of + * the database. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540/databases/5230 + * + * @apiSuccess {Number} company_id The ID of the Company. + * @apiSuccess {Number} database_id The ID of the database to update. + * @apiSuccess {string} username The username of the used used for read + * data from the database. + * @apiSuccess {string} password The password of the used used for read + * data from the database. + * @apiSuccess {string} host The host of the database. + * @apiSuccess {string} name The name of the database. + * @apiSuccess {Number} port The port of the database. + * + * @apiError CannotRemoveTheDatabase It was impossible to find the requested + * database. + * @apiError CannotFindTheCompany It was impossible to find the requested + * company. + * @apiError NoAccessRight Only authenticated admins can access + * the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot update the database" + * } + */ private updateDatabase(request : express.Request, result : express.Response) : void { this.databaseModel @@ -178,6 +305,39 @@ class DatabaseRouter { * See the official * documentation for more details. */ + /** + * @api {delete} /api/companies/:company_id/databases/:database_id + * Update a stated database. + * @apiVersion 0.1.0 + * @apiName removeDatabase + * @apiGroup Database + * @apiPermission ADMIN + * + * @apiDescription Use this request to update an existing database. + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} database_id The ID of the database to remove. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540/databases/5230 + * + * @apiSuccess {Number} company_id The ID of the Company. + * @apiSuccess {Number} database_id The ID of the database to update. + * + * @apiError CannotCreateTheDatabase It was impossible to find the requested + * database. + * @apiError CannotFindTheCompany It was impossible to find the requested + * company. + * @apiError NoAccessRight Only authenticated admins can access + * the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot remove the database" + * } + */ private removeDatabase(request : express.Request, result : express.Response) : void { this.databaseModel @@ -206,6 +366,53 @@ class DatabaseRouter { * See the official * documentation for more details. */ + /** + * @api {post} /api/companies/:company_id/databases/:database_id + * Create a new database. + * @apiVersion 0.1.0 + * @apiName createDatabase + * @apiGroup Database + * @apiPermission ADMIN + * + * @apiDescription Use this request to create a new database. + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} database_id The ID of the database to create. + * @apiParam {string} username The username of the used used for read + * data from the database. + * @apiParam {string} password The password of the used used for read + * data from the database. + * @apiParam {string} host The host of the database. + * @apiParam {string} name The name of the database. + * @apiParam {Number} port The port of the database. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540/databases/5230 + * + * @apiSuccess {Number} company_id The ID of the Company. + * @apiSuccess {Number} database_id The ID of the database to update. + * @apiSuccess {string} username The username of the used used for read + * data from the database. + * @apiSuccess {string} password The password of the used used for read + * data from the database. + * @apiSuccess {string} host The host of the database. + * @apiSuccess {string} name The name of the database. + * @apiSuccess {Number} port The port of the database. + * + * @apiError CannotUpdateTheDatabase It was impossible to find the requested + * database. + * @apiError CannotFindTheCompany It was impossible to find the requested + * company. + * @apiError NoAccessRight Only authenticated admins can access + * the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot create the database" + * } + */ private createDatabase(request : express.Request, result : express.Response) : void { this.databaseModel diff --git a/src/routes/userRoute.ts b/src/routes/userRoute.ts index bf16dd7..f1403f2 100644 --- a/src/routes/userRoute.ts +++ b/src/routes/userRoute.ts @@ -293,7 +293,7 @@ class UserRouter { * documentation for more details. */ /** - * @api {get} /api/companies/:company_id/users Read data of an User + * @api {post} /api/companies/:company_id/users Read data of an User * @apiVersion 0.1.0 * @apiName createUser * @apiGroup User From 1c9c4a43a4f244c0d05452a0c19e962f9ec193ec Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Sat, 14 May 2016 12:25:51 +0200 Subject: [PATCH 125/157] Add api doc title and description --- src/apidoc.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/apidoc.json b/src/apidoc.json index 62707a6..34270c2 100644 --- a/src/apidoc.json +++ b/src/apidoc.json @@ -1,7 +1,7 @@ { - "name": "example", + "name": "MaaS", "version": "0.1.0", - "description": "apiDoc basic example", - "title": "Custom apiDoc browser title", - "url" : "https://api.github.com/v1" + "description": "API for MaaS", + "title": "MaaS: MongoDB as a Service API documentation", + "url" : "http://bugbusterswe.github.io/MaaS/" } From ded89a135fbcc6db0e171576a0121df05217a07b Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Sat, 14 May 2016 13:11:24 +0200 Subject: [PATCH 126/157] Complete API's doc --- src/routes/companyRouter.ts | 7 +- src/routes/databaseRouter.ts | 8 +- src/routes/dslRouter.ts | 175 ++++++++++++++++++++++++++++++++++- src/routes/userRoute.ts | 30 ++++++ 4 files changed, 215 insertions(+), 5 deletions(-) diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index b76ecac..aa8a965 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -107,7 +107,8 @@ class CompanyRouter { * * @apiDescription Use this request to get the data of a specific Company. * - * @apiParam {Number} company_id The ID of the Company + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} user_id The ID of the logged user. * * @apiExample Example usage: * curl -i http://maas.com/api/companies/1540 @@ -163,6 +164,8 @@ class CompanyRouter { * @apiDescription Use this request to get the data of all the companies * subscribed to MaaS. They are stored in an array. * + * @apiParam {Number} user_id The ID of the logged user. + * * @apiExample Example usage: * curl -i http://maas.com/api/companies/company_id * @@ -281,6 +284,7 @@ class CompanyRouter { * @apiParam {Number} company_id The ID of the Company. * @apiParam {string} name The name of the Company. * @apiParam {string} owner The ID of the owner of the Company. + * @apiParam {Number} user_id The ID of the logged user. * * @apiExample Example usage: * curl -i http://maas.com/api/companies/1540 @@ -339,6 +343,7 @@ class CompanyRouter { * @apiDescription Use this request to remove a specific Company. * * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} user_id The ID of the logged user. * * @apiExample Example usage: * curl -i http://maas.com/api/companies/1540 diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index b48e895..14bac4f 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -108,6 +108,7 @@ class DatabaseRouter { * * @apiParam {Number} company_id The ID of the Company. * @apiParam {Number} database_id The ID of the database to return. + * @apiParam {Number} user_id The ID of the logged user. * * @apiExample Example usage: * curl -i http://maas.com/api/companies/1540/databases/5230 @@ -176,6 +177,7 @@ class DatabaseRouter { * * @apiParam {Number} company_id The ID of the Company. * @apiParam {Number} database_id The ID of the database to update. + * @apiParam {Number} user_id The ID of the logged user. * * @apiExample Example usage: * curl -i http://maas.com/api/companies/1540/databases/5230 @@ -239,6 +241,7 @@ class DatabaseRouter { * * @apiParam {Number} company_id The ID of the Company. * @apiParam {Number} database_id The ID of the database to update. + * @apiParam {Number} user_id The ID of the logged user. * @apiParam {string} username The username of the used used for read * data from the database. * @apiParam {string} password The password of the used used for read @@ -317,6 +320,7 @@ class DatabaseRouter { * * @apiParam {Number} company_id The ID of the Company. * @apiParam {Number} database_id The ID of the database to remove. + * @apiParam {Number} user_id The ID of the logged user. * * @apiExample Example usage: * curl -i http://maas.com/api/companies/1540/databases/5230 @@ -367,7 +371,7 @@ class DatabaseRouter { * documentation for more details. */ /** - * @api {post} /api/companies/:company_id/databases/:database_id + * @api {post} /api/companies/:company_id/databases/ * Create a new database. * @apiVersion 0.1.0 * @apiName createDatabase @@ -377,7 +381,7 @@ class DatabaseRouter { * @apiDescription Use this request to create a new database. * * @apiParam {Number} company_id The ID of the Company. - * @apiParam {Number} database_id The ID of the database to create. + * @apiParam {Number} user_id The ID of the logged user. * @apiParam {string} username The username of the used used for read * data from the database. * @apiParam {string} password The password of the used used for read diff --git a/src/routes/dslRouter.ts b/src/routes/dslRouter.ts index e9ed8c4..51629e6 100644 --- a/src/routes/dslRouter.ts +++ b/src/routes/dslRouter.ts @@ -60,6 +60,9 @@ class DSLRouter { "/companies/:company_id/DSLs/:dsl_id", this.checkMember.check, this.removeDSL); + + // TODO DSL execution + // TODO dashboard } /** @@ -80,6 +83,39 @@ class DSLRouter { * See the official * documentation for more details. */ + /** + * @api {get} /api/companies/:company_id/DSLs/:dsl_id + * Get all the DSL specifics accessible from the logged user. + * @apiVersion 0.1.0 + * @apiName getOneDSL + * @apiGroup DSL + * @apiPermission GUEST + * + * @apiDescription Use this request to get the code of a stated specific + * DSL. + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} user_id The ID of the logged user. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540/DSLs/6552/ + * + * @apiSuccess {Number} dsl_id The ID of the specific dsl. + * @apiSuccess {string} code The code of the specific dsl. + * + * @apiError CannotFindTheDSL It was impossible to find the requested + * specific dsl. + * @apiError CannotFindTheCompany It was impossible to find the requested + * company. + * @apiError NoAccessRight Only authenticated members can access the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot find the DSL" + * } + */ private getOneDSL(request : express.Request, response : express.Response) : void { this.dslModel @@ -108,6 +144,40 @@ class DSLRouter { * See the official * documentation for more details. */ + /** + * @api {get} /api/companies/:company_id/DSLs + * Get all the DSL specifics accessible from the logged user. + * @apiVersion 0.1.0 + * @apiName getAllDSL + * @apiGroup DSL + * @apiPermission MEMBER + * + * @apiDescription Use this request to get all the specific dsls + * accessible from the logged user. + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} user_id The ID of the logged user. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540/DSLs/ + * + * @apiSuccess {JSON[]} dsls Please take note that all the data of the + * DSLs are returned in an array. + * @apiSuccess {Number} dsl_id The ID of the specific dsl. + * @apiSuccess {string} code The code of the specific dsl. + * + * @apiError CannotFindTheDSL It was impossible to find the requested + * specific dsl. + * @apiError CannotFindTheCompany It was impossible to find the requested + * company. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot find the DSLs" + * } + */ private getAllDSL(request : express.Request, response : express.Response) : void { this.dslModel @@ -136,6 +206,43 @@ class DSLRouter { * See the official * documentation for more details. */ + /** + * @api {put} /api/companies/:company_id/DSLs/:dsl_id + * Update a stated specific DSL. + * @apiVersion 0.1.0 + * @apiName updateDSL + * @apiGroup DSL + * @apiPermission MEMBER + * + * @apiDescription Use this request to update a stated specific DSL. + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} user_id The ID of the logged user. + * @apiParam {Number} dsl_id The ID of the specific DSL. + * @apiParam {string} code The code of the specific DSL. + * @apiParam {JSON[]} permits Array which contains all the access + * permissions to the specific DSL. In particular, each element have two + * boolean fields, 'write', for writing permits, and 'exec' for the + * execution permits. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540/DSLs/6558/ + * + * @apiSuccess {Number} id The ID of the specific dsl. + * + * @apiError CannotUpdateTheDSL It was impossible to create the specific + * DSL. + * @apiError CannotFindTheCompany It was impossible to find the requested + * company. + * @apiError NoAccessRight Only authenticated members can access the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot update the DSL" + * } + */ private updateDSL(request : express.Request, response : express.Response) : void { this.dslModel @@ -165,6 +272,38 @@ class DSLRouter { * See the official * documentation for more details. */ + /** + * @api {put} /api/companies/:company_id/DSLs/:dsl_id + * Remove a stated specific DSL. + * @apiVersion 0.1.0 + * @apiName removeDSL + * @apiGroup DSL + * @apiPermission MEMBER + * + * @apiDescription Use this request to remove a stated specific DSL. + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} user_id The ID of the logged user. + * @apiParam {Number} dsl_id The ID of the specific DSL. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540/DSLs/6558/ + * + * @apiSuccess {Number} id The ID of the specific DSL. + * + * @apiError CannotRemoveTheDSL It was impossible to create the specific + * DSL. + * @apiError CannotFindTheCompany It was impossible to find the requested + * company. + * @apiError NoAccessRight Only authenticated members can access the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot remove the DSL" + * } + */ private removeDSL(request : express.Request, response : express.Response) : void { this.dslModel @@ -179,7 +318,7 @@ class DSLRouter { .status(404) .json({ done: false, - message: "Cannot remove the databases" + message: "Cannot remove the DSL" }); }); } @@ -193,6 +332,38 @@ class DSLRouter { * See the official * documentation for more details. */ + /** + * @api {post} /api/companies/:company_id/DSLs + * Create a new specific DSL. + * @apiVersion 0.1.0 + * @apiName createDSL + * @apiGroup DSL + * @apiPermission MEMBER + * + * @apiDescription Use this request to create a new specific DSL. + * + * @apiParam {Number} company_id The ID of the Company. + * @apiParam {Number} user_id The ID of the logged user. + * @apiParam {string} code The code of the specific DSL. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/1540/DSLs/ + * + * @apiSuccess {Number} id The ID of the specific dsl. + * + * @apiError CannotCreateTheDSL It was impossible to create the specific + * DSL. + * @apiError CannotFindTheCompany It was impossible to find the requested + * company. + * @apiError NoAccessRight Only authenticated members can access the data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot create the DSL" + * } + */ private createDSL(request : express.Request, response : express.Response) : void { this.dslModel @@ -207,7 +378,7 @@ class DSLRouter { .status(404) .json({ done: false, - message: "Cannot create the databases" + message: "Cannot create the DSL" }); }); } diff --git a/src/routes/userRoute.ts b/src/routes/userRoute.ts index f1403f2..98f4f18 100644 --- a/src/routes/userRoute.ts +++ b/src/routes/userRoute.ts @@ -92,6 +92,33 @@ class UserRouter { * See the official * documentation for more details. */ + /** + * @api {get} /api/login + * USer login. + * @apiVersion 0.1.0 + * @apiName updateUser + * @apiGroup User + * + * @apiDescription Use this request in order to login. + * + * @apiParam {string} username The new user's email address. + * @apiParam {string} password The new user's password. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/5741/users/12054/credentials + * + * @apiSuccess {Number} id The User's ID. + * @apiSuccess {jwt} token Access token. + * + * @apiError CannotFindTheUser It was impossible to find the user. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot find the user" + * } + */ private login(request : express.Request, response : express.Response) : void { this.authCheck @@ -187,6 +214,7 @@ class UserRouter { * * @apiParam {Number} company_id The Company's ID. * @apiParam {Number} user_id The user's ID. + * @apiParam {Number} user_id The ID of the logged user. * @apiParam {string} username The new user's email address. * @apiParam {string} password The new user's password. * @@ -247,6 +275,7 @@ class UserRouter { * * @apiParam {Number} company_id The Company's ID. * @apiParam {Number} user_id The user's ID. + * @apiParam {Number} user_id The ID of the logged user. * * @apiExample Example usage: * curl -i http://maas.com/api/companies/5741/users/12054/ @@ -303,6 +332,7 @@ class UserRouter { * company. * * @apiParam {Number} company_id The Company's ID. + * @apiParam {Number} user_id The ID of the logged user. * * @apiExample Example usage: * curl -i http://maas.com/api/companies/5741/users From 53ebb66903bb57992a761a5c68d3fd1906585ac1 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sat, 14 May 2016 21:22:15 +0200 Subject: [PATCH 127/157] Fixed problems on models to compile --- src/models/databaseModel.ts | 84 ++++++++++++++-------- src/models/userModel.ts | 11 ++- src/routes/{userRoute.ts => userRouter.ts} | 0 3 files changed, 63 insertions(+), 32 deletions(-) rename src/routes/{userRoute.ts => userRouter.ts} (100%) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index a2480a5..4e03e0b 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -78,18 +78,31 @@ class DatabaseModel extends Model { */ public create(jsonData : Object) : Promise { let self : DatabaseModel = this; - this - .getCollections( - jsonData["port"], - jsonData["host"], - jsonData["username"], - jsonData["password"], - jsonData["dbName"] - ) - .then(function (collections : Array) : Promise { - jsonData["collections"] = collections; - return self.superCreate(jsonData); - }); + + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + this + .getCollections( + jsonData["port"], + jsonData["host"], + jsonData["username"], + jsonData["password"], + jsonData["dbName"] + ) + .then(function (collections : Array) : void { + jsonData["collections"] = collections; + self + .superCreate(jsonData) + .then((data : Object) => { + resolve(data); + }, + (error : Object) => { + reject(error); + }); + }); + }); + + } /** @@ -99,20 +112,32 @@ class DatabaseModel extends Model { * @returns {Promise} * Promise with the error or the saved data. */ - public update(_id : string, jsonData : Object) : Promise { + /* Luca Bianco: ho settato in Object il tipo di promise per rimanere + nella stessa linea di derivazione di model */ + public update(_id : string, jsonData : Object) : Promise { let self : DatabaseModel = this; - this - .getCollections( - jsonData["port"], - jsonData["host"], - jsonData["username"], - jsonData["password"], - jsonData["dbName"] - ) - .then(function (collections : Array) : void { - jsonData["collections"] = collections; - self.superUpdate(_id, jsonData); - }) + + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + + this + .getCollections( + jsonData["port"], + jsonData["host"], + jsonData["username"], + jsonData["password"], + jsonData["dbName"] + ) + .then(function (collections : Array) : void { + jsonData["collections"] = collections; + self.superUpdate(_id, jsonData) + .then((data : Object) => { + resolve(data); + }, (error : Object) => { + reject(error); + }); + }) + }); } /** @@ -145,7 +170,8 @@ class DatabaseModel extends Model { * @param username Database's user username. * @param password Database's user password. * @param dbName Database's name. - * @returns {Promise|Promise} Promise generated by a mongoose's query. + * @returns {Promise|Promise} Promise + * generated by a mongoose's query. */ private getCollections(port : string, host : string, username : string, password : string, @@ -194,11 +220,11 @@ class DatabaseModel extends Model { * function. * @param _id The id of the company * @param jsonData Data of the database. - * @returns {Promise} + * @returns {Promise} * Promise with the error or the saved data */ - private superUpdate(_id : string, jsonData : Object) : - Promise { + private superUpdate(_id : string, + jsonData : Object) : Promise { return super.update(_id, jsonData); } } diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 2605b58..76074f9 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -16,6 +16,7 @@ import CustomModel from "./customModelInterface"; */ interface UserDocument extends CustomModel { + _id : string; /** * @description The user's username. */ @@ -40,6 +41,8 @@ interface UserDocument extends CustomModel { * @description The user's level. */ level : string; + + authenticate : (password : string) => boolean; } /** @@ -88,7 +91,7 @@ class UserModel extends Model { this.model.findOne( {username: username}, function (error : Object, - user : mongoose.Model) : void { + user : UserDocument) : void { if (error) { reject(error); } else { @@ -108,7 +111,8 @@ class UserModel extends Model { /** * Get the element represented by the _id ID. * @param _id The ID of the element. - * @returns {Promise|Promise} Promise generated by the mongoose's query. + * @returns {Promise|Promise} Promise generated by the mongoose's + * query. */ public getOne(_id : string) : Promise { return new Promise((resolve : (data : Object) => void, @@ -131,7 +135,8 @@ class UserModel extends Model { /** * Get all the element of a collection. - * @returns {Promise|Promise} Promise generated by the mongoose's query. + * @returns {Promise|Promise} Promise generated by the mongoose's + * query. */ public getAll() : Promise { return new Promise((resolve : (data : Object) => void, diff --git a/src/routes/userRoute.ts b/src/routes/userRouter.ts similarity index 100% rename from src/routes/userRoute.ts rename to src/routes/userRouter.ts From 7e85087dcb24e7eb17eab6706c2f010e0eb38313 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sat, 14 May 2016 21:47:49 +0200 Subject: [PATCH 128/157] Modifies for user credentials change --- src/lib/authenticationChecker.ts | 2 +- src/models/userModel.ts | 46 +++++++++++++++--- src/routes/userRouter.ts | 81 ++++++++++++++++++++++++++++---- 3 files changed, 113 insertions(+), 16 deletions(-) diff --git a/src/lib/authenticationChecker.ts b/src/lib/authenticationChecker.ts index f503261..8110043 100644 --- a/src/lib/authenticationChecker.ts +++ b/src/lib/authenticationChecker.ts @@ -58,7 +58,7 @@ class AuthenticationChecker { let userModel : UserModel = new UserModel(); userModel .login(username, password) // Call the login method... - .then(function (user : mongoose.Model) : + .then(function (user : UserDocument) : void { // ...when done, let's say it to the client if (!user) { this.loginFailed(response); diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 76074f9..14192df 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -108,13 +108,45 @@ class UserModel extends Model { }); } + /** + * setThe new Credentials only if old credentials are good + * @param username old user's username + * @param password old user's password + * @param newUsername new user's username + * @param newPassword new user's password + * @returns {Promise|Promise} + */ + public setCredentials(username : string, + password : string, + newUsername : string, + newPassword : string) : Promise { + return new Promise( + function (resolve : (data : Object) => void, + reject : (error : Object) => void) : void { + this + .login(username, password) + .then((user : UserDocument) => { + user.username = newUsername; + user.password = newPassword; + + user.save((error : Object, data : Object) => { + if (error) { + reject(error); + } else { + resolve(data); + } + }) + }) + }); + } + /** * Get the element represented by the _id ID. * @param _id The ID of the element. - * @returns {Promise|Promise} Promise generated by the mongoose's + * @returns {Promise|Promise} Promise generated by the mongoose's * query. */ - public getOne(_id : string) : Promise { + public getOne(_id : string) : Promise < Object > { return new Promise((resolve : (data : Object) => void, reject : (error : Object) => void) => { this.model.findOne({_id: _id}, @@ -135,10 +167,10 @@ class UserModel extends Model { /** * Get all the element of a collection. - * @returns {Promise|Promise} Promise generated by the mongoose's + * @returns {Promise|Promise} Promise generated by the mongoose's * query. */ - public getAll() : Promise { + public getAll() : Promise < Object > { return new Promise((resolve : (data : Object) => void, reject : (error : Object) => void) => { this.model.find({}, @@ -162,7 +194,7 @@ class UserModel extends Model { * @returns {Model} The model. * @override */ - protected getModel() : mongoose.Model { + protected getModel() : mongoose.Model < UserDocument > { return mongoose.model("User", this.getSchema()); } @@ -242,4 +274,6 @@ class UserModel extends Model { } -export default UserModel; +export +default +UserModel; diff --git a/src/routes/userRouter.ts b/src/routes/userRouter.ts index 98f4f18..c40aedb 100644 --- a/src/routes/userRouter.ts +++ b/src/routes/userRouter.ts @@ -7,9 +7,9 @@ import LevelChecker from "../lib/levelChecker"; * This class contains endpoint definition about users. * * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Emanuele Carraro | Create class DSLRouter | 10/05/2016 | + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Luca Bianco | Create class UserRouter | 10/05/2016 | * * @author Emanuele Carraro * @license MIT @@ -46,7 +46,7 @@ class UserRouter { this.router = express.Router(); this.userModel = new UserModel(); this.authCheck = new AuthenticationChecker(); - this.checkOwner = new LevelChecker( ["OWNER", "SUPERADMIN"]); + this.checkOwner = new LevelChecker(["OWNER", "SUPERADMIN"]); // FIXME: QUESTA NON C'È NELLE API DEFINITE this.router.get( @@ -122,17 +122,80 @@ class UserRouter { private login(request : express.Request, response : express.Response) : void { this.authCheck - .login(request, response) - .then(function (data : Object) : void { + .login(request, response); + /*.then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Error) : void { + response + .status(404) + .json({ + done: false, + message: "Cannot login" + }); + });*/ + } + + /** + * @description Method to modify the credentials of an user + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ + /** + * @api {put} /api/companies/:company_id/users/:user_id/credentials + * Update credentials of an user. + * @apiVersion 0.1.0 + * @apiName updateUser + * @apiGroup User + * @apiPermission GUEST + * + * @apiDescription Use this request to update your access credentials. + * + * @apiParam {Number} company_id The Company's ID. + * @apiParam {Number} user_id The user's ID. + * @apiParam {Number} user_id The ID of the logged user. + * @apiParam {string} username The new user's email address. + * @apiParam {string} password The new user's password. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/companies/5741/users/12054/credentials + * + * @apiSuccess {Number} id The User's ID. + * @apiSuccess {string} username The user's new username. + * @apiSuccess {string} password The user's new password. + * + * @apiError CannotModifyTheUser It was impossible to update the user's + * data. + * + * @apiErrorExample Response (example): + * HTTP/1.1 404 + * { + * "done": false, + * "error": "Cannot modify the credentials" + * } + */ + private changeCredentials(request : express.Request, + response : express.Response) : void { + this.userModel + .setCredentials(request.body.username, + request.body.password, + request.body.newUsername, + request.body.newPassword) + .then((data : Object) => { response .status(200) .json(data); - }, function (error : Error) : void { + }, (error : Object) => { response - .status(404) + .status(400) .json({ done: false, - message: "Cannot login" + message: "Cannot modify the credentials" }); }); } From cc813408621101fed0b9344062f716d3d56fccb2 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sat, 14 May 2016 21:49:42 +0200 Subject: [PATCH 129/157] Added descriptions on user model --- src/models/userModel.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 14192df..7ca522c 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -22,6 +22,12 @@ interface UserDocument extends CustomModel { */ username : string; + + /** + * @description virtual field to store the password before hasing + */ + password : string; + /** * @description The user's hashed password. */ @@ -42,6 +48,10 @@ interface UserDocument extends CustomModel { */ level : string; + /** + * Document method to authenticate the user + * @param password + */ authenticate : (password : string) => boolean; } From 4e2b91e533b690165a56c44014b1948d7d3b77ec Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sat, 14 May 2016 22:06:46 +0200 Subject: [PATCH 130/157] added DSLs for company --- src/models/dslModel.ts | 31 +++++++++++++++++++++++++++++-- src/routes/dslRouter.ts | 13 ++++++------- 2 files changed, 35 insertions(+), 9 deletions(-) diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index df18d87..4a5dd52 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -1,7 +1,6 @@ import * as mongoose from "mongoose"; import Model from "./model"; -type Promise = mongoose.Promise; type DSLSchema = { permission : [{user : String, read : Boolean, exec : Boolean}], content : String @@ -60,6 +59,12 @@ export interface DSLDocument extends mongoose.Document { * Code of the DSL */ content : string; + + /** + * @description + * Id of the company that owns the DSL + */ + company_id : string; } /** @@ -100,6 +105,25 @@ class DSLModel extends Model { super(); } + /** + * @description gets all the DSLs for a company + * @param company_id + * @returns {Promise|Promise} + */ + public getAllForCompany(company_id : string) : Promise { + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + this.model.find({company_id: company_id}, + (error : Object, data : Object) => { + if (error) { + reject(error); + } else { + resolve(data); + } + }) + }); + } + /** * @description Get the dsl's schema. * @returns {"mongoose".Schema} The schema. @@ -108,7 +132,8 @@ class DSLModel extends Model { protected getSchema() : mongoose.Schema { return new mongoose.Schema({ permission: [{user: String, read: Boolean, exec: Boolean}], - content: String + content: String, + company_id: mongoose.Schema.Types.ObjectId }); } @@ -120,6 +145,8 @@ class DSLModel extends Model { protected getModel() : mongoose.Model { return mongoose.model("DSL", this.getSchema()); } + + } export default DSLModel; diff --git a/src/routes/dslRouter.ts b/src/routes/dslRouter.ts index 51629e6..8acc35a 100644 --- a/src/routes/dslRouter.ts +++ b/src/routes/dslRouter.ts @@ -42,8 +42,8 @@ class DSLRouter { ["MEMBER", "ADMIN", "OWNER", "SUPERADMIN"]); this.router.get( - "/companies/:company_id/dsl", - this.getAllDSL); + "/companies/:company_id/DSLs", + this.getAllDSLForCompany); this.router.get( "/companies/:company_id/DSLs/:dsl_id", this.checkMember.check, @@ -135,8 +135,7 @@ class DSLRouter { } /** - * @description Get the database represented by the id contained in - * the request. + * @description Get the dsl for the company * @param request The express request. * See the official * documentation for more details. @@ -148,7 +147,7 @@ class DSLRouter { * @api {get} /api/companies/:company_id/DSLs * Get all the DSL specifics accessible from the logged user. * @apiVersion 0.1.0 - * @apiName getAllDSL + * @apiName getAllDSLForCompany * @apiGroup DSL * @apiPermission MEMBER * @@ -178,10 +177,10 @@ class DSLRouter { * "error": "Cannot find the DSLs" * } */ - private getAllDSL(request : express.Request, + private getAllDSLForCompany(request : express.Request, response : express.Response) : void { this.dslModel - .getAll() + .getAllForCompany(request.params.company_id) .then(function (data : Object) : void { response .status(200) From 29ee7f3ce9fdfaad012ad0325615656501ef172d Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sat, 14 May 2016 22:10:40 +0200 Subject: [PATCH 131/157] added dashboard field on dsl model --- src/models/dslModel.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index 4a5dd52..090f7a6 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -65,6 +65,12 @@ export interface DSLDocument extends mongoose.Document { * Id of the company that owns the DSL */ company_id : string; + + /** + * @description + * Boolean value to check if it's a dashboard + */ + isDashobard : boolean; } /** @@ -133,7 +139,8 @@ class DSLModel extends Model { return new mongoose.Schema({ permission: [{user: String, read: Boolean, exec: Boolean}], content: String, - company_id: mongoose.Schema.Types.ObjectId + company_id: mongoose.Schema.Types.ObjectId, + isDashboard: Boolean }); } From 46dba2e7386d4d907ec77d3065c01bf31f4c6db9 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sat, 14 May 2016 22:18:36 +0200 Subject: [PATCH 132/157] setted the company databases list --- src/models/databaseModel.ts | 482 ++++++++++++++++++----------------- src/routes/databaseRouter.ts | 8 +- 2 files changed, 254 insertions(+), 236 deletions(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 4e03e0b..e881309 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -1,232 +1,250 @@ -import * as mongoose from "mongoose"; -import Model from "./model"; -import CustomModel from "./customModelInterface"; -import MongoDBUpdate from "./model"; - -/** - * DatabaseModel is a interface that represent the document on MongoDB. - * - * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Davide Polonio | Create interface | 09/05/2016 | - * - * @author Davide Polonio - * @copyright MIT - */ -export interface DatabaseDocument extends CustomModel { - /** - * @description Represent the company name. - */ - name : string, - /** - * @description Represent the owner id. - */ - idOwner : string, - /** - * @description Represent the username to access to the database. - */ - username : string, - /** - * @description Represent the password to access to the database. - */ - password : string, - /** - * @description Represent the address host where is install the database. - */ - host : string, - /** - * @description Represent the name of database. - */ - dbName : string -} - - -/** - * DatabaseModel manage all connections to MongoDB companies databases. - * Implements model and schema of MongooseJS. - * - * This model represent a connection to a company. - * - * - * @history - * | Author | Action Performed | Data | - * | --- | --- | --- | - * | Davide Polonio | Create class | 06/05/2016 | - * - * @author Davide Polonio - * @copyright MIT - */ -class DatabaseModel extends Model { - /** - * @description - *

This constructor calls his super constructor. After it gets the - * database connection and puts it in model.

- * @return {DatabaseModel} - * This. - */ - constructor() { - super(); - } - - /** - * @description Create a new database for the stated Company. - * @param jsonData data of the new database. - * @returns {Promise} - * Promise with the error or the saved data. - * @override - */ - public create(jsonData : Object) : Promise { - let self : DatabaseModel = this; - - return new Promise((resolve : (data : Object) => void, - reject : (error : Object) => void) => { - this - .getCollections( - jsonData["port"], - jsonData["host"], - jsonData["username"], - jsonData["password"], - jsonData["dbName"] - ) - .then(function (collections : Array) : void { - jsonData["collections"] = collections; - self - .superCreate(jsonData) - .then((data : Object) => { - resolve(data); - }, - (error : Object) => { - reject(error); - }); - }); - }); - - - } - - /** - * @description Update the stated Company databases. - * @param _id The id of the Company. - * @param jsonData Data of the new database. - * @returns {Promise} - * Promise with the error or the saved data. - */ - /* Luca Bianco: ho settato in Object il tipo di promise per rimanere - nella stessa linea di derivazione di model */ - public update(_id : string, jsonData : Object) : Promise { - let self : DatabaseModel = this; - - return new Promise((resolve : (data : Object) => void, - reject : (error : Object) => void) => { - - this - .getCollections( - jsonData["port"], - jsonData["host"], - jsonData["username"], - jsonData["password"], - jsonData["dbName"] - ) - .then(function (collections : Array) : void { - jsonData["collections"] = collections; - self.superUpdate(_id, jsonData) - .then((data : Object) => { - resolve(data); - }, (error : Object) => { - reject(error); - }); - }) - }); - } - - /** - * @description Get the database's schema. - * @returns {"mongoose".Schema} The schema. - * @override - */ - protected getSchema() : mongoose.Schema { - return new mongoose.Schema({ - name: String, - idOwner: String, - idDatabase: String, - collections: [] - }); - } - - /** - * @description Return the database's model. - * @returns {Model} The model. - * @override - */ - protected getModel() : mongoose.Model { - return mongoose.model("Database", this.getSchema()); - } - - /** - * @description Return the collection's list of the stated database. - * @param port Database's port. - * @param host Database's host. - * @param username Database's user username. - * @param password Database's user password. - * @param dbName Database's name. - * @returns {Promise|Promise} Promise - * generated by a mongoose's query. - */ - private getCollections(port : string, host : string, - username : string, password : string, - dbName : string) : Promise { - - // Connect to the database: - // Create the string - let connectionString : string = - "mongodb://" + username + - ":" + password + - "@" + host + - ":" + port + - "/" + dbName; - - // And use it to connect - let mongooseTemporaryConnection : mongoose.Connection = - mongoose.createConnection(connectionString); - return new Promise((resolve : (data : Object) => void, - reject : (error : Object) => void) => { - - // Get connections' names - mongooseTemporaryConnection.db.collectionNames( - function (err : Object, names : Array) : void { - if (err) { - reject(err); - } else { - resolve(names); - } - }); - }); - } - - /** - * Method used for invoke the base class create method from a callback - * function. - * @param jsonData Data of the database. - * @returns {Promise} - * Promise with the error or the saved data - */ - private superCreate(jsonData : Object) : Promise { - return super.create(jsonData) - } - - /** - * Method used for invoke the base class update method from a callback - * function. - * @param _id The id of the company - * @param jsonData Data of the database. - * @returns {Promise} - * Promise with the error or the saved data - */ - private superUpdate(_id : string, - jsonData : Object) : Promise { - return super.update(_id, jsonData); - } -} - -export default DatabaseModel; +import * as mongoose from "mongoose"; +import Model from "./model"; +import CustomModel from "./customModelInterface"; + +/** + * DatabaseModel is a interface that represent the document on MongoDB. + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Polonio | Create interface | 09/05/2016 | + * + * @author Davide Polonio + * @copyright MIT + */ +export interface DatabaseDocument extends CustomModel { + /** + * @description Represent the company name. + */ + name : string, + /** + * @description Represent the owner id ( the Company that owns the db). + */ + idOwner : string, + /** + * @description Represent the username to access to the database. + */ + username : string, + /** + * @description Represent the password to access to the database. + */ + password : string, + /** + * @description Represent the address host where is install the database. + */ + host : string, + /** + * @description Represent the name of database. + */ + dbName : string +} + + +/** + * DatabaseModel manage all connections to MongoDB companies databases. + * Implements model and schema of MongooseJS. + * + * This model represent a connection to a company. + * + * + * @history + * | Author | Action Performed | Data | + * | --- | --- | --- | + * | Davide Polonio | Create class | 06/05/2016 | + * + * @author Davide Polonio + * @copyright MIT + */ +class DatabaseModel extends Model { + /** + * @description + *

This constructor calls his super constructor. After it gets the + * database connection and puts it in model.

+ * @return {DatabaseModel} + * This. + */ + constructor() { + super(); + } + + /** + * gets All the databases for a company + * @param company_id + * @returns {Promise|Promise} + */ + public getAllForCompany(company_id : string) : Promise { + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + this.model.find({idOwner : company_id}, + (error : Object, data : Object) => { + if (error) { + reject(error); + } else { + resolve(data); + } + }) + }) + } + + /** + * @description Create a new database for the stated Company. + * @param jsonData data of the new database. + * @returns {Promise} + * Promise with the error or the saved data. + * @override + */ + public create(jsonData : Object) : Promise { + let self : DatabaseModel = this; + + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + this + .getCollections( + jsonData["port"], + jsonData["host"], + jsonData["username"], + jsonData["password"], + jsonData["dbName"] + ) + .then(function (collections : Array) : void { + jsonData["collections"] = collections; + self + .superCreate(jsonData) + .then((data : Object) => { + resolve(data); + }, + (error : Object) => { + reject(error); + }); + }); + }); + + + } + + /** + * @description Update the stated Company databases. + * @param _id The id of the Company. + * @param jsonData Data of the new database. + * @returns {Promise} + * Promise with the error or the saved data. + */ + /* Luca Bianco: ho settato in Object il tipo di promise per rimanere + nella stessa linea di derivazione di model */ + public update(_id : string, jsonData : Object) : Promise { + let self : DatabaseModel = this; + + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + + this + .getCollections( + jsonData["port"], + jsonData["host"], + jsonData["username"], + jsonData["password"], + jsonData["dbName"] + ) + .then(function (collections : Array) : void { + jsonData["collections"] = collections; + self.superUpdate(_id, jsonData) + .then((data : Object) => { + resolve(data); + }, (error : Object) => { + reject(error); + }); + }) + }); + } + + /** + * @description Get the database's schema. + * @returns {"mongoose".Schema} The schema. + * @override + */ + protected getSchema() : mongoose.Schema { + return new mongoose.Schema({ + name: String, + idOwner: String, + idDatabase: String, + collections: [String] + }); + } + + /** + * @description Return the database's model. + * @returns {Model} The model. + * @override + */ + protected getModel() : mongoose.Model { + return mongoose.model("Database", this.getSchema()); + } + + /** + * @description Return the collection's list of the stated database. + * @param port Database's port. + * @param host Database's host. + * @param username Database's user username. + * @param password Database's user password. + * @param dbName Database's name. + * @returns {Promise|Promise} Promise + * generated by a mongoose's query. + */ + private getCollections(port : string, host : string, + username : string, password : string, + dbName : string) : Promise { + + // Connect to the database: + // Create the string + let connectionString : string = + "mongodb://" + username + + ":" + password + + "@" + host + + ":" + port + + "/" + dbName; + + // And use it to connect + let mongooseTemporaryConnection : mongoose.Connection = + mongoose.createConnection(connectionString); + return new Promise((resolve : (data : Object) => void, + reject : (error : Object) => void) => { + + // Get connections' names + mongooseTemporaryConnection.db.collectionNames( + function (err : Object, names : Array) : void { + if (err) { + reject(err); + } else { + resolve(names); + } + }); + }); + } + + /** + * Method used for invoke the base class create method from a callback + * function. + * @param jsonData Data of the database. + * @returns {Promise} + * Promise with the error or the saved data + */ + private superCreate(jsonData : Object) : Promise { + return super.create(jsonData) + } + + /** + * Method used for invoke the base class update method from a callback + * function. + * @param _id The id of the company + * @param jsonData Data of the database. + * @returns {Promise} + * Promise with the error or the saved data + */ + private superUpdate(_id : string, + jsonData : Object) : Promise { + return super.update(_id, jsonData); + } +} + +export default DatabaseModel; diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 14bac4f..5a34dd7 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -57,7 +57,7 @@ class DatabaseRouter { this.router.get( "/companies/:company_id/databases", this.checkMember.check, - this.getAllDatabases); + this.getAllDatabasesForCompany); this.router.get( "/companies/:company_id/databases/:database_id", this.checkMember.check, @@ -156,7 +156,7 @@ class DatabaseRouter { } /** - * @description Get all databases. + * @description Get all databases for the company. * @param request The express request. * See the official * documentation for more details. @@ -201,10 +201,10 @@ class DatabaseRouter { * "error": "Cannot find the database" * } */ - private getAllDatabases(request : express.Request, + private getAllDatabasesForCompany(request : express.Request, result : express.Response) : void { this.databaseModel - .getAll() + .getAllForCompany(request.params.company_id) .then(function (data : Object) : void { result .status(200) From 86d401282b5889e0e4267ad357f3abf2aa749cbf Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sat, 14 May 2016 23:01:50 +0200 Subject: [PATCH 133/157] Added the superAdmin creation --- src/models/userModel.ts | 15 +++++++-- src/routes/userRouter.ts | 71 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 83 insertions(+), 3 deletions(-) diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 7ca522c..0b4e765 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -118,6 +118,17 @@ class UserModel extends Model { }); } + + /** + * @description Create a superAdmin + * @param jsonData + * @returns {Promise} + */ + public addSuperAdmin(jsonData : Object) : Promise { + jsonData.type = "SUPERADMIN"; + return this.create(jsonData); + } + /** * setThe new Credentials only if old credentials are good * @param username old user's username @@ -284,6 +295,4 @@ class UserModel extends Model { } -export -default -UserModel; +export default UserModel; diff --git a/src/routes/userRouter.ts b/src/routes/userRouter.ts index c40aedb..4f4d9ee 100644 --- a/src/routes/userRouter.ts +++ b/src/routes/userRouter.ts @@ -38,6 +38,12 @@ class UserRouter { */ private checkOwner : LevelChecker; + /** + * @description Level checker for SuperAdmin + * @type {LevelChecker} + */ + private checkSuperAdmin : LevelChecker; + /** * @description Complete constructor. Here we initialize user's routes. */ @@ -47,6 +53,7 @@ class UserRouter { this.userModel = new UserModel(); this.authCheck = new AuthenticationChecker(); this.checkOwner = new LevelChecker(["OWNER", "SUPERADMIN"]); + this.checkSuperAdmin = new LevelChecker(["SUPERADMIN"]); // FIXME: QUESTA NON C'È NELLE API DEFINITE this.router.get( @@ -73,6 +80,11 @@ class UserRouter { "/companies/:company_id/users/:user_id", this.checkOwner.checkWithIDSkip, this.removeUser); + + this.router.post( + "/admin/superadmins", + this.checkSuperAdmin.check, + this.createSuperAdmin); } /** @@ -137,6 +149,65 @@ class UserRouter { });*/ } + // TODO: is this right? + /** + * @description Creates a new super admin + * @param request The express request. + * See the official + * documentation for more details. + * @param response The express response object. + * See the official + * documentation for more details. + */ + /** + * @api {put} /api/admin/superadmins + * Add a new superadmin + * @apiVersion 0.1.0 + * @apiName addSuperAdmin + * @apiGroup Admin + * @apiPermission SUPERADMIN + * + * @apiDescription Use this API o add a new SuperAdmin + * + * @apiParam {Number} company_id The Company's ID. + * @apiParam {Number} user_id The user's ID. + * @apiParam {Number} user_id The ID of the logged user. + * @apiParam {string} username The new user's email address. + * @apiParam {string} password The new user's password. + * + * @apiExample Example usage: + * curl -i http://maas.com/api/admin/superadmin + * + * + * @apiError CannotAddTheSuperAdmin It was impossible to add the new + * SuperAdmin + * + * @apiErrorExample Response (example): + * HTTP/1.1 400 + * { + * "done": false, + * "error": "Cannot add the new Super Admin" + * } + */ + private createSuperAdmin(request : express.Request, + response : express.Response) : void { + this.userModel + .addSuperAdmin(request.body) + .then(function (data : Object) : void { + response + .status(200) + .json(data); + }, function (error : Object) : void { + response + // Todo : set the status + .status(400) + .json({ + done: false, + message: "Cannot create the user" + }); + }); + } + /** * @description Method to modify the credentials of an user * @param request The express request. From 237cd891c818a36ff4a5fe434179317f4beb26a5 Mon Sep 17 00:00:00 2001 From: Luca Bianco Date: Sat, 14 May 2016 23:16:31 +0200 Subject: [PATCH 134/157] Added check on route and removed FIXME --- src/routes/userRouter.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/routes/userRouter.ts b/src/routes/userRouter.ts index 4f4d9ee..221b7f7 100644 --- a/src/routes/userRouter.ts +++ b/src/routes/userRouter.ts @@ -55,20 +55,18 @@ class UserRouter { this.checkOwner = new LevelChecker(["OWNER", "SUPERADMIN"]); this.checkSuperAdmin = new LevelChecker(["SUPERADMIN"]); - // FIXME: QUESTA NON C'È NELLE API DEFINITE this.router.get( "/companies/:company_id/users", this.checkOwner.check, this.getAllUsers); - // FIXME: QUESTA NON C'È NELLE API DEFINITE this.router.get( "/companies/:company_id/users/:user_id/", this.getOneUser); - // FIXME: che tipo di check deve essere fatto qui? this.router.post( "/companies/:company_id/users", + this.checkOwner.check, this.createUser); this.router.put( From 7e009c695e00cd1a9bf006442ffa89073836ed11 Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Sun, 15 May 2016 10:17:11 +0200 Subject: [PATCH 135/157] Correct compile error --- src/models/userModel.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 0b4e765..4cd553a 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -125,7 +125,7 @@ class UserModel extends Model { * @returns {Promise} */ public addSuperAdmin(jsonData : Object) : Promise { - jsonData.type = "SUPERADMIN"; + jsonData["type"] = "SUPERADMIN"; return this.create(jsonData); } From bb3740eb56f73f02b994e98f88c70c5b6d3f16ad Mon Sep 17 00:00:00 2001 From: Matteo Di Pirro Date: Sun, 15 May 2016 10:22:34 +0200 Subject: [PATCH 136/157] Resolve compile errors on tests --- test/models/companyModelTest.ts | 16 ++++++++-------- test/models/dslModelTest.ts | 13 +++++++------ 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/test/models/companyModelTest.ts b/test/models/companyModelTest.ts index 96de67a..181725c 100644 --- a/test/models/companyModelTest.ts +++ b/test/models/companyModelTest.ts @@ -1,5 +1,5 @@ import CompanyModel from "../../src/models/companyModel"; -import CompanyDocument from "../../src/models/companyDocument"; +import CompanyDocument from "../../src/models/companyModel"; import * as Chai from "chai"; import * as mongoose from "mongoose"; @@ -32,17 +32,17 @@ describe("CompanyModel", () => { describe("#Find", () => { it("Should find a company", () => { - toTest.getCompanyById(testID).then( + toTest.getOne(testID).then( function(doc : CompanyDocument) : void { - Chai.expect(doc._id).to.equal(testID); + Chai.expect(doc["_id"]).to.equal(testID); }); }); it("Should find all companies", () => { - toTest.getCompanies().then( + toTest.getAll().then( function(docs : CompanyDocument[]) : void { - Chai.expect(docs[0]._id).to.equal(testID); - Chai.expect(docs[1]._id).to.equal(anotherTestID); + Chai.expect(docs[0]["_id"]).to.equal(testID); + Chai.expect(docs[1]["_id"]).to.equal(anotherTestID); }) }) }); @@ -56,9 +56,9 @@ describe("CompanyModel", () => { describe("#Remove", () => { it("Should remove a company given its id", () => { - let promise : mongoose.Promise = toTest.delete(testID); + let promise : Promise = toTest.remove(testID); promise.then(function(doc : CompanyDocument) : void { - toTest.getCompanyById(doc._id).then( + toTest.getOne(doc["_id"]).then( function(doc2 : CompanyDocument) : void { Chai.expect(doc2).null; }) diff --git a/test/models/dslModelTest.ts b/test/models/dslModelTest.ts index 430fc82..f298a16 100644 --- a/test/models/dslModelTest.ts +++ b/test/models/dslModelTest.ts @@ -1,28 +1,29 @@ import * as Chai from "chai" import * as mongoose from "mongoose" -import * as model from "../../src/models/dslModel" +import DSLModel from "../../src/models/dslModel" describe("DSLModel", () => { - let dsl : model.DSLModel; + let dsl : DSLModel; beforeEach(() => { - dsl = new model.DSLModel(); + dsl = new DSLModel(); }); describe("#loadADSLOnDatabase", () => { it("should exec the callback", () => { - let promise : mongoose.Promise<(data : Object) => void> = - dsl.add({ + let promise : Promise = + dsl.create({ permission: [{user: "bo", read: true, exec: true}], content: "this is unsafe" }); + /* @todo promise.onFulfill((data : Object) => { console.log("Hello world!"); }).onReject((error : Object) => { console.log("Errore"); - }); + });*/ }); }); }); From 0bf5ae88d75f61c09ce6278aacca07f9f7d4016f Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Sun, 15 May 2016 13:17:09 +0200 Subject: [PATCH 137/157] Add dslengine declaration --- typings.json | 1 + 1 file changed, 1 insertion(+) diff --git a/typings.json b/typings.json index b09e92f..8616170 100644 --- a/typings.json +++ b/typings.json @@ -2,6 +2,7 @@ "ambientDependencies": { "body-parser": "registry:dt/body-parser#0.0.0+20160317120654", "chai": "registry:dt/chai#3.4.0+20160317120654", + "dslEngine": "github:BugBusterSWE/DSLEngine/src/dslEngine.d.ts", "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", "express": "registry:dt/express#4.0.0+20160317120654", "express-serve-static-core": "registry:dt/express-serve-static-core#0.0.0+20160322035842", From ff29742e48ce302683f85e100f0cbc6f9f667501 Mon Sep 17 00:00:00 2001 From: korut94 Date: Mon, 16 May 2016 15:19:21 +0200 Subject: [PATCH 138/157] Correct name file class --- src/config/{index.ts => configurationChooser.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/config/{index.ts => configurationChooser.ts} (100%) diff --git a/src/config/index.ts b/src/config/configurationChooser.ts similarity index 100% rename from src/config/index.ts rename to src/config/configurationChooser.ts From 17ebaa99ec5c98f3f17740f8cbd04f39332e3797 Mon Sep 17 00:00:00 2001 From: korut94 Date: Mon, 16 May 2016 15:29:25 +0200 Subject: [PATCH 139/157] Restore index.ts --- src/config/{configurationChooser.ts => index.ts} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/config/{configurationChooser.ts => index.ts} (100%) diff --git a/src/config/configurationChooser.ts b/src/config/index.ts similarity index 100% rename from src/config/configurationChooser.ts rename to src/config/index.ts From 49be2382d430f5c09340263b8ff29c3556d5d958 Mon Sep 17 00:00:00 2001 From: korut94 Date: Mon, 16 May 2016 15:29:40 +0200 Subject: [PATCH 140/157] Correct import path --- src/maas.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/maas.ts b/src/maas.ts index 8a243b8..7b8d2ee 100644 --- a/src/maas.ts +++ b/src/maas.ts @@ -2,7 +2,7 @@ import * as express from "express"; import * as bodyParser from "body-parser"; import * as http from "http"; import * as helmet from "helmet"; -import ConfigurationChooser from "./config/configurationChooser"; +import ConfigurationChooser from "./config/index"; import Configuration from "./config/configuration"; import * as routes from "./routes/routerFacade"; From 8fe793ad439625674acf8173fabb44fd37efa18f Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 15:57:11 +0200 Subject: [PATCH 141/157] Update devConfiguration.ts --- src/config/devConfiguration.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/devConfiguration.ts b/src/config/devConfiguration.ts index 18ae2eb..0fe0bdd 100644 --- a/src/config/devConfiguration.ts +++ b/src/config/devConfiguration.ts @@ -1,7 +1,7 @@ import Configuration from "./configuration"; import MongoConnection from "./mongoConnection"; /** - * @description Development configuration. + * Development configuration. * @history * | Author | Action Performed | Data | * | --- | --- | --- | From 53ba195da906576da9738f698dfa605cd83e4436 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 15:58:04 +0200 Subject: [PATCH 142/157] Update mongoConnection.ts --- src/config/mongoConnection.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/mongoConnection.ts b/src/config/mongoConnection.ts index 8a2508c..ec9a0d0 100644 --- a/src/config/mongoConnection.ts +++ b/src/config/mongoConnection.ts @@ -1,5 +1,5 @@ /** - * @description This class stores the parameters for the MondoDB connection. + * This class stores the parameters for the MondoDB connection. * @history * | Author | Action Performed | Data | * | --- | --- | --- | From 9b05226f916a680e6d3f4d73c11ae7a2428c5513 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 15:58:58 +0200 Subject: [PATCH 143/157] Update index.ts --- src/config/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/index.ts b/src/config/index.ts index 7a79084..843f05d 100644 --- a/src/config/index.ts +++ b/src/config/index.ts @@ -6,7 +6,7 @@ import ProdConfiguration from "./prodConfiguration"; import {readFileSync} from "fs"; /** - * @description Class used for get the necessary configuration. + * Class used for get the necessary configuration. * @history * | Author | Action Performed | Data | * | --- | --- | --- | From 9754e678f5f99afc8e24d25729b58304a69de751 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:00:04 +0200 Subject: [PATCH 144/157] Update prodConfiguration.ts --- src/config/prodConfiguration.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/config/prodConfiguration.ts b/src/config/prodConfiguration.ts index c1fb907..afe23dd 100644 --- a/src/config/prodConfiguration.ts +++ b/src/config/prodConfiguration.ts @@ -2,7 +2,7 @@ import Configuration from "./configuration"; import MongoConnection from "./mongoConnection"; /** - * @description Production configuration. + * Production configuration. * @history * | Author | Action Performed | Data | * | --- | --- | --- | From c97c9175c6920fef9babd34e61cfb5001f13b99a Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:07:44 +0200 Subject: [PATCH 145/157] Update authenticationChecker.ts --- src/lib/authenticationChecker.ts | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/lib/authenticationChecker.ts b/src/lib/authenticationChecker.ts index 8110043..18de283 100644 --- a/src/lib/authenticationChecker.ts +++ b/src/lib/authenticationChecker.ts @@ -41,7 +41,7 @@ class AuthenticationChecker { private PASSWORD_BODY_FIELD : string = "password"; /** - * Login the user. + * @description Login the user. * @param request The express request. * See the official * documentation for more details. @@ -76,7 +76,7 @@ class AuthenticationChecker { } /** - * Authenticate the user. + * @description Authenticate the user. * @param request The express request. * See the official * documentation for more details. @@ -109,7 +109,7 @@ class AuthenticationChecker { } /** - * Create the JWT token for the current user. + * @description Create the JWT token for the current user. * @param data User's data. * @returns {string} A string which represents the JWT token created. */ @@ -124,7 +124,7 @@ class AuthenticationChecker { } /** - * Create a parametrized response for the token not found situation. + * @descripton Create a parametrized response for the token not found situation. * @param response The generated response with an error message which * represents the "token not found" situation. */ @@ -137,7 +137,7 @@ class AuthenticationChecker { } /** - * Create a parametrized response for the authentication failed situation. + * @description Create a parametrized response for the authentication failed situation. * @param response The generated response with an error message which * represents the "authentication failed" situation. */ @@ -150,7 +150,7 @@ class AuthenticationChecker { } /** - * Create a parametrized response for the login failed situation. + * @description Create a parametrized response for the login failed situation. * @param response The generated response with an error message which * represents the "login failed" situation. */ From 86547a858ca4852e6c711f96b62175dc3dafe37b Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Mon, 16 May 2016 16:11:57 +0200 Subject: [PATCH 146/157] Remove double dependences --- package.json | 2 -- 1 file changed, 2 deletions(-) diff --git a/package.json b/package.json index 9a73d9b..b87b775 100644 --- a/package.json +++ b/package.json @@ -40,8 +40,6 @@ "author": "BugBusters bugbusterswe@gmail.com", "license": "MIT", "dependencies": { - - "chai": "^3.5.0", "express": "^4.13.1", "mongoose": "^4.4.14", "promise": "^7.1.1", From bd840bb467838157de09bd93d601a699febd81d7 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:12:46 +0200 Subject: [PATCH 147/157] Update levelChecker.ts --- src/lib/levelChecker.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/lib/levelChecker.ts b/src/lib/levelChecker.ts index 1be7205..f8aeeab 100644 --- a/src/lib/levelChecker.ts +++ b/src/lib/levelChecker.ts @@ -20,7 +20,7 @@ class LevelChecker { private levelsAllowed : Array; /** - * Complete constructor. + * @description Complete constructor. * @param levelsAllowed An array which contains all the possible users' * levels. */ @@ -82,7 +82,7 @@ class LevelChecker { } /** - * Create a parametrized response for the access denied situation. + * @description Create a parametrized response for the access denied situation. * @param response The generated response with an error message which * represents the "access denied" situation. */ From 5323a4f8343feee463e795d1d23986e39ce8041d Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Mon, 16 May 2016 16:34:26 +0200 Subject: [PATCH 148/157] Fix lint errors --- src/lib/authenticationChecker.ts | 9 ++++++--- src/lib/levelChecker.ts | 3 ++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/lib/authenticationChecker.ts b/src/lib/authenticationChecker.ts index 18de283..f410e5d 100644 --- a/src/lib/authenticationChecker.ts +++ b/src/lib/authenticationChecker.ts @@ -124,7 +124,8 @@ class AuthenticationChecker { } /** - * @descripton Create a parametrized response for the token not found situation. + * @descripton + * Create a parametrized response for the token not found situation. * @param response The generated response with an error message which * represents the "token not found" situation. */ @@ -137,7 +138,8 @@ class AuthenticationChecker { } /** - * @description Create a parametrized response for the authentication failed situation. + * @description + * Create a parametrized response for the authentication failed situation. * @param response The generated response with an error message which * represents the "authentication failed" situation. */ @@ -150,7 +152,8 @@ class AuthenticationChecker { } /** - * @description Create a parametrized response for the login failed situation. + * @description + * Create a parametrized response for the login failed situation. * @param response The generated response with an error message which * represents the "login failed" situation. */ diff --git a/src/lib/levelChecker.ts b/src/lib/levelChecker.ts index f8aeeab..5492d29 100644 --- a/src/lib/levelChecker.ts +++ b/src/lib/levelChecker.ts @@ -82,7 +82,8 @@ class LevelChecker { } /** - * @description Create a parametrized response for the access denied situation. + * @description + * Create a parametrized response for the access denied situation. * @param response The generated response with an error message which * represents the "access denied" situation. */ From f280bc7e4434309d9fed6c05c09e184fe5d30bc5 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:38:35 +0200 Subject: [PATCH 149/157] Update databaseModel.ts --- src/models/databaseModel.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index e881309..90e5813 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -69,7 +69,7 @@ class DatabaseModel extends Model { } /** - * gets All the databases for a company + * @description Gets All the databases for a company * @param company_id * @returns {Promise|Promise} */ @@ -223,7 +223,7 @@ class DatabaseModel extends Model { } /** - * Method used for invoke the base class create method from a callback + * @description Method used for invoke the base class create method from a callback * function. * @param jsonData Data of the database. * @returns {Promise} @@ -234,7 +234,7 @@ class DatabaseModel extends Model { } /** - * Method used for invoke the base class update method from a callback + * @description Method used for invoke the base class update method from a callback * function. * @param _id The id of the company * @param jsonData Data of the database. From 7adf2ce4f89096795d5f34774abfe31df041b884 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:39:49 +0200 Subject: [PATCH 150/157] Update dslModel.ts --- src/models/dslModel.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/models/dslModel.ts b/src/models/dslModel.ts index 090f7a6..e796ec3 100644 --- a/src/models/dslModel.ts +++ b/src/models/dslModel.ts @@ -112,7 +112,7 @@ class DSLModel extends Model { } /** - * @description gets all the DSLs for a company + * @description Gets all the DSLs for a company * @param company_id * @returns {Promise|Promise} */ From 3ac744a8a9a60d2b05d7d786b260c3a499bd3a8a Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:41:36 +0200 Subject: [PATCH 151/157] Update mongooseConnection.ts --- src/models/mongooseConnection.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/models/mongooseConnection.ts b/src/models/mongooseConnection.ts index 10fcabd..f408ca9 100644 --- a/src/models/mongooseConnection.ts +++ b/src/models/mongooseConnection.ts @@ -2,7 +2,7 @@ * This is a Singleton class used for perform a connection with a MongoDB * database. * - * * @history + * @history * | Author | Action Performed | Data | * | --- | --- | --- | * | Matteo Di Pirro | Create class | 04/05/2016 | From 626474640b01579ffce140f8ae5e45191934f757 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:46:30 +0200 Subject: [PATCH 152/157] Update userModel.ts --- src/models/userModel.ts | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/models/userModel.ts b/src/models/userModel.ts index 4cd553a..30a1248 100644 --- a/src/models/userModel.ts +++ b/src/models/userModel.ts @@ -56,7 +56,7 @@ interface UserDocument extends CustomModel { } /** - * @description This class represents the user model. + * description This class represents the user model. */ class UserModel extends Model { /** @@ -82,14 +82,14 @@ class UserModel extends Model { ]; /** - * Default constructor. + * @description Default constructor. */ constructor() { super(); } /** - * Login method. + * @description Login method. * @param username User's username. * @param password USer's password. * @returns {Promise|Promise} Promise generated by the mongoose's query. @@ -130,7 +130,7 @@ class UserModel extends Model { } /** - * setThe new Credentials only if old credentials are good + * @description Set the new Credentials only if old credentials are good * @param username old user's username * @param password old user's password * @param newUsername new user's username @@ -162,7 +162,7 @@ class UserModel extends Model { } /** - * Get the element represented by the _id ID. + * @description Get the element represented by the _id ID. * @param _id The ID of the element. * @returns {Promise|Promise} Promise generated by the mongoose's * query. @@ -187,7 +187,7 @@ class UserModel extends Model { } /** - * Get all the element of a collection. + * @description Get all the element of a collection. * @returns {Promise|Promise} Promise generated by the mongoose's * query. */ @@ -221,7 +221,7 @@ class UserModel extends Model { /** * @description Return the user's model. - * @returns {Model} The model. + * @returns {Schema} The model. * @override */ protected getSchema() : mongoose.Schema { @@ -267,7 +267,7 @@ class UserModel extends Model { } /** - * Set the methods of the user's schema. + * @description Set the methods of the user's schema. * @param schema The user's schema. */ private setSchemaMethods(schema : mongoose.Schema) : void { From d127761b86b92db17749551a8007b0b711dbad83 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:48:57 +0200 Subject: [PATCH 153/157] Update companyRouter.ts --- src/routes/companyRouter.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/routes/companyRouter.ts b/src/routes/companyRouter.ts index aa8a965..0ff187d 100644 --- a/src/routes/companyRouter.ts +++ b/src/routes/companyRouter.ts @@ -44,7 +44,7 @@ class CompanyRouter { private checkSuperAdmin : LevelChecker; /** - * Complete constructor. Here we initialize the company routes. + * @description Complete constructor. Here we initialize the company routes. */ constructor() { @@ -262,7 +262,7 @@ class CompanyRouter { } /** - * Update a stated Company. + * @description Update a stated Company. * @param request The express request. * See the official * documentation for more details. @@ -324,7 +324,7 @@ class CompanyRouter { } /** - * Remove a stated company. + * @description Remove a stated company. * @param request The express request. * See the official * documentation for more details. From 963185d1bf6c0f1fa6c60189469301e9ff690f62 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:52:37 +0200 Subject: [PATCH 154/157] Update databaseRouter.ts --- src/routes/databaseRouter.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/routes/databaseRouter.ts b/src/routes/databaseRouter.ts index 5a34dd7..4b7e393 100644 --- a/src/routes/databaseRouter.ts +++ b/src/routes/databaseRouter.ts @@ -1,3 +1,6 @@ +/* +TODO: Missing reference to the DatabaseModel object +*/ import * as express from "express"; import DatabaseModel from "../models/databaseModel"; import LevelChecker from "../lib/levelChecker"; @@ -13,12 +16,7 @@ import LevelChecker from "../lib/levelChecker"; * * @author Davide Polonio * @copyright MIT - * - * - * @todo Missing reference to the DatabaseModel object - * */ - class DatabaseRouter { /** @@ -42,7 +40,7 @@ class DatabaseRouter { private databaseModel : DatabaseModel; /** - * Complete constructor. Here we initialize databases routers. + * @description Complete constructor. Here we initialize databases routers. */ constructor() { From 1db98de57e87d5ed0fa8cef69fbd5696276e1b33 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:54:10 +0200 Subject: [PATCH 155/157] Update databaseModel.ts --- src/models/databaseModel.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 90e5813..615dc49 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -223,7 +223,8 @@ class DatabaseModel extends Model { } /** - * @description Method used for invoke the base class create method from a callback + * @description + * Method used for invoke the base class create method from a callback * function. * @param jsonData Data of the database. * @returns {Promise} @@ -234,7 +235,8 @@ class DatabaseModel extends Model { } /** - * @description Method used for invoke the base class update method from a callback + * @description + * Method used for invoke the base class update method from a callback * function. * @param _id The id of the company * @param jsonData Data of the database. From 8cee71e1aae7ac87b97a061293e640bafca301da Mon Sep 17 00:00:00 2001 From: Davide Polonio Date: Mon, 16 May 2016 16:55:53 +0200 Subject: [PATCH 156/157] Fix lint 80 columns --- src/models/databaseModel.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/models/databaseModel.ts b/src/models/databaseModel.ts index 90e5813..04cf780 100644 --- a/src/models/databaseModel.ts +++ b/src/models/databaseModel.ts @@ -223,8 +223,9 @@ class DatabaseModel extends Model { } /** - * @description Method used for invoke the base class create method from a callback - * function. + * @description + *

Method used for invoke the base class create method from a callback + * function.

* @param jsonData Data of the database. * @returns {Promise} * Promise with the error or the saved data @@ -234,8 +235,9 @@ class DatabaseModel extends Model { } /** - * @description Method used for invoke the base class update method from a callback - * function. + * @description + *

Method used for invoke the base class update method from a callback + * function.

* @param _id The id of the company * @param jsonData Data of the database. * @returns {Promise} From 42c608c4d65327159d2b96ef57dd5c68932316c9 Mon Sep 17 00:00:00 2001 From: Andrea Mantovani Date: Mon, 16 May 2016 16:57:38 +0200 Subject: [PATCH 157/157] Update userRouter.ts --- src/routes/userRouter.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/routes/userRouter.ts b/src/routes/userRouter.ts index 221b7f7..638dc89 100644 --- a/src/routes/userRouter.ts +++ b/src/routes/userRouter.ts @@ -18,7 +18,7 @@ import LevelChecker from "../lib/levelChecker"; class UserRouter { /** - * * @description Express router. + * @description Express router. */ private router : express.Router;