Eco-Sync Waste Management

Project Overview and Objectives

  1. Can you give a brief overview of your project "Eco-Sync: Waste Management in DNCC"?

  2. Can you describe the key features of the website?

    1. User Login and No Registration System (Only Admin can give access to website by creating user with details)

    2. In Login there is forget password options (Can Reset Password with Email Verification)

    3. Dynamic Role based and Permission Access to website

    4. Different Users : Admin, STS Manager, Landfill Manager and Unassigned

    5. Admin 👍

      1. Dynamic Real time data with analytics dashboard

      2. Create User Form, Search user , Edit and delete users, Show user lists and Shorting option and Finally can change user roles

      3. Create New Role and Change Role Permission dynamically

      4. Add New Vehicle with Information and checks their data

      5. Add New STS manager with Information and checks their data and assign a sts to that manager

      6. Add Landfill Manager with Information and checks their data and assign a lanfill to that manager

      7. User Profile change his information's and logout

    6. STS Manager

    7. Landfill Manager

    8. Unassigned

  3. What were the primary objectives and requirements set by the judges for this project?

    1. They Provided a complete requirement in PDF

    2. Including Diagrams (Backend and Activity), API Documentations, PowerPoint Presentation

  4. How did you ensure that all the judges' requirements were met within the 8-day timeframe?

    1. Continuous Planning

    2. Doing Key Features First

    3. Taking Time When I get. It Tooks 5 days for me to crack a idea for implementing the role-based system

    4. Diving the tasks based on their skills. For example, I took the complex tasks giving my teammates for freedom to the easier tasks

    5. Daily Meeting at 8 pm describing what each one has done during whole day

    6. Although we didn't meet all the requirements but still, we became 2nd in 2nd preliminary based on this project

Technical Implementation

  1. Can you explain the architecture of your website?

  2. What technologies and frameworks did you use to develop the website?

    1. Frontend: ReactJS, TailwindCSS

    2. Backend: NodeJs, ExpressJS

    3. Database: MongoDB

    4. Collaboration: Github

    5. Documentation: Swagger.js

  3. Did you work in a team or individually on this project? If in a team, what was your specific role?

    Ans:

    1. Lead Role: I have to understand the requirement properly and the team capability. And assigning the tasks to my mates based on their skills set... I also give them enough freedom to choose which feature they can implement.

    2. Full-Stack Role: I mainly choose hard topics or key feature that goanna plays crucial role. So, I have to work on both backend and frontend parallelly completing a feature. Sometimes I also have to create a base so that can understand and learn from this for implementing similiar features.

    3. Testing and Helping Role: I also have ensured they are doing tasks right, help them whenever they got stuck in problem. I so have to handle both my tasks and, in the meantime, monitoring their tasks

  4. What data structures or databases did you use for managing user and vehicle data?

    1. NoSQL Databases: MongoDB

Features and Functionality

  1. How does the real-time route checking feature work?

  2. How did you integrate Google Maps API for real-time route checking?

    Ans: Google Map Route Optimization

  3. What additional features did you include, such as user management and data entry for vehicles?

    1. User Management:

      1. Create a new user with details

      2. Assign/Update a role to user

      3. Edit and Delete User Details

      4. Sorting User Information List

      5. Search User with ID

    2. Vehicle Management:

      1. Vehicle Entry form with backend + Validation

      2. Vehicle Information Table

    3. Frontend of Billing Functionalities.

  4. How do you ensure the scalability and security of the website?

    1. Here Scalability means In Future Website have more roles and permissions. For example, in final, there was a new role "Contract Manager". So, built the system in way, admin can create role and permission any time rather hand coding,

    2. Security means as all routes are restricted, you cannot bypass routes until admin give you access to that route. So, it increases the overall privacy of different user.

Documentation and Deployment

  1. Can you discuss the API documentation you created?

    Ans: Used Swagger.js

// Swagger For API Documentation
const swaggerUi = require("swagger-ui-express");
const swaggerDocument = require("./swagger-output.json");
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));

Reflection and Future Improvements

  1. What were the most significant challenges you faced during this project, and how did you address them?

    1. Role and Permission Based Access System in Website

    2. Intregating Google Map in Website

  2. If you had more time, what additional features or improvements would you implement?

    1. Truck Scheduling System

  3. What did you learn from this project that you can apply to future projects?

    1. How to integrate Role and Permission Based Access System in Website?

    2. This is my first project with MongoDB which helped me lot learning it more

    3. ?

Soft Skills and Problem Solving

  1. How did you approach problem-solving when you encountered a technical issue during the project?

  2. Can you provide an example of a particularly challenging problem you solved and how you did it?

JavaScript

  1. How did you handle asynchronous operations in JavaScript, particularly for API calls and database interactions?

    Ans: For API calls from the frontend, I used the Axios API and wrapped these calls in async functions. This approach allowed me to wait for the API responses without blocking the execution of other code.

    On the backend, I used async functions and await for database operations with MongoDB. For instance, when querying the database for user information, I ensured the operations were performed asynchronously to avoid blocking the event loop.

  2. What JavaScript ES6 features did you leverage in your project and why?

    1. Arrow Functions: Used for concise syntax and to maintain the correct this context in callbacks. const addUser = (user) => { // Add user logic };

    2. Template Literals: Used for constructing strings with embedded expressions, making the code cleaner. const welcomeMessage = Welcome, ${user.name}!;

    3. Destructuring Assignment: Used for extracting values from objects and arrays, which simplifies code and improves readability. const { name, email } = user;

    4. Modules: Used to organize the codebase into separate files, promoting modularity and reusability. import { addUser, deleteUser } from './userService';

ReactJS

  1. How did you structure your ReactJS application in terms of components and state management?

    • src/

      • Dashboard/

        • components/

          • layout

            • Header.jsx

            • Layout.jsx

            • Sidebar.jsx

          • Dashboard Related Componets

        • lib/

          • Sidebar Constants and Mapping

        • pages/

          • Every Section of Websile in Different Folder

      • ForgetPass/

      • Home/

      • Login/

      • App.jsx

      • Main.js

  2. How did you manage side effects in your React application (e.g., using hooks like useEffect)?

    Ans: useEffects: The useEffect hook allowed me to perform side effects in functional components.

    1. Data Fetching:

      • When components mounted or specific state variables changed, I used useEffect to fetch data from the backend. This ensured that the latest data was always available to the users.

  3. Can you discuss a particular challenge you faced with ReactJS and how you resolved it?

    1. Dynamic Role Based and Permissions Based Routing

    2. Using React Hooks Properly to Handle Api and show updated data real-time to user

    One significant challenge I faced was efficiently managing global state and synchronizing it across multiple components, particularly for user authentication and role-based permissions.

  4. How did you design and implement the role-based authentication and permission system?

  5. What challenges did you face while implementing dynamic role and permission management, and how did you overcome them?

  6. Can you explain how you implemented dynamic role-based authentication in ReactJS?

  7. What libraries or tools did you use for state management in ReactJS? (e.g., Redux, Context API)

    Ans: Although there are better approaches but in that time i didn't know about those features i Intergrated it on my own style and logic because I have less time to learn something new in that time.

    1. Firstly, I use JWT token for authentication and saved it in browser cookie with some information like (user id , role , name)

    2. Then in backend database I have 3 table for this. One is for list of roles and roles id. Second List of permission and permission id. Third a mapping of roleid, permissionid and status

    3. In Frontend, in main app.jsx routing - I first check for user cookie based on that cookie data i check user roles dynamically using api from backend and get all the available permissions of that user from api Json. Now set those permission data using boolen variable in frontend. Now in routing i restricted a route only if that Boolean variable is true.

    4. Suppose User Role want to go dashboard. I will check for if the user's dashboard variable is true or not. Only then he can go to that route. Using the same logic i hides many features-based role from different user in different section

import { KJUR } from "jsrsasign"; // Importing the KJUR module from jsrsasign for token parsing
import Dashboard from "./Dashboard/pages/Dashboard.jsx"; // Importing the Dashboard component
import { useState, useEffect } from "react"; // Importing hooks from React
import axios from "axios"; // Importing axios for making HTTP requests
import { BrowserRouter, Routes, Route } from "react-router-dom"; // Importing necessary components from react-router-dom for routing
import Layout from "./Layout"; // Assuming there's a Layout component
import NOACCESS from "./NOACCESS"; // Assuming there's a NOACCESS component

function App() {
  // Retrieving the access token from localStorage
  const token = localStorage.getItem("access_token");
  let userRole = null;

  // If a token exists, parse it to get the user role
  if (token) {
    const decodedToken = KJUR.jws.JWS.parse(token); // Parsing the token
    userRole = decodedToken.payloadObj?.role; // Extracting the role from the token
    console.log(userRole); // Logging the user role
  }

  // State to manage dashboard access
  const [dashboard, setDashboard] = useState(false);

  // Effect to check permissions based on the user role
  useEffect(() => {
    if (userRole) {
      axios
        .get(
          `http://localhost:3000/rbac/check/${encodeURIComponent(
            userRole
          )}/permissions`
        ) // Making a GET request to check permissions
        .then((response) => {
          response.data.forEach((permission) => {
            switch (permission.permissionName) {
              case "Dashboard":
                setDashboard(permission.status); // Setting the dashboard access based on the permission status
                break;
            }
          });
        })
        .catch((error) => {
          console.error("Error checking permissions:", error); // Handling any errors
        });
    }
  }, [userRole]); // The effect depends on the userRole

  return (
    <BrowserRouter>
      <Routes>
        <Route path="/dashboard" element={<Layout />}>
          <Route index element={dashboard ? <Dashboard /> : <NOACCESS />} /> {/* Conditional rendering based on dashboard access */}
        </Route>
      </Routes>
    </BrowserRouter>
  );
}

export default App; // Exporting the App component

MongoDB

  1. How did you design your MongoDB schema for managing users, roles, permissions, and vehicle data?

    const UserScheme = new Schema({ email: { type: String, unique: true, }, password: { type: String, }, name: { type: String, }, phone: { type: Number, }, role: { type: String, default: "UNASSIGNED", }, });

    const RoleSchema = new Schema({ roleId: { type: Number, required: true, unique: true, }, roleName: { type: String, required: true, }, });

    const PermissionSchema = new Schema({ roleId: { type: Number, required: true, }, permissionName: { type: String, required: true, }, status: { type: Boolean, required: true, }, });

    const VehicleScheme = new Schema({ regnumber: { type: String, required: true, }, type: { type: String, required: true, }, capacity: { type: String, required: true, }, loadedfuelcost: { type: String, required: true, }, unloadedfuelcost: { type: String, required: true, }, });

  2. Can you explain how you handled relationships between different collections in MongoDB?

    Ans: Your approach to handling relationships between collections directly within the Express route is effective for your use case. It ensures that the logic for finding roles and permissions is encapsulated within the route handler, which is beneficial for straightforward applications.

    Advantages of This Approach

    1. Simplicity: This approach is straightforward and keeps the logic within the route handler, making it easy to follow.

    2. Direct Query Execution: Directly querying the database within the route ensures that you always have the most up-to-date data.

    3. Modularization: By using Mongoose models and route handlers, you keep your code modular, which can be easily extended or modified.

const express = require('express');
const router = express.Router();
const Role = require('../models/Role'); // Import Role model
const Permission = require('../models/Permission'); // Import Permission model

router.get("/check/:roleName/permissions", async (req, res, next) => {
    const { roleName } = req.params;

    try {
        // Find the role ID based on the role name
        const role = await Role.findOne({ roleName });
        if (!role) {
            return res.status(404).send("Role not found");
        }
        console.log(role);

        // Ensure the roleId is a number
        const roleId = Number(role.roleId);
        if (isNaN(roleId)) {
            return res.status(400).send("Invalid role ID");
        }
        console.log(roleId);

        // Find all permissions that match the role ID and have a status of true
        const permissions = await Permission.find({ roleId, status: true });
        res.json(permissions);
    } catch (err) {
        console.error(err.message);
        res.status(500).send("Server Error");
    }
});
  1. What indexing strategies did you use to optimize query performance in MongoDB?

  2. How did you ensure data validation and integrity in MongoDB?

JWT Token

  1. How did you handle token expiration and refresh in your application?

    res.cookie("access_token", "", { expires: new Date(0), httpOnly: true });

  2. How did you implement JWT (JSON Web Token) for authentication and authorization?

  3. How did you handle user authentication and authorization securely using JWT tokens?

  4. Can you explain the process of generating and validating JWT tokens in your application?

router.post("/login", async (req, res, next) => {
  const { email, password } = req.body;
  console.log(email, password);
  try {
    const validUser = await User.findOne({ email });
    if (!validUser) return next(errorHandle(404, "User not found!"));
    const validPassword = bcryptjs.compareSync(password, validUser.password);
    if (!validPassword) return next(errorHandle(401, "Wrong credentials!"));
    const token = jwt.sign(
      { id: validUser._id, email: validUser.email, role: validUser.role },
      JWT_SECRET
    );
    const { password: pass, ...rest } = validUser._doc;

    res
      .cookie("access_token", token, { httpOnly: false })
      .status(200)
      .json({ access_token: token });
  } catch (error) {
    next(error);
  }
});

Node.js and Express.js

  1. Can you explain the middleware you used in Express.js and their purposes?

  2. How did you handle routing and error handling in your Node.js application?

    Ans:

    Structure of the Node.js and Express.js Server

    The server is structured to maintain clarity and separation of concerns. Here’s a high-level overview:

    1. Middleware Setup: Middleware for JSON parsing, URL encoding, and CORS are configured.

      1. Swagger Integration: Swagger is used for API documentation.

      2. MongoDB Connection: Mongoose is used to connect to MongoDB.

      3. Routing: Different routes are handled by importing and using route modules.

      4. Error Handling: Middleware for handling 404 and other errors.

      5. Server Initialization: The server is started and listens on a specified port.

    Middleware Used in Express.js and Their Purposes

    1. express.json():

      • Purpose: To parse incoming request bodies in JSON format.

      • Usage: app.use(express.json());

    2. express.urlencoded():

      • Purpose: To parse incoming request bodies with URL-encoded payloads.

      • Usage: app.use(express.urlencoded({ extended: true }));

    3. cors():

      • Purpose: To enable Cross-Origin Resource Sharing (CORS) which allows the server to handle requests from different origins.

      • Usage: app.use(cors());

    4. swagger-ui-express:

      • Purpose: To serve and display API documentation using Swagger.

      • Usage: app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));

    5. Custom Error Handling Middleware:

      • 404 Error Handling: Captures requests to undefined routes and forwards an error.

        javascriptCopy codeapp.use((req, res, next) => {
          const err = new Error("Not Found");
          err.status = 404;
          next(err);
        });
      • General Error Handling: Sends a JSON response with the error details.

        javascriptCopy codeapp.use((err, req, res, next) => {
          res.status(err.status || 500);
          res.send({
            error: {
              status: err.status || 500,
              message: err.message,
            },
          });
        });

    Routing in the Node.js Application

    Routing is handled by importing and using different route modules for various parts of the application. Each route module corresponds to a specific feature or entity in the application.

    Example of routing:

    1. Index.js

    2. Routes

      1. Product.route.js

      2. User.route.js

    3. Models

      1. Product.model.js

      2. User.model.js

    const productRouter = require("./Routes/Product.route.js");
    app.use("/products", productRouter);
    
    const userRouter = require("./Routes/user.route.js");
    app.use("/user", userRouter);

    Each route module (Product.route.js, user.route.js, etc.) contains the route definitions and the associated controllers that handle the requests for those routes.

Integration and Deployment

  1. How did you integrate ReactJS with your Node.js backend?

  2. How did you ensure secure communication between your frontend and backend?

    Ans:

    1. Backend : First, I created a backend server on port 3000 maintaining CORS

      • On the Node.js backend, I typically use Express.js, a minimalist web framework, to handle incoming HTTP requests. Express provides a robust infrastructure for building RESTful APIs that can be consumed by the React frontend

    2. Frontend : First, I created a frontend server on port 5173 maintaining CORS

      • In the frontend, I use Axios to communicate with the Node.js backend by making API calls to fetch or send data. This ensures a seamless flow of data between the client-side and server-side applications.

    3. CORS (Cross-Origin Resource Sharing): I configure CORS settings on the backend to restrict access to API endpoints only from trusted origins, preventing unauthorized access to sensitive data.

    4. Why use Axios in Frontend Communication ?

      1. Axios provides a simpler and more convenient interface for making HTTP requests. It automatically transforms JSON data to and from the response, simplifying the handling of data.

      2. Axios has a more straightforward error handling mechanism. When using fetch(), errors are only rejected on network failure, whereas Axios treats any HTTP status outside the range of 200-299 as an error, providing a consistent way to handle errors across different types of HTTP responses

      3. Timeouts: Axios supports setting timeouts directly in the configuration, allowing developers to specify how long to wait for a response before giving up.

      4. Progress Events: Axios supports tracking the progress of uploads and downloads, which is useful for displaying upload/download progress bars in the UI.

      5. Browser Compatibility: While fetch() is natively supported in modern browsers, Axios extends its compatibility to older browser

      6. Automatic JSON Data Transformation: As mentioned earlier, Axios automatically transforms JSON data to and from the response, reducing the need for manual parsing and serializatio

// Importing Packages
const express = require("express");
const app = express();
const cors = require("cors");
app.use(express.json()); // Handle Json Body
app.use(express.urlencoded({ extended: true })); // Handle URL-encoded data
app.use(cors()); // allow cross origin policy

// Swagger For API Documentation
const swaggerUi = require("swagger-ui-express");
const swaggerDocument = require("./swagger-output.json");
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));

// Conntection MongoDB
const mongoose = require("mongoose");
mongoose
  .connect(
    `mongodb+srv://wastemanagement.ug8d6fr.mongodb.net/?retryWrites=true&w=majority&appName=WasteManagement/`,
    {
      dbName: "WasteManagement",
      user: "promimojumder8",
      pass: "aXipRG6t3JTC2dpG",
      useNewUrlParser: true,
      useUnifiedTopology: true,
    }
  )
  .then(() => console.log("MongoDB is connected"))
  .catch((err) => console.log("Failed to connect to MongoDB", err));

// Product routes
const productRouter = require("./Routes/Product.route.js");
app.use("/products", productRouter);

Performance and Optimization

  1. How did you optimize the performance of your ReactJS application?

  2. What measures did you take to ensure the scalability of your Node.js server?

  3. How did you handle database connection management and pooling in MongoDB?

Debugging and Troubleshooting

  1. Can you describe a challenging bug you encountered and how you resolved it?

  2. How did you monitor and log application errors in both the frontend and backend?

Last updated