Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 77 additions & 71 deletions loaders/ManagersLoader.js
Original file line number Diff line number Diff line change
@@ -1,80 +1,86 @@
const MiddlewaresLoader = require('./MiddlewaresLoader');
const ApiHandler = require("../managers/api/Api.manager");
const LiveDB = require('../managers/live_db/LiveDb.manager');
const UserServer = require('../managers/http/UserServer.manager');
const ResponseDispatcher = require('../managers/response_dispatcher/ResponseDispatcher.manager');
const VirtualStack = require('../managers/virtual_stack/VirtualStack.manager');
const ValidatorsLoader = require('./ValidatorsLoader');
const ResourceMeshLoader = require('./ResourceMeshLoader');
const utils = require('../libs/utils');
const MiddlewaresLoader = require("./MiddlewaresLoader");
const ApiHandler = require("../managers/api/Api.manager");
const LiveDB = require("../managers/live_db/LiveDb.manager");
const UserServer = require("../managers/http/UserServer.manager");
const ResponseDispatcher = require("../managers/response_dispatcher/ResponseDispatcher.manager");
const VirtualStack = require("../managers/virtual_stack/VirtualStack.manager");
const ValidatorsLoader = require("./ValidatorsLoader");
const ResourceMeshLoader = require("./ResourceMeshLoader");
const utils = require("../libs/utils");
const MongoLoader = require("./MongoLoader");

const systemArch = require('../static_arch/main.system');
const TokenManager = require('../managers/token/Token.manager');
const SharkFin = require('../managers/shark_fin/SharkFin.manager');
const TimeMachine = require('../managers/time_machine/TimeMachine.manager');

/**
const systemArch = require("../static_arch/main.system");
const TokenManager = require("../managers/entities/token/Token.manager");
const SharkFin = require("../managers/shark_fin/SharkFin.manager");
const TimeMachine = require("../managers/time_machine/TimeMachine.manager");
const UserManager = require("../managers/entities/user/User.manager");
const SchoolManager = require('../managers/entities/school/school.manager')
/**
* load sharable modules
* @return modules tree with instance of each module
*/
*/
module.exports = class ManagersLoader {
constructor({ config, cortex, cache, oyster, aeon }) {

this.managers = {};
this.config = config;
this.cache = cache;
this.cortex = cortex;

this._preload();
this.injectable = {
utils,
cache,
config,
cortex,
oyster,
aeon,
managers: this.managers,
validators: this.validators,
// mongomodels: this.mongomodels,
resourceNodes: this.resourceNodes,
};

}

_preload(){
const validatorsLoader = new ValidatorsLoader({
models: require('../managers/_common/schema.models'),
customValidators: require('../managers/_common/schema.validators'),
});
const resourceMeshLoader = new ResourceMeshLoader({})
// const mongoLoader = new MongoLoader({ schemaExtension: "mongoModel.js" });

this.validators = validatorsLoader.load();
this.resourceNodes = resourceMeshLoader.load();
// this.mongomodels = mongoLoader.load();

}
constructor({ config, cortex, cache, oyster, aeon }) {
this.managers = {};
this.config = config;
this.cache = cache;
this.cortex = cortex;

load() {
this.managers.responseDispatcher = new ResponseDispatcher();
this.managers.liveDb = new LiveDB(this.injectable);
const middlewaresLoader = new MiddlewaresLoader(this.injectable);
const mwsRepo = middlewaresLoader.load();
const { layers, actions } = systemArch;
this.injectable.mwsRepo = mwsRepo;
/*****************************************CUSTOM MANAGERS*****************************************/
this.managers.shark = new SharkFin({ ...this.injectable, layers, actions });
this.managers.timeMachine = new TimeMachine(this.injectable);
this.managers.token = new TokenManager(this.injectable);
/*************************************************************************************************/
this.managers.mwsExec = new VirtualStack({ ...{ preStack: [/* '__token', */'__device',] }, ...this.injectable });
this.managers.userApi = new ApiHandler({...this.injectable,...{prop:'httpExposed'}});
this.managers.userServer = new UserServer({ config: this.config, managers: this.managers });
this._preload();
this.injectable = {
utils,
cache,
config,
cortex,
oyster,
aeon,
managers: this.managers,
validators: this.validators,
mongomodels: this.mongomodels,
resourceNodes: this.resourceNodes,
};
}


return this.managers;
_preload() {
const validatorsLoader = new ValidatorsLoader({
models: require("../managers/_common/schema.models"),
customValidators: require("../managers/_common/schema.validators"),
});
const resourceMeshLoader = new ResourceMeshLoader({});
const mongoLoader = new MongoLoader({ schemaExtension: "mongoModel.js" });

}
this.validators = validatorsLoader.load();
this.resourceNodes = resourceMeshLoader.load();
this.mongomodels = mongoLoader.load();
}

}
load() {
this.managers.responseDispatcher = new ResponseDispatcher();
this.managers.liveDb = new LiveDB(this.injectable);
const middlewaresLoader = new MiddlewaresLoader(this.injectable);
const mwsRepo = middlewaresLoader.load();
const { layers, actions } = systemArch;
this.injectable.mwsRepo = mwsRepo;
/*****************************************CUSTOM MANAGERS*****************************************/
this.managers.shark = new SharkFin({ ...this.injectable, layers, actions });
this.managers.timeMachine = new TimeMachine(this.injectable);
this.managers.token = new TokenManager(this.injectable);
this.managers.user = new UserManager(this.injectable);
this.managers.school = new SchoolManager(this.injectable)
/*************************************************************************************************/
this.managers.mwsExec = new VirtualStack({
...{ preStack: [/* '__token', */ "__device"] },
...this.injectable,
});
this.managers.userApi = new ApiHandler({
...this.injectable,
...{ prop: "httpExposed" },
});
this.managers.userServer = new UserServer({
config: this.config,
managers: this.managers,
});

return this.managers;
}
};
3 changes: 2 additions & 1 deletion loaders/MiddlewaresLoader.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ module.exports = class MiddlewareLoader {
return mws;
}

}
}

2 changes: 1 addition & 1 deletion managers/api/Api.manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ module.exports = class ApiHandler {
let context = req.params.context;
let fnName = req.params.fnName;
let moduleMatrix = this.methodMatrix[moduleName];

console.log(this.methodMatrix)
/** validate module */
if(!moduleMatrix) return this.managers.responseDispatcher.dispatch(res, {ok: false, message: `module ${moduleName} not found`});

Expand Down
19 changes: 19 additions & 0 deletions managers/entities/classroom/classroom.mongoModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
const mongoose = require('mongoose');

const classroomSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
school: {
type: mongoose.Schema.Types.ObjectId,
ref: 'School',
required: true
},
students: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Student'
}]
});

module.exports = mongoose.model('Classroom', classroomSchema);
21 changes: 21 additions & 0 deletions managers/entities/errorHandlers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const _ = require("lodash");

const errorHandlers = {
conflictError: (message) => {
return { ok: false, code: 409, data: {}, errors: [message], message };
},
validationError: (message) => {
return { ok: false, code: 400, data: {}, errors: [message], message };
},

notFoundError: (message) => {
return { ok: false, code: 404, data: {}, errors: [message], message };
},

nonAuthorizedError: (message) => {
return { ok: false, code: 403, data: {}, errors: [message], message };
},
};

// Export the object containing both functions
module.exports = errorHandlers;
56 changes: 56 additions & 0 deletions managers/entities/school/school.manager.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
const bcrypt = require("bcrypt");
const {
validationError,
conflictError,
notFoundError,
nonAuthorizedError,
} = require("../errorHandlers");
const SchoolModel = require("./school.mongoModel");
const UserModel = require("../user/user.mongoModel");
class School {
constructor({
utils,
cache,
config,
cortex,
managers,
validators,
mongomodels,
} = {}) {
this.config = config;
this.cortex = cortex;
this.validators = validators;
this.mongomodels = mongomodels;
this.tokenManager = managers.token;
this.usersCollection = "school";
this.httpExposed = ["create"];
this.scopes = ["super-admin"];
}

async create({ __longToken, schoolManager, name, address, website }) {
try {
const validationIssue = await this.validators.school.create({ name });
if (validationIssue) {
return validationError(validation[0].message);
}
const { role } = __longToken;
if (!this.hasScope(role)) {
return nonAuthorizedError("Insufficient permissions");
}
const school = await SchoolModel.findOne({ name });
if (school) {
return conflictError("A school with this name already exists ");
}

return SchoolModel.create({ name });
} catch (err) {
throw new Error("Internal server error");
}
}

hasScope(role) {
return this.scopes.includes(role);
}
}

module.exports = School;
22 changes: 22 additions & 0 deletions managers/entities/school/school.mongoModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
const mongoose = require('mongoose');

const schoolSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
admins: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
}],
classrooms: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Classroom'
}],
students: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Student'
}]
});

module.exports = mongoose.model('School', schoolSchema);
9 changes: 9 additions & 0 deletions managers/entities/school/school.schema.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
module.exports = {
create: [
{
model: "text",
path: "name",
required: true,
},
],
};
15 changes: 15 additions & 0 deletions managers/entities/student/student.mongoModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const mongoose = require('mongoose');

const studentSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
classroom: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Classroom',
required: true
}
});

module.exports = mongoose.model('Student', studentSchema);
6 changes: 3 additions & 3 deletions managers/entities/token/Token.manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ module.exports = class TokenManager {
* long token contains immutable data and long lived
* master key must exists on any device to create short tokens
*/
genLongToken({userId, userKey}){
genLongToken({userId, role}){
return jwt.sign(
{
userKey,
role,
userId,
},
this.config.dotEnv.LONG_TOKEN_SECRET,
Expand All @@ -36,7 +36,7 @@ module.exports = class TokenManager {

genShortToken({userId, userKey, sessionId, deviceId}){
return jwt.sign(
{ userKey, userId, sessionId, deviceId},
{ role, userId, sessionId, deviceId},
this.config.dotEnv.SHORT_TOKEN_SECRET,
{expiresIn: this.shortTokenExpiresIn
})
Expand Down
Loading