Hostel
Hostel
management, hostel management, and more, using Express.js, Sequelize ORM, and various utilities
like bcrypt for hashing passwords. Here's an overview of what the different parts of the code are
doing:
Workflow:
o Compares the provided password with the hashed password stored in the database.
Workflow: Sets the AUTHCOOKIE to null, effectively logging the user out.
Workflow:
o Uses the user's ID (extracted from the request) to fetch their data from the database,
including their role.
o Returns the user details if found, or an error message if the user doesn't exist.
Workflow:
o If not, it creates the new role and responds with a success message.
Purpose: Adds a new user to the system (either as a regular user or admin).
Workflow:
o Generates a random password, hashes it, and associates the user with the provided
role.
Workflow:
o For adding a hostel, it checks if a hostel with the same name already exists.
o For deleting a hostel, it ensures the hostel exists and then deletes it.
Purpose: Manages blocks within a hostel (add, get all, and get by hostel ID).
Workflow:
o For adding a block, it ensures the hostel exists and that the block name is unique
within the hostel.
o For fetching blocks, it either fetches all blocks or fetches blocks by hostel ID.
Workflow:
o Validates the provided room details (block ID, room number, and capacity).
o Checks if the room already exists in the specified block and then adds it.
Error Handling:
Each function is wrapped with a catchAsyncErrors middleware to handle any async errors
gracefully.
Error messages are passed through an errorHandler utility, which formats the error messages
based on the environment (development or production).
Utility Functions:
Observations:
The code is structured well with proper error handling and asynchronous operations.
It uses Sequelize ORM for interacting with the database and models like Users, Roles,
Hostels, Blocks, and Rooms for various operations.
The user and hostel management functions ensure that actions like adding users or hostels
only happen if the required conditions are met (e.g., unique email, valid role).
If you need further explanation or modifications to specific parts of this code, feel free to ask!
Here is the documentation for the middleware functionality without the code:
Middleware: Authentication & Authorization
1. isAuthenticated Middleware
Purpose:
Verifies if the user is authenticated by checking for a valid JWT token in the cookies. It
ensures that only logged-in users can access protected routes.
Functionality:
o If the cookie is absent, the request is rejected with a 401 Unauthorized error and the
message "You're not logged in."
o Verifies the JWT token using the secret key stored in the environment variables.
o Decodes the token to extract the user’s ID and fetches the user's data from the
database, including their associated role.
Error Handling:
2. authorizeRoles Middleware
Purpose:
Restricts access to certain routes based on the user's role. It allows only users with specific
roles to access protected resources.
Functionality:
o Compares the role of the currently authenticated user (req.user.role) with the
allowed roles.
o If the user’s role is not in the allowed list, access is denied with a 403 Forbidden
error and the message "Cannot access the resource."
o If the user’s role matches one of the allowed roles, the request proceeds to the next
middleware or route handler.
Purpose:
A custom error handling utility that formats and sends error responses. It includes:
o Error Message: A descriptive message of what went wrong (e.g., "You're not logged
in").
o Status Code: Corresponding HTTP status codes such as 401 Unauthorized or 403
Forbidden.
Summary:
These middlewares handle authentication and role-based access control in the application. The
isAuthenticated middleware ensures that the user is logged in, while authorizeRoles enforces access
control based on the user’s role, restricting access to only authorized users.
1. Users Table
Columns:
o name (STRING): User's full name (validated to allow alphabets, spaces, and
hyphens).
Associations:
2. Roles Table
Columns:
Associations:
3. Hostels Table
Associations:
4. Blocks Table
Columns:
Associations:
5. Rooms Table
Columns:
Associations:
6. Tenants Table
Columns:
o id (UUID): Unique identifier for each tenant record (Primary Key).
o room_id (UUID): Foreign key referencing the Rooms table (Room assigned to the
tenant).
Associations:
Users ↔ Roles: Each user has one role, but each role can be associated with multiple users
(One-to-Many relationship).
Hostels ↔ Blocks: Each hostel can have multiple blocks, but each block belongs to only one
hostel (One-to-Many relationship).
Blocks ↔ Rooms: Each block can have multiple rooms, but each room belongs to only one
block (One-to-Many relationship).
Users ↔ Tenants: Each user can have one tenant record (One-to-One relationship).
Rooms ↔ Tenants: Each room can accommodate multiple tenants, but each tenant is
assigned to a single room (One-to-Many relationship).
This schema outlines the structure of the application database, covering user management, hostel
and room allocation, and role-based access control, with clear relationships between the tables.
1. User Routes
Route: /login
Method: POST
Middleware:
Controller: login
Request Body:
Route: /logout
Method: POST
Middleware:
Controller: logout
Response:
Route: /dashboard
Method: GET
Middleware:
Controller: getuserdetails
Response:
2. Admin Routes
Route: /add/role
Method: POST
Middleware:
Controller: addRole
Request Body:
Response:
Route: /add/user
Method: POST
Middleware:
o authorizeRoles: Ensures the user has the necessary role (SUPER_ADMIN) to add
users.
Controller: addUser
Request Body:
Response:
Route: /add/admin
Method: POST
Middleware:
o authorizeRoles: Ensures the user has the necessary role (SUPER_ADMIN) to add
admin users.
Controller: addAdminUser
Request Body:
Response:
Route: /add/hostel
Method: POST
Middleware:
o authorizeRoles: Ensures the user has the necessary role (SUPER_ADMIN) to add
hostels.
Controller: addHostel
Request Body:
Response:
Route: /add/hostel/block
Method: POST
Middleware:
o authorizeRoles: Ensures the user has the necessary role (SUPER_ADMIN) to add
blocks to hostels.
Controller: addHostelBlock
Request Body:
Response:
Route: /add/hostel/block/room
Method: POST
Middleware:
o authorizeRoles: Ensures the user has the necessary role (SUPER_ADMIN) to add
rooms to blocks.
Controller: addRoom
Request Body:
Response:
Route: /get/hostels/all
Method: GET
Middleware:
o authorizeRoles: Ensures the user has the necessary role (SUPER_ADMIN) to view all
hostels.
Controller: getAllHostels
Response:
Route: /get/blocks/all
Method: GET
Middleware:
o authorizeRoles: Ensures the user has the necessary role (SUPER_ADMIN) to view all
blocks.
Controller: getAllHostelBlocks
Response:
Route: /delete/hostel/:hostel_id
Method: DELETE
Middleware:
o authorizeRoles: Ensures the user has the necessary role (SUPER_ADMIN) to delete
the hostel.
Controller: deleteHostel
Request Parameters:
Response:
Route: /get/blocks/:hostel_id
Method: GET
Middleware:
o isAuthenticated: Verifies the user is authenticated.
o authorizeRoles: Ensures the user has the necessary role (SUPER_ADMIN) to view
blocks.
Controller: getBlocksByHostelId
Request Parameters:
Response:
Route: /get/rooms/:block_id
Method: GET
Middleware:
o authorizeRoles: Ensures the user has the necessary role (SUPER_ADMIN) to view
rooms.
Controller: getRoomsByBlockId
Request Parameters:
Response:
This documentation outlines all the available routes, their methods, descriptions, required
middlewares, request bodies/parameters, and possible responses.
Here is the documentation for the code you provided, which sets up and runs an Express application
with environment variables, static file serving, and error handling:
o Purpose: Loads environment variables from the .env file into process.env. The .env
file is located in the config folder.
2. Middleware Setup
cookieParser()
o Purpose: Parses cookies attached to the incoming request and makes them
accessible via req.cookies.
express.json()
o Purpose: Parses incoming JSON requests and makes the data available in req.body.
o Purpose: Parses incoming requests with URL-encoded data, and makes it available in
req.body.
cors()
o Configuration: origin set to frontend host and port, credentials set to true, which
allows cookies to be sent between the frontend and backend.
o Purpose: Catches any errors that are not handled in other parts of the app and sends
a standardized response.
3. Routes Setup
User Routes:
o Router: Imports routes from userRoutes.js, where user-related routes (e.g., login,
logout) are defined.
Admin Routes:
o Router: Imports routes from adminRoutes.js, where admin-related routes (e.g., add
roles, manage hostels) are defined.
o app.use(express.static(path.join(__dirname, "../frontend/dist")));
Purpose: Serves static files from the Vite dist directory, where the frontend
build is located.
Folder Path: frontend/dist directory relative to the server's root.
o Fallback to index.html:
Route: GET *
Purpose: All other routes are redirected to the index.html file located in
frontend/dist, which allows client-side routing (for single-page applications).
Implementation:
res.sendFile(path.join(__dirname, "../frontend/dist/index.html"));
});
Database Connection:
o await dbConnection();
Start Server:
o Port: The server listens on a port defined in the environment variable PORT.
o Host: The server listens on the host defined in the environment variable HOST.
o Message: Logs a message in the console when the server is successfully started.
Purpose: Catches uncaught exceptions, logs the error, and shuts down the
server gracefully by exiting with code 1.
Purpose: Catches unhandled promise rejections, logs the error, and shuts
down the server gracefully by closing the server and exiting with code 1.
o This function initializes the database connection, starts the Express server, and
listens on the specified PORT and HOST provided in environment variables.
o Uncaught Exceptions: If any uncaught exceptions occur, the server will log the error
message and exit.
o Unhandled Promise Rejections: If a promise is rejected without handling, the server
will log the error message and shut down.
Dependencies
express: Web framework for Node.js to handle HTTP requests and routing.
dotenv: Loads environment variables from the .env file into process.env.
cors: Provides Cross-Origin Resource Sharing middleware to allow requests from specified
origins.
path: Provides utilities for working with file and directory paths.
sequelize: An ORM for interacting with relational databases (used for database connection).
This documentation describes how the server and routing logic are set up, the environment variables
required, middleware used, and the error handling mechanisms in place.
The Home component is a React functional component that displays information about a hostel,
including details like the hostel's description, facilities, sections, events, and committee members. It
uses animations for a smooth scrolling effect and lazy loading. Let's break down and document the
major parts of the component:
Imports:
React, useEffect, useRef: React hooks are imported to handle component lifecycle and
references to DOM elements.
Material UI Icons: Various icons (e.g., LocalLibraryIcon, FitnessCenterIcon, etc.) are imported
for representing hostel facilities and contact information.
Material UI Table Components: These are used to display committee member data in a table
format.
React Router Link: Used for navigation to external links, such as phone numbers and email.
iconStyle Constant:
Defines a CSS style for the icons (font size is set to 2.5rem).
hostelData Object:
Contains details about the hostel, including title, image, description, sections (such as
facilities, committee, etc.), and contact information. It is structured as an object, but its
properties appear to be missing in the code (this is likely a mistake that needs to be fixed).
Home Component:
Section References (sectionRefs): Uses useRef to store references to each section for
scrolling animation effects.
useEffect Hook:
Sets up an IntersectionObserver that triggers animations when sections come into view.
The observer is used to add the class loaded to each section when it becomes visible
(indicating that the animation should start).
Component Structure:
1. Header Section:
o Contains animated headers (AnimatedH1) that introduce the hostel ("Your Journey
Starts Here at Dream Land") and a short welcome message.
3. Section Information:
o Displays additional details about the hostel's sections (e.g., facilities, buildings,
events, etc.). These sections include dynamic information pulled from the
hostelData.sections.
4. Facilities Section:
o Uses a grid layout to display hostel facilities, each represented by an icon and a
name. This information is dynamically fetched from hostelData.sections[0].facilities.
5. Events Section:
6. Committee Information:
o Displays a table of committee members, including their names and roles, taken from
hostelData.sections[3].committees.
7. Contact Information:
o Provides contact details for the hostel (phone numbers and email), which are fetched
from hostelData.contact.
Issues to Address:
o Some properties within hostelData (e.g., title, image_url, description, and sections)
are not correctly populated with values or are missing in the code.
o The images (e.g., src= "$ hostelData.image_url ") are currently using incorrect syntax.
The image URL needs to be inserted correctly using the dynamic data.
4. Undefined References:
Conclusion:
This component is designed to render a dynamic, animated homepage for the hostel, showcasing
various aspects like facilities, events, and committee members. It needs some fixes to correctly
render dynamic data from hostelData. Additionally, the animations applied through the
IntersectionObserver and the Animated components provide a smooth user experience as sections
of the page load.
Recommended Fixes:
1. Properly define the hostelData object with values for all its properties.
3. Correct the usage of the map method for dynamic data rendering.
Purpose:
The login async thunk is responsible for handling the login action. It sends a POST request to the
backend with user credentials and handles the response (success or failure).
Key Features:
Error Handling: If the request fails, the error message is captured and returned.
Parameters:
Side Effects:
Purpose:
The logoutuser async thunk is responsible for logging out a user by sending a request to the backend
to end the user's session.
Key Features:
Error Handling: If the request fails, the error message is captured and returned.
Parameters:
Side Effects:
Updates Redux state to reflect that the user has been logged out.
Purpose:
The loaduser async thunk is responsible for loading the user data when the user accesses the
dashboard or logs in.
Key Features:
Parameters:
Side Effects:
Purpose:
The userSlice is a Redux slice that manages the authentication state of the user, including login,
logout, and loading user data.
Key Features:
Initial State: Defines state variables such as user, loading, isAuthenticated, etc.
Reducers:
ExtraReducers: Handles the state changes based on the results of the async thunks:
o Handles login, logoutuser, and loaduser actions, updating the state based on
pending, fulfilled, and rejected states.
Side Effects:
5. Navbar Component
Purpose:
The Navbar component is a responsive navigation bar that allows users to navigate to different
sections of the app (Home, About, Account) and provides login/logout functionality.
Key Features:
Authentication Handling: Displays a "Login" button if the user is not authenticated and a
"Logout" button if the user is authenticated.
Routing: Uses React Router to navigate between pages (/, /about, /account).
Responsive Design: The drawer is toggleable, making it suitable for mobile devices.
State:
Side Effects:
Dispatches the logoutuser thunk on logout, redirecting the user to the home page after a
successful logout.
6. Login Component
Purpose:
The Login component is used to handle user login functionality. It collects the user's email and
password, dispatches the login action, and handles the login process.
Key Features:
Login Action: Dispatches the login async thunk with the entered credentials.
Redirection: Redirects the user to the home page if they are already authenticated.
State:
Side Effects:
These are the components and their descriptions based on the code you provided. Let me know if
you need more detailed documentation or explanations.
Reducers:
App Component:
o The main entry point for the application is wrapped inside React.StrictMode.
o The Redux store is passed to the app via the Provider component.
o The ThemeProvider from MUI applies the custom theme defined in the app.
Router Setup:
/: Home page.
Suspense:
o The app uses Suspense to handle the loading state while components are being lazy-
loaded. A custom Loader component is displayed during this time.
4. Toast Notifications
ToastContainer:
A custom MUI theme is defined with specific color schemes for primary and gray shades,
including multiple variations of gray.
User Authentication:
o The loaduser() action is dispatched to load the user’s data on app initialization.
Error Handling:
o If there are any errors or messages related to the user state, they are shown using
the toast notifications.
The Header and Footer components are rendered outside of the Routes, ensuring they are
visible on every page of the app.
o The header is fixed to the top, with a z-index to ensure it's above other content.
8. Loader Component
The Loader component is shown while the lazy-loaded components are being fetched,
providing a better user experience during loading.
This documentation summarizes the architecture and flow of the code, focusing on Redux store
configuration, routing, theme management, user authentication, and error handling in the app.