jcc-express-mvc 1.1.4 → 1.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jcc-express-mvc",
3
- "version": "1.1.4",
3
+ "version": "1.1.6",
4
4
  "description": "express mvc structure",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/src/Auth/index.js CHANGED
@@ -1,76 +1,89 @@
1
- const passport = require("passport");
2
- const { getModel, verifyHash } = require("../helpers");
3
- const User = getModel("User");
1
+ const passport = require("passport"); // Import Passport for authentication
2
+ const { getModel, verifyHash } = require("../helpers"); // Import helper functions for database operations and password hashing
3
+ const User = getModel("User"); // Get the User model from database
4
4
 
5
5
  class Auth {
6
- async login(data = {}, password = "") {
6
+ // Method to authenticate user login
7
+ static async login(data = {}, password = "") {
7
8
  try {
8
- const user = await User.findOne(data).select("+password");
9
+ const user = await User.findOne(data).select("+password"); // Find user by provided data and include password field
9
10
  if (!user) {
10
- return false;
11
+ return false; // If user not found, return false
11
12
  }
12
13
 
13
- return (await verifyHash(password, user.password)) ? user : false;
14
+ return (await verifyHash(password, user.password)) ? user : false; // Verify password hash and return user if successful, otherwise false
14
15
  } catch (error) {
15
- return new Error(error.message);
16
+ return new Error(error.message); // Return error if any exception occurs during login
16
17
  }
17
18
  }
18
19
 
19
- async isAdmin(req, res, next) {
20
+ // Middleware to check if user is an admin
21
+ static async isAdmin(req, res, next) {
20
22
  try {
21
- const user = await User.findById(req.id);
23
+ const user = await User.findById(req.id); // Find user by ID extracted from request
22
24
  if (!user) {
23
- return res.json({ message: "Not authorize" }).status(403);
25
+ return res.json({ message: "Not authorized" }).status(403); // If user not found, return 403 Forbidden
24
26
  }
25
27
 
28
+ // Check if user has admin privileges
26
29
  if (
27
- user.role != "admin" ||
28
- user.role != "Admin" ||
29
- user.role != false ||
30
- user.roleType != "admin" ||
31
- user.roleType != "Admin" ||
32
- user.roleType != false ||
33
- user.isAdmin != "Admin" ||
34
- user.isAdmin != "admin" ||
35
- user.isAdmin != false
30
+ !user.role ||
31
+ !user.roleType ||
32
+ !user.isAdmin ||
33
+ !(
34
+ user.role === "admin" ||
35
+ user.role === "Admin" ||
36
+ user.roleType === "admin" ||
37
+ user.roleType === "Admin" ||
38
+ user.isAdmin === true ||
39
+ user.isAdmin === "admin" ||
40
+ user.isAdmin === "Admin"
41
+ )
36
42
  ) {
37
- return res.json({ message: "Not authorize" }).status(403);
43
+ return res.json({ message: "Not authorized" }).status(403); // If user doesn't have admin privileges, return 403 Forbidden
38
44
  }
39
45
 
40
- next();
46
+ next(); // If user is admin, proceed to next middleware
41
47
  } catch (error) {
42
- next(error);
48
+ next(error); // Pass any errors to the error handling middleware
43
49
  }
44
50
  }
45
51
 
46
- async verifyEmail(req, res, next) {
52
+ // Middleware to verify user email
53
+ static async verifyEmail(req, res, next) {
47
54
  try {
48
- const user = await User.findById(req.id);
55
+ const user = await User.findById(req.id); // Find user by ID extracted from request
49
56
  if (!user) {
50
- return res.json({ message: "Not authorize" }).status(403);
57
+ return res.json({ message: "Not authorized" }).status(403); // If user not found, return 403 Forbidden
51
58
  }
52
- if (!user.verify_email || !user.verifyEmail) {
53
- return res.json({ message: "please verify your email" }).status(403);
59
+
60
+ // Check if user's email is verified
61
+ if (!user.verify_email && !user.verifyEmail) {
62
+ return res.json({ message: "Please verify your email" }).status(403); // If email is not verified, return 403 Forbidden
54
63
  }
55
- next();
56
- } catch (err) {
57
- next(err);
64
+
65
+ next(); // If email is verified, proceed to next middleware
66
+ } catch (error) {
67
+ next(error); // Pass any errors to the error handling middleware
58
68
  }
59
69
  }
60
70
 
61
- attempt(req, res, next) {
71
+ // Method to handle authentication attempt
72
+ static attempt(req, res, next) {
62
73
  try {
63
- let redirectBack = req.previsiousUrls[1];
64
- const appRedirect = req.session["appRedirect"];
65
- const redirectPath = appRedirect ? appRedirect : "/home";
74
+ let redirectBack = req.previsiousUrls[1]; // Retrieve the previous URL
75
+ const appRedirect = req.session["appRedirect"]; // Retrieve redirect URL from session
76
+ const redirectPath = appRedirect ? appRedirect : "/home"; // Determine the redirect path
77
+ // Use Passport's local authentication strategy
66
78
  return passport.authenticate("local", {
67
- successRedirect: redirectPath,
68
- failureRedirect: `${redirectBack ? redirectBack : "/login"}`,
69
- failureFlash: true,
70
- })(req, res, next);
79
+ successRedirect: redirectPath, // Redirect on successful authentication
80
+ failureRedirect: `${redirectBack ? redirectBack : "/login"}`, // Redirect on failed authentication
81
+ failureFlash: true, // Enable flash messages on failed authentication
82
+ })(req, res, next); // Call Passport's authentication middleware
71
83
  } catch (error) {
72
- next(error);
84
+ next(error); // Pass any errors to the error handling middleware
73
85
  }
74
86
  }
75
87
  }
76
- module.exports = new Auth();
88
+
89
+ module.exports = Auth; // Export an instance of the Auth class
@@ -1,21 +1,20 @@
1
+ // Middleware to check if user is authenticated, redirect to login page if not
1
2
  exports.authenticated = (req, res, next) => {
2
3
  let url = "";
3
4
  if (req.url) {
4
5
  url = req.url;
5
6
  req.session["appRedirect"] = url;
6
7
  }
8
+ // Check if user is authenticated using Passport's isAuthenticated method
7
9
  return req.isAuthenticated()
8
- ? next()
9
- : res.redirect(url ? `/login?redirect=${url}` : "/login");
10
+ ? next() // If authenticated, proceed to the next middleware
11
+ : res.redirect(url ? `/login?redirect=${url}` : "/login"); // If not authenticated, redirect to login page
10
12
  };
11
13
 
12
- // exports.isLogIn = (req, res, next) =>
13
- // req.isAuthenticated() ? res.redirect("/home") : next();
14
-
15
- // exports.isLogIn
16
-
14
+ // Middleware to protect API routes, ensuring requests have a valid token
17
15
  exports.protectedApi = (request, response, next) => {
18
16
  let token;
17
+ // Extract token from different sources: headers, cookies, or custom header
19
18
  if (
20
19
  request.headers.authorization &&
21
20
  request.headers.authorization.startsWith("Bearer")
@@ -26,13 +25,15 @@ exports.protectedApi = (request, response, next) => {
26
25
  } else if (request.header("x-auth-token")) {
27
26
  token = request.header("x-auth-token");
28
27
  }
28
+ // If token is not present, return unauthorized response
29
29
  if (!token) {
30
- return response.json({ message: "Not authorize" }).status(403);
30
+ return response.json({ message: "Not authorized" }).status(403);
31
31
  }
32
32
  try {
33
+ // Verify the token using JWT and store the decoded ID in the request object
33
34
  request.id = jwt.verify(token, process.env.JWT_SECRET);
34
- next();
35
+ next(); // Proceed to the next middleware if token is valid
35
36
  } catch (err) {
36
- return response.json({ message: "Not authorize" }).status(403);
37
+ return response.json({ message: "Not authorized" }).status(403); // Return unauthorized response if token is invalid
37
38
  }
38
39
  };
@@ -1,37 +1,86 @@
1
1
  const Util = require("../utils");
2
2
 
3
+ /**
4
+ * Initializes a Router object.
5
+ * This class helps in setting up routes for different HTTP methods.
6
+ * @param {Object} options - Options object containing basePath and app properties.
7
+ * @param {string} prefix - Prefix for the routes.
8
+ * @param {Array} middlewares - Array of middleware functions.
9
+ * @param {Object} classController - Controller class.
10
+ */
3
11
  class Router {
4
- constructor(app, prefix, middlewares, classController) {
12
+ constructor({ basePath, app }, prefix, middlewares, classController) {
5
13
  this.app = app;
14
+ this.basePath = basePath;
6
15
  this.prefixUrl = prefix;
7
16
  this.middlewares = middlewares;
8
17
  this.classController = classController;
9
18
 
10
- this.util = new Util(app, prefix, middlewares, classController);
19
+ // Initializes Util instance for route handling
20
+ this.util = new Util(basePath, app, prefix, middlewares, classController);
11
21
  }
12
22
 
23
+ /**
24
+ * Sets middleware functions for the router.
25
+ * @param {Array} middlewares - Array of middleware functions.
26
+ * @returns {Router} - Returns the router instance.
27
+ */
13
28
  middleware(middlewares = [] || func) {
14
29
  this.middlewares = middlewares;
15
30
  this.util.setGroupMiddleware(middlewares);
16
31
  return this;
17
32
  }
18
33
 
34
+ /**
35
+ * Adds a route handler for GET requests.
36
+ * @param {string} path - Route path.
37
+ * @param {Function} callback - Callback function to handle the request.
38
+ * @returns {Router} - Returns the router instance.
39
+ */
19
40
  get(path, callback) {
20
41
  this.util.routeHelper("get", path, callback);
21
42
  return this;
22
43
  }
44
+
45
+ /**
46
+ * Adds a route handler for POST requests.
47
+ * @param {string} path - Route path.
48
+ * @param {Function} callback - Callback function to handle the request.
49
+ * @returns {Router} - Returns the router instance.
50
+ */
23
51
  post(path, callback) {
24
52
  this.util.routeHelper("post", path, callback);
25
53
  return this;
26
54
  }
55
+
56
+ /**
57
+ * Adds a route handler for PATCH requests.
58
+ * @param {string} path - Route path.
59
+ * @param {Function} callback - Callback function to handle the request.
60
+ * @returns {Router} - Returns the router instance.
61
+ */
27
62
  patch(path, callback) {
28
63
  this.util.routeHelper("patch", path, callback);
29
64
  return this;
30
65
  }
66
+
67
+ /**
68
+ * Adds a route handler for PUT requests.
69
+ * @param {string} path - Route path.
70
+ * @param {Function} callback - Callback function to handle the request.
71
+ * @returns {Router} - Returns the router instance.
72
+ */
31
73
  put(path, callback) {
32
74
  this.util.routeHelper("put", path, callback);
33
75
  return this;
34
76
  }
77
+
78
+ /**
79
+ * Adds a route handler for DELETE requests.
80
+ * @param {string} path - Route path.
81
+ * @param {Function} callback - Callback function to handle the request.
82
+ * @returns {Router} - Returns the router instance.
83
+ */
35
84
  delete(path, callback) {
36
85
  this.util.routeHelper("delete", path, callback);
37
86
  return this;
@@ -1,21 +1,47 @@
1
1
  const Router = require("./Router");
2
+
3
+ /**
4
+ * Initializes a Routes object.
5
+ * This class extends the Router class and provides additional functionalities for route grouping and controller setting.
6
+ * @param {Object} app - Express application instance.
7
+ */
2
8
  class Routes extends Router {
3
9
  constructor(app) {
4
10
  super(app);
5
11
  }
12
+
13
+ /**
14
+ * Sets a prefix for the routes.
15
+ * @param {string} url - Prefix URL for the routes.
16
+ * @returns {Routes} - Returns the Routes instance.
17
+ */
6
18
  prefix(url) {
7
19
  this.prefixUrl = url;
8
20
  return this;
9
21
  }
22
+
23
+ /**
24
+ * Sets the controller for the routes.
25
+ * @param {Object} controller - Controller class or object.
26
+ * @returns {Routes} - Returns the Routes instance.
27
+ */
10
28
  controller(controller) {
11
29
  this.classController = controller;
30
+ // Sets group controller using Util instance
12
31
  this.util.setGroupController(controller);
13
32
  return this;
14
33
  }
34
+
35
+ /**
36
+ * Groups routes using a callback function.
37
+ * @param {Function} callback - Callback function for defining grouped routes.
38
+ * @returns {Routes} - Returns the Routes instance.
39
+ */
15
40
  group(callback) {
41
+ // Invokes the callback with a new Router instance and returns the Routes instance
16
42
  callback(
17
43
  new Router(
18
- this.app,
44
+ { basePath: this.basePath, app: this.app },
19
45
  this.prefixUrl,
20
46
  this.middlewares,
21
47
  this.classController
package/src/app/index.js CHANGED
@@ -17,44 +17,65 @@ class App {
17
17
  new Middleware(express, this.app);
18
18
  }
19
19
 
20
+ /**
21
+ * Method to parse command line arguments.
22
+ * @param {string[]} argv - Command line arguments.
23
+ * @returns {object} - Processed command line arguments.
24
+ */
20
25
  commandLineArgv(argv) {
21
26
  return getCommands(argv.slice(2));
22
27
  }
23
28
 
29
+ /**
30
+ * Method to define web routes.
31
+ * @returns {object} - Instance of Routes class for web routes.
32
+ */
24
33
  webRoute() {
25
- return new Routes(this.app);
34
+ return new Routes({ basePath: "", app: this.app });
26
35
  }
36
+
37
+ /**
38
+ * Method to define API routes.
39
+ * @returns {object} - Instance of Routes class for API routes.
40
+ */
27
41
  apiRoute() {
28
- return new Routes(this.app);
42
+ return new Routes({ basePath: "/api", app: this.app });
29
43
  }
44
+
45
+ /**
46
+ * Method to configure and start the server.
47
+ * @returns {object} - Object containing server run method and server instance.
48
+ */
30
49
  server() {
31
50
  const app = this.app;
32
- const PORT = process.env.PORT || process.env.NODE_ENV;
33
- const server = http.Server(app);
34
- const appError = new ErrorHandler(app);
35
- new SocketIo(server);
51
+ const PORT = process.env.PORT || process.env.NODE_ENV; // Set the port for the server
52
+ const server = http.Server(app); // Create HTTP server using Express app
53
+ const appError = new ErrorHandler(app); // Initialize error handling middleware
54
+ new SocketIo(server); // Set up Socket.IO for real-time communication
36
55
  return {
37
56
  run() {
38
- dbConnection();
39
- rootPath("routes/index");
40
- // rootPath("routes/api");
57
+ dbConnection(); // Establish connection to the database
58
+ rootPath("routes/api"); // Set root path for API routes
59
+ rootPath("routes/web"); // Set root path for web routes
41
60
 
42
- appError.errorRoutesHandler();
43
- app.use(appError.handler);
61
+ appError.errorRoutesHandler(); // Handle error routes
62
+ app.use(appError.handler); // Use error handling middleware
44
63
 
64
+ // Start listening on the specified port
45
65
  app.listen(PORT, () => {
46
- console.log(`Server running on port ${PORT}`);
66
+ console.log(`Server running on port ${PORT}`); // Log server start message
47
67
  if (process.send) {
48
- process.send("online");
68
+ process.send("online"); // Notify parent process that server is online
49
69
  }
50
70
  });
51
71
 
72
+ // Handle unhandled promise rejections
52
73
  process.on("unhandledRejection", (err) => {
53
- console.log({ unhandledRejection: err.message });
54
- process.exit(1);
74
+ console.log({ unhandledRejection: err.message }); // Log unhandled rejection error message
75
+ process.exit(1); // Exit process with failure status
55
76
  });
56
77
  },
57
- server,
78
+ server, // Return the HTTP server instance
58
79
  };
59
80
  }
60
81
  }
@@ -1,119 +1,107 @@
1
1
  const path = require("path");
2
2
  const fs = require("fs");
3
- const createController = require("../files/controller");
4
- const createModel = require("../files/model");
5
- const resourceController = require("../files/resoucesController");
6
- const createRequest = require("../files/request");
7
- const rootPath = require("app-root-path").path;
8
- const colors = require("colors");
3
+ const createController = require("../files/controller"); // Function to create a controller file
4
+ const createModel = require("../files/model"); // Function to create a model file
5
+ const resourceController = require("../files/resoucesController"); // Function to create a resource controller file
6
+ const createRequest = require("../files/request"); // Function to create a request file
7
+ const rootPath = require("app-root-path").path; // Module to get the root path of the application
8
+ const colors = require("colors"); // Module for adding color to console output
9
+
9
10
  class Command {
11
+ // Method to add a web controller
10
12
  addWeb(controllerName, modelName = false) {
11
13
  try {
12
- let webControllerPath = path.resolve(`${rootPath}/app/Controllers`);
14
+ let webControllerPath = path.resolve(`${rootPath}/app/Controllers`); // Resolve path to web controllers directory
13
15
  if (fs.existsSync(`${webControllerPath}/${controllerName}.js`)) {
14
- return console.log(`${controllerName} already exist`.yellow);
16
+ // Check if controller file already exists
17
+ return console.log(`${controllerName} already exist`.yellow); // Log a warning if controller already exists
15
18
  }
16
19
  if (modelName) {
20
+ // If model name is provided, create a resource controller
17
21
  fs.writeFileSync(
18
22
  `${webControllerPath}/${controllerName}.js`,
19
23
  resourceController(controllerName, modelName)
20
24
  );
21
- return console.log(`${controllerName} added successfully`.green);
25
+ return console.log(`${controllerName} added successfully`.green); // Log success message
22
26
  }
23
27
  fs.writeFileSync(
24
28
  `${webControllerPath}/${controllerName}.js`,
25
- createController(controllerName)
29
+ createController(controllerName) // Create a basic controller file
26
30
  );
27
31
 
28
- return console.log(`${controllerName} added successfully`.green);
32
+ return console.log(`${controllerName} added successfully`.green); // Log success message
29
33
  } catch (err) {
30
- console.log(`${controllerName} admin controller not added`.red);
34
+ console.log(`${controllerName} admin controller not added`.red); // Log error if controller addition fails
31
35
  }
32
36
  }
33
37
 
34
- // addAdmin(controllerName, modelName = false) {
35
- // try {
36
- // let adminPath = path.resolve(`${rootPath}/app/Controllers/Admin`);
37
- // if (fs.existsSync(`${adminPath}/${controllerName}.js`)) {
38
- // return console.log(`${controllerName} already exist`.yellow);
39
- // }
40
- // if (modelName) {
41
- // fs.writeFileSync(
42
- // `${adminPath}/${controllerName}.js`,
43
- // resourceController(controllerName, modelName)
44
- // );
45
- // return console.log(`${controllerName} added successfully`.green);
46
- // }
47
- // fs.writeFileSync(
48
- // `${adminPath}/${controllerName}.js`,
49
- // createController(controllerName)
50
- // );
51
-
52
- // return console.log(`${controllerName} added successfully`.green);
53
- // } catch (err) {
54
- // console.log(`${controllerName} admin controller not added`.red);
55
- // }
56
- // }
57
-
38
+ // Method to add an API controller
58
39
  addApi(controllerName, modelName = false) {
59
40
  try {
60
- let apiPath = path.resolve(`${rootPath}/app/Controllers/Api`);
41
+ let apiPath = path.resolve(`${rootPath}/app/Controllers/Api`); // Resolve path to API controllers directory
61
42
  if (fs.existsSync(`${apiPath}/${controllerName}.js`)) {
43
+ // Check if API controller file already exists
62
44
  return console.log(
63
45
  `${controllerName} api controller already exist`.yellow
64
- );
46
+ ); // Log a warning if API controller already exists
65
47
  }
66
48
  if (modelName) {
49
+ // If model name is provided, create a resource controller
67
50
  fs.writeFileSync(
68
51
  `${apiPath}/${controllerName}.js`,
69
52
  resourceController(controllerName, modelName)
70
53
  );
71
- return console.log(`${controllerName} added successfully`.green);
54
+ return console.log(`${controllerName} added successfully`.green); // Log success message
72
55
  }
73
56
  fs.writeFileSync(
74
57
  `${apiPath}/${controllerName}.js`,
75
- createController(controllerName)
58
+ createController(controllerName) // Create a basic controller file
76
59
  );
77
- return console.log(`${controllerName} added successfully`.green);
60
+ return console.log(`${controllerName} added successfully`.green); // Log success message
78
61
  } catch (err) {
79
62
  console.log(err.message);
80
- console.log(`${controllerName} api controller not added`.red);
63
+ console.log(`${controllerName} api controller not added`.red); // Log error if controller addition fails
81
64
  }
82
65
  }
83
66
 
67
+ // Method to add a model
84
68
  addModel(modelName) {
85
69
  try {
86
- let modelPath = path.resolve(`${rootPath}/app/Models`);
70
+ let modelPath = path.resolve(`${rootPath}/app/Models`); // Resolve path to models directory
87
71
  if (fs.existsSync(`${modelPath}/${modelName}.js`)) {
88
- return console.log(`${modelName} model already exist`.yellow);
72
+ // Check if model file already exists
73
+ return console.log(`${modelName} model already exist`.yellow); // Log a warning if model already exists
89
74
  }
90
- fs.writeFileSync(`${modelPath}/${modelName}.js`, createModel(modelName));
91
- return console.log(`${modelName} model added successfully`.green);
75
+ fs.writeFileSync(`${modelPath}/${modelName}.js`, createModel(modelName)); // Create a model file
76
+ return console.log(`${modelName} model added successfully`.green); // Log success message
92
77
  } catch (err) {
93
- return console.log(`${modelName} model not added`.red);
78
+ return console.log(`${modelName} model not added`.red); // Log error if model addition fails
94
79
  }
95
80
  }
96
81
 
82
+ // Method to add a request file
97
83
  addRequest(requestName) {
98
84
  try {
99
- let requestPath = path.resolve(`${rootPath}/app/Request`);
85
+ let requestPath = path.resolve(`${rootPath}/app/Request`); // Resolve path to request files directory
100
86
  if (fs.existsSync(`${requestPath}/${requestName}.js`)) {
101
- return console.log(`${requestName} already exist`.yellow);
87
+ // Check if request file already exists
88
+ return console.log(`${requestName} already exist`.yellow); // Log a warning if request file already exists
102
89
  }
103
90
 
104
91
  fs.writeFileSync(
105
92
  `${requestPath}/${requestName}.js`,
106
- createRequest(requestName)
93
+ createRequest(requestName) // Create a request file
107
94
  );
108
- return console.log(`${requestName} added successfully`.green);
95
+ return console.log(`${requestName} added successfully`.green); // Log success message
109
96
  } catch (err) {
110
- return console.log(`${requestName} request not added`.red, { err });
97
+ return console.log(`${requestName} request not added`.red, { err }); // Log error if request addition fails
111
98
  }
112
99
  }
113
100
 
101
+ // Method to handle a command not found
114
102
  notFound() {
115
- return console.log(`Command not found`.bgRed);
103
+ return console.log(`Command not found`.bgRed); // Log a message indicating the command was not found
116
104
  }
117
105
  }
118
106
 
119
- module.exports = new Command();
107
+ module.exports = new Command(); // Export an instance of the Command class