Eco-Sync Waste Management
Project Overview and Objectives
Can you give a brief overview of your project "Eco-Sync: Waste Management in DNCC"?
Can you describe the key features of the website?
User Login and No Registration System (Only Admin can give access to website by creating user with details)
In Login there is forget password options (Can Reset Password with Email Verification)
Dynamic Role based and Permission Access to website
Different Users : Admin, STS Manager, Landfill Manager and Unassigned
Admin 👍
Dynamic Real time data with analytics dashboard
Create User Form, Search user , Edit and delete users, Show user lists and Shorting option and Finally can change user roles
Create New Role and Change Role Permission dynamically
Add New Vehicle with Information and checks their data
Add New STS manager with Information and checks their data and assign a sts to that manager
Add Landfill Manager with Information and checks their data and assign a lanfill to that manager
User Profile change his information's and logout
STS Manager
Landfill Manager
Unassigned
What were the primary objectives and requirements set by the judges for this project?
They Provided a complete requirement in PDF
Including Diagrams (Backend and Activity), API Documentations, PowerPoint Presentation
How did you ensure that all the judges' requirements were met within the 8-day timeframe?
Continuous Planning
Doing Key Features First
Taking Time When I get. It Tooks 5 days for me to crack a idea for implementing the role-based system
Diving the tasks based on their skills. For example, I took the complex tasks giving my teammates for freedom to the easier tasks
Daily Meeting at 8 pm describing what each one has done during whole day
Although we didn't meet all the requirements but still, we became 2nd in 2nd preliminary based on this project
Technical Implementation
Can you explain the architecture of your website?
What technologies and frameworks did you use to develop the website?
Frontend: ReactJS, TailwindCSS
Backend: NodeJs, ExpressJS
Database: MongoDB
Collaboration: Github
Documentation: Swagger.js
Did you work in a team or individually on this project? If in a team, what was your specific role?
Ans:
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.
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.
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
What data structures or databases did you use for managing user and vehicle data?
NoSQL Databases: MongoDB
Features and Functionality
How does the real-time route checking feature work?
How did you integrate Google Maps API for real-time route checking?
What additional features did you include, such as user management and data entry for vehicles?
User Management:
Create a new user with details
Assign/Update a role to user
Edit and Delete User Details
Sorting User Information List
Search User with ID
Vehicle Management:
Vehicle Entry form with backend + Validation
Vehicle Information Table
Frontend of Billing Functionalities.
How do you ensure the scalability and security of the website?
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,
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
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
What were the most significant challenges you faced during this project, and how did you address them?
Role and Permission Based Access System in Website
Intregating Google Map in Website
If you had more time, what additional features or improvements would you implement?
Truck Scheduling System
What did you learn from this project that you can apply to future projects?
How to integrate Role and Permission Based Access System in Website?
This is my first project with MongoDB which helped me lot learning it more
?
Soft Skills and Problem Solving
How did you approach problem-solving when you encountered a technical issue during the project?
Can you provide an example of a particularly challenging problem you solved and how you did it?
JavaScript
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.
What JavaScript ES6 features did you leverage in your project and why?
Arrow Functions: Used for concise syntax and to maintain the correct
this
context in callbacks.const addUser = (user) => { // Add user logic };
Template Literals: Used for constructing strings with embedded expressions, making the code cleaner.
const welcomeMessage = Welcome, ${user.name}!
;Destructuring Assignment: Used for extracting values from objects and arrays, which simplifies code and improves readability.
const { name, email } = user;
Modules: Used to organize the codebase into separate files, promoting modularity and reusability.
import { addUser, deleteUser } from './userService';
ReactJS
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
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.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.
Can you discuss a particular challenge you faced with ReactJS and how you resolved it?
Dynamic Role Based and Permissions Based Routing
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.
How did you design and implement the role-based authentication and permission system?
What challenges did you face while implementing dynamic role and permission management, and how did you overcome them?
Can you explain how you implemented dynamic role-based authentication in ReactJS?
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.
Firstly, I use JWT token for authentication and saved it in browser cookie with some information like (user id , role , name)
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
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.
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
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, }, });
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 ApproachSimplicity: This approach is straightforward and keeps the logic within the route handler, making it easy to follow.
Direct Query Execution: Directly querying the database within the route ensures that you always have the most up-to-date data.
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");
}
});
What indexing strategies did you use to optimize query performance in MongoDB?
How did you ensure data validation and integrity in MongoDB?
JWT Token
How did you handle token expiration and refresh in your application?
res.cookie("access_token", "", { expires: new Date(0), httpOnly: true });
How did you implement JWT (JSON Web Token) for authentication and authorization?
How did you handle user authentication and authorization securely using JWT tokens?
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
Can you explain the middleware you used in Express.js and their purposes?
How did you handle routing and error handling in your Node.js application?
Ans:
Structure of the Node.js and Express.js ServerThe server is structured to maintain clarity and separation of concerns. Here’s a high-level overview:
Middleware Setup: Middleware for JSON parsing, URL encoding, and CORS are configured.
Swagger Integration: Swagger is used for API documentation.
MongoDB Connection: Mongoose is used to connect to MongoDB.
Routing: Different routes are handled by importing and using route modules.
Error Handling: Middleware for handling 404 and other errors.
Server Initialization: The server is started and listens on a specified port.
Middleware Used in Express.js and Their Purposesexpress.json()
:Purpose: To parse incoming request bodies in JSON format.
Usage:
app.use(express.json());
express.urlencoded()
:Purpose: To parse incoming request bodies with URL-encoded payloads.
Usage:
app.use(express.urlencoded({ extended: true }));
cors()
:Purpose: To enable Cross-Origin Resource Sharing (CORS) which allows the server to handle requests from different origins.
Usage:
app.use(cors());
swagger-ui-express
:Purpose: To serve and display API documentation using Swagger.
Usage:
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));
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 ApplicationRouting 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:
Index.js
Routes
Product.route.js
User.route.js
Models
Product.model.js
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
How did you integrate ReactJS with your Node.js backend?
How did you ensure secure communication between your frontend and backend?
Ans:
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
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.
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.
Why use Axios in Frontend Communication ?
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.
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 responsesTimeouts: Axios supports setting timeouts directly in the configuration, allowing developers to specify how long to wait for a response before giving up.
Progress Events: Axios supports tracking the progress of uploads and downloads, which is useful for displaying upload/download progress bars in the UI.
Browser Compatibility: While
fetch()
is natively supported in modern browsers, Axios extends its compatibility to older browserAutomatic 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
How did you optimize the performance of your ReactJS application?
What measures did you take to ensure the scalability of your Node.js server?
How did you handle database connection management and pooling in MongoDB?
Debugging and Troubleshooting
Can you describe a challenging bug you encountered and how you resolved it?
How did you monitor and log application errors in both the frontend and backend?
Last updated