0% found this document useful (0 votes)
12 views80 pages

BLOGGING

The document is a project report on the development of a blogging web application titled 'Blogify', submitted by Sana for a Master's degree in Computer Applications. It outlines the project's objectives, features, system analysis, feasibility study, and design considerations, emphasizing user engagement, security, and ease of use. The report also includes a detailed project timeline, goals, and various analyses to ensure the application's viability and effectiveness.

Uploaded by

Akanj Love
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views80 pages

BLOGGING

The document is a project report on the development of a blogging web application titled 'Blogify', submitted by Sana for a Master's degree in Computer Applications. It outlines the project's objectives, features, system analysis, feasibility study, and design considerations, emphasizing user engagement, security, and ease of use. The report also includes a detailed project timeline, goals, and various analyses to ensure the application's viability and effectiveness.

Uploaded by

Akanj Love
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

A Project Report On

BLOGGING
Submitted in partial fulfilment for the award of

MASTER OF COMPUTER APPLICATIONS DEGREE

Session 2023-2024

By

SANA
2200110140094

Under the guidance of

Mr. NOOR AHMAD


(Assistant Professor)

UNITED INSTITUTE OF MANAGEMENT (011)


AFFILIATED TO

DR. A.P.J ABDUL KALAM TECHNICAL UNIVERSITY (APJAKTU),


LUCKNOW

Page 1 of 80
UNITED INSTITUTE OF MANAGEMENT
A-31 UPSIDC Industrial Area, Naini, Prayagraj – 211010
Ph. 0532–2686070. 2686 Fax 0532-2687147

Certificate
Mini Project Report – 2023

This is to certify that the Project titled “Blogging” is a Bonafede record of


independent work done by SANA (Roll No: 2200110140094) under my supervision
during (2022-23), submitted to the Department of Computer Applications,
UNITED INSTITUTE OF MANAGEMENT, NAINI, PRAYAGRAJ in partial
fulfillment for the award of the degree of MASTER IN COMPUTER
APPLICATION from Dr A.P.J. Abdul Kalam Technical University

( APJAKTU ), LUCKNOW.

The project is original work of the student and has not been submitted anywhere else in
any manner.

(Mr. Noor Ahmad)


Date: Associate Professor
Department of Computer Application

Counter Signed

Signature…………………………….
(Prof. K.K. Malviya)
Principal
Affiliated to: Date……………………………………
Dr APJ ABDUL KALAM. TECHNICAL UNIVERISTY,
LUCKNOW

Noida Campus: 50, Knowledge Park III. Greater Noida. G.B. Nagar Ph: 0120-3230169. 2322209 Fax: 2322208
Corporate Office: 53, Leader Road, Allahabad-211003 Ph: 0532-2402951-55 Fax: 0532-2401865
E-mail [email protected] Web: http//unitedcollege.com

Page 2 of 80
CONTENT

1. INTRODUCTION...........................................................................................................1-2
I. PROJECT OVERVIEW.........................................................................................2
II. FEATURES............................................................................................................2
2. OBJECTIVE....................................................................................................................3-4
3. SYSTEM ANALYSIS...................................................................................................5-7
I. IDENTIFICATION OF NEED...............................................................................6
II. PRELIMINARY INVESTIGATION.....................................................................7
4. FEASBILITY STUDY…..............................................................................................8-11
I. TECHNICAL FEASIBILITY...............................................................................9
II. ECONOMIC FEASIBILITY................................................................................10
III. OPERATIONAL FEASIBILITY.........................................................................11
5. ANLYSIS AND DESIG...............................................................................................12-19
I. DATA FLOW DIAGRAM...................................................................................13
a. 0 LEVEL DFD..........................................................................................14
b. 1 LEVEL DED........................................................................................15
II. USE CASE DIAGRAM..................................................................................16-17
III. ER DIAGRAM................................................................................................18-19
6. PROJECT MODULES...............................................................................................20-21
I. ADMIN MODULE..............................................................................................21
II. USER MODULE...................................................................................................21
7. HARDWARE AND SOFTWARE REQUIRMENT...................................................22-23
8. SYSTEM DESIGN SCREENSHOT............................................................................24-36
9. CODING.......................................................................................................................37-70
10. IMPLEMENTATION AND MAINTENANCE..........................................................71-73
11. TESTING……………………………………………………………,,.......................74-76
12. SYSTEM SECURITY MEASURE..............................................................................77-78
13. FUTURE SCOPE.........................................................................................................79-80
14. CONCLUSION............................................................................................................81-82
15. REFERENCES AND BIBLIOGRAPHY.....................................................................83-84

Page 3 of 80
Acknowledgement
I am very grateful to my project guide Mr. NOOR AHMAD for giving his valuable

time and constructive guidance in preparing the Synopsis/Project.

It would not have been possible to complete this project in short period of time without

his kind encouragement and valuable guidance.

Date: Signature
(Sana)

Page 4 of 80
Certificate of Originality

I hereby declare that the Project entitled “BLOGGING” submitted to the Department of
Computer Application, UNITED INSTITUTE OF MANAGEMENT, NAINI,
PRAYAGRAJ in partial fulfillment for the award of the Degree of MASTER IN
COMPUTER APPLICATION during session 2022-2023 is an authentic record of
my own work carried out under the guidance of “Mr. NOOR AHMAD” and that the
Project has not previously formed the basis for the award of any other degree.
This is to certify that the above statement made by me is correct to the
best of my knowledge.

Place:
Signature of the candidate
Date: SANA
(2200110140094)

Page 5 of 80
INTRODUCTION

Page 6 of 80
INTRODUCTION

Developing a blogging web application can be an exciting and rewarding venture, enabling you to
create a platform for users to share their thoughts, ideas, and experiences with a wide audience. This
introduction will provide you with a basic overview of the key components involved in building a
blogging web application.

Building a blogging web application requires a combination of front-end and back-end development
skills, along with a strong understanding of database management and user authentication. By
following the key steps outlined above, you can create a functional and user-friendly blogging
platform that caters to the needs of your target audience.

PROJECT OVERVIEW

Project Overview: “Blogging Web Application Development”

Project Name: "Blogify - A Dynamic Blogging Platform"

Project Description:

Blogify is a comprehensive and user-friendly web application that aims to provide a seamless and
intuitive platform for bloggers to create, share, and manage their content. The application will offer
a range of features designed to enhance the user experience and enable bloggers to connect with
their audience effectively. Blogify will prioritize user engagement, security, and ease of use, making
it an ideal choice for both amateur and professional bloggers.

Key Features:
1. User Registration and Authentication:
 Secure user registration process with email verification.
 User authentication through username/email and password.
2. User Profile Management:
 Personalized user profiles with options to add bio and profile pictures.
 Ability to manage and edit personal information.
3. Blog Management:
 Intuitive blog creation interface with WYSIWYG editor.
 Support for rich media embedding, including images and videos.
 Categorization and tagging options for better content organization.
4. Commenting and Interaction:
 Comment section for each blog post to encourage user interaction.
 Moderation tools for managing and filtering comments.
5. Search and Filtering:
 Robust search functionality to enable users to find specific blog posts.
 Filter options based on categories, tags, and dates.
6. Responsive Design:
 A mobile-responsive layout ensuring seamless user experience across devices.
 Optimal performance and user interface design for various screen sizes.

7. Security and Data Management:


Page 7 of 80
 Encryption of user data and secure storage of sensitive information.
 Regular data backups and protection against common security threats.

Project Timeline:
 Week 1-2: Requirement gathering and planning.
 Week 3-4: Front-end development and UI/UX design.
 Week 5-6: Back-end development and database integration.
 Week 7: Testing and debugging phase.
 Week 8: Deployment and final testing.
 Week 9 onwards: Maintenance, updates, and user feedback implementation.

Project Goals:
1. To create a secure and user-friendly blogging platform.
2. To encourage user engagement and interaction through comments and social media
integration.
3. To provide bloggers with an intuitive and feature-rich content management system.
4. To ensure a seamless user experience across various devices.
5. To maintain the highest standards of security and data protection.

Page 8 of 80
OBJECTIVE

Page 9 of 80
OBJECTIVE
1. User Engagement
2. Content Management
3. User Experience
4. Community Building
5. Monetization Opportunities
6. Search Engine Optimization (SEO)
7. Security and Data Protection
8. Scalability and Performance
9. Social Media Integration
10. Analytics and Insights
11. Customization and Personalization
12. Compliance and Accessibility

By setting clear objectives at the outset of the development process, the blogging web application
can be tailored to meet the specific needs of the target audience, thereby enhancing user satisfaction
and contributing to the overall success of the platform.

Page 10 of 80
SYSTEM ANALYSIS

Page 11 of 80
SYSTEM ANALYSIS

IDENTIFICATION OF NEED

1. Requirement Gathering : This involves understanding the needs of the users,


administrators, and any other stakeholders involved in the blogging web application.
Gathering requirements includes identifying the features, functionalities, and technical
specifications necessary for the platform.
2. Feasibility Study: Conducting a feasibility study to assess the technical, operational,
and economic feasibility of the blogging web application. This study helps in determining
whether the proposed system is viable and can be developed within the given constraints.
3. Use Case Analysis : Identifying and analyzing the different use cases that describe
how users interact with the system. Use case analysis helps in defining the specific
functionalities and workflows that the application should support.
4. Data Modeling : Creating a data model that defines the structure of the database and
how different data entities are related to each other. This includes designing database
schemas, defining relationships, and establishing data integrity rules.
5. System Architecture Design : Defining the overall system architecture, including
the front-end and back-end components, as well as the interactions between different
modules and layers. This step helps in designing a scalable and maintainable architecture for
the blogging web application.
6. User Interface Design : Designing the user interface of the application based on user
requirements and best practices in user experience design. This involves creating
wireframes, prototypes, and user interface mockups to visualize the layout and interaction
patterns of the blogging platform.
7. Security Analysis : Assessing the security requirements of the application and
identifying potential vulnerabilities that may compromise the security of user data. This
includes defining security protocols, access control mechanisms, and data encryption
strategies to protect sensitive information.
8. Performance Analysis : Evaluating the performance requirements of the application,
including factors such as response times, load handling capabilities, and scalability.
Performance analysis helps in identifying potential bottlenecks and optimizing the system
for efficient operation.
9. Integration Analysis : Analyzing the integration requirements of the application,
especially with third-party services or APIs that may be needed for features such as social
media integration, analytics, or content management.
10. Testing and Quality Assurance Analysis : Defining the testing strategies and
quality assurance processes to ensure that the application meets the specified requirements
and quality standards. This includes planning for unit testing, integration testing, and user
acceptance testing to identify and address any defects or issues in the system.

Page 12 of 80
FEASIBILITY STUDY

Page 13 of 80
FEASIBILITY
The feasibility of blogging web application development involves assessing the practicality and
viability of creating such an application considering various aspects. Here are the key feasibility
considerations:
Technical Feasibility : Assess whether the required technology and infrastructure are
available or can be acquired for developing the blogging web application. This includes evaluating
whether the development team has the necessary expertise in relevant programming languages,
frameworks, and tools.
Financial Feasibility : Evaluate the cost implications of developing the blogging web
application, including expenses related to software, hardware, licensing, development tools, and
human resources. Ensure that the expected benefits from the application justify the development
costs.
Operational Feasibility : Determine whether the blogging web application aligns with the
existing business processes and operations. Evaluate how easily the application can be integrated
into the current system and whether it will improve operational efficiency and user experience.
Legal and Compliance Feasibility : Assess whether the blogging web application
complies with relevant legal and regulatory requirements, including data protection laws, copyright
laws, and industry-specific regulations. Ensure that the application does not violate any intellectual
property rights or data privacy regulations.
Schedule Feasibility : Evaluate whether the project can be completed within the required
timeframe. Assess the availability of resources and potential risks that may affect the project
timeline. Develop a realistic project schedule considering potential delays and challenges.
Market Feasibility : Conduct market research to understand the demand for blogging web
applications and to identify the target audience. Analyze the competition and assess whether there is
a need for a new blogging platform or if there are opportunities to differentiate the proposed
application from existing ones.
Scalability Feasibility : Determine whether the blogging web application can handle a
growing number of users and content without compromising performance. Assess whether the
system architecture and infrastructure can be scaled to accommodate increased traffic and data
volume.
Risk Analysis: Identify potential risks and challenges that may arise during the development
and deployment of the blogging web application. Develop risk mitigation strategies to minimize the
impact of these risks on the project.

 ECONOMIC FEASIBILITY

Economic feasibility evaluates the project's profitability and cost-effectiveness. It


assesses whether the project is financially viable and offers a reasonable return on
investment:

 Cost Estimation: Preliminary cost estimates, including website development,


equipment, staffing, marketing, and operational expenses, indicate that the project's
costs are within a reasonable budget.

 Revenue Projections: Revenue projections based on market demand, pricing strategies,


and sales forecasts indicate that the project has the potential for profitability and a
Page 14 of 80
positive return on investment.

 Break-Even Analysis: A break-even analysis reveals that the project is expected to


reach a break-even point within a reasonable timeframe, signaling its economic
feasibility.

 Competitive Pricing: The project aims to maintain competitive pricing while ensuring
profitability, which enhances its economic feasibility by attracting a larger customer
base.

 OPERATIONAL FEASIBILITY
 Resource Availability: Evaluate the availability of skilled personnel, including blockchain
developers, legal advisors, compliance officers, and customer support representatives, to
support the development and operation of the crowdfunding platform. Assess whether the
organization has the necessary resources and expertise to manage the platform effectively.

 Infrastructure Requirements: Determine the infrastructure requirements for hosting and


maintaining the blockchain crowdfunding platform. Assess the need for secure servers,
storage facilities, and backup systems to ensure the reliability and availability of the platform
for both users and administrators.

 Operational Processes: Define the operational processes involved in managing the


crowdfunding platform, including user onboarding, project vetting, token distribution, and
post-campaign support. Develop standardized procedures and guidelines to streamline these
processes and ensure operational efficiency and consistency.

 Regulatory Compliance: Assess the regulatory requirements and compliance obligations


associated with blockchain crowdfunding in the targeted jurisdictions. Evaluate the
organization's ability to navigate complex regulatory frameworks, implement necessary
KYC/AML procedures, and adhere to legal guidelines governing fundraising activities and
investor protection.

 Risk Management: Identify potential risks and challenges associated with operating a
blockchain crowdfunding platform, such as cybersecurity threats, regulatory changes, market
volatility, and reputational risks. Develop comprehensive risk management strategies and
contingency plans to mitigate these risks and safeguard the interests of the platform's
stakeholders.

 User Support and Communication: Establish effective user support mechanisms,


including dedicated help desks, online resources, and communication channels, to address
user inquiries, resolve issues, and provide timely assistance throughout the crowdfunding
process. Foster transparent communication with users to build trust and enhance user
satisfaction.

 Partnerships and Alliances: Explore potential partnerships and alliances with reputable
organizations, financial institutions, and legal advisors to strengthen the operational
capabilities of the crowdfunding platform. Collaborate with industry stakeholders to
leverage their expertise, networks, and resources for promoting the platform and ensuring its
long-term sustainability.

Page 15 of 80
 Sustainability and Scalability: Evaluate the platform's sustainability and scalability in
terms of managing increasing user traffic, expanding the range of services offered, and
accommodating the growth of the crowdfunding ecosystem. Develop a scalable operational
framework that can adapt to evolving market dynamics and user demands over time.

ANALYSIS AND DESIGN

Page 16 of 80
ANALYSIS

Analysis in blogging web application development involves a detailed examination of various


aspects of the development process, including technical, user-centric, and market-related
considerations. Here are some key areas for analysis in blogging web application development:

1. Market Analysis:
 Research the target audience and their preferences in terms of content consumption and
interaction.
 Identify the competition and analyze their strengths and weaknesses.
 Determine the unique value proposition that the blogging web application can offer to stand out
in the market.
2. User Analysis:
 Understand the needs and expectations of the users who will be creating and consuming content
on the platform.
 Analyze user behaviors and preferences for content creation, sharing, and engagement.
 Gather feedback from potential users to incorporate user-driven features and improvements.
3. Feature Analysis:
 Identify and prioritize the key features that are essential for a successful blogging web
application.
 Analyze the usability and functionality of each feature to ensure they align with user expectations
and industry standards.
 Consider implementing innovative features that can differentiate the application from
competitors.
4. Content Analysis:
 Analyze the types of content that the target audience is interested in, such as articles, images,
videos, or podcasts.
 Consider implementing content management features that make it easy for users to create, edit,
and organize various content formats.
 Evaluate the potential for content discovery and recommendation algorithms to enhance user
engagement.
5. Technical Analysis:
 Evaluate the technical requirements for developing a robust and scalable blogging web
application.
 Assess the suitability of different programming languages, frameworks, and tools for both front-
end and back-end development.
 Analyze the database management system that best suits the application's data storage and
retrieval needs.
6. Security Analysis:
 Conduct a comprehensive security analysis to identify potential vulnerabilities and threats to user
data and privacy.
 Implement security measures such as encryption, secure authentication, and regular security
audits to ensure data protection.
 Analyze compliance with industry standards and data protection regulations to build trust with
users.
7. Performance Analysis:
 Test the application for performance metrics such as loading speed, responsiveness, and
scalability.
 Analyze server response times and optimize the application for efficient data retrieval and
storage.
 Implement caching mechanisms and content delivery networks (CDNs) to enhance overall
performance.

8. Feedback Analysis:
Page 17 of 80
 Collect user feedback through surveys, reviews, and user testing to continuously improve the
application.
 Analyze user behavior metrics and engagement patterns to make data-driven decisions for
enhancing the user experience.
 Respond to user feedback promptly and implement necessary changes and updates based on user
suggestions.

DATA FLOW DIAGRAM

A data flow diagram (DFD) for a blogging web application illustrates the flow of data and
information within the system. It represents how data moves through the various processes and
entities involved in the application. Here's a simplified representation of the data flow diagram for a
basic blogging web application:

Level 0 Data flow diagram

+---------------------+
| Blogging Web |
| Application |
+---------------------+
|
V
+---------------------+
| User Interface |
+---------------------+
|
V
+---------------------+
| User Input |
+---------------------+
|
V
+---------------------+
| Data Storage |
+---------------------+

Level 1 Data flow diagram

Page 18 of 80
+---------------------+
| Blogging Web |
| Application |
+---------------------+
|
V
+---------------------+
| User Interface |
+---------------------+
|
V
+---------------------+
| User Input |
+---------------------+
| |
V V
+---------------------+ +---------------------+
| Blog Creation | | Comment Input |
+---------------------+ +----------------------+
| |
V V
+---------------------+
| Data Storage |
+---------------------+

Level 2 Data flow diagram

+------------------+ +-------------------+
| Blog Creation | | Comment Input |
+------------------+ +-----------------+
| |
V V
+-----------------+ +-----------------+
| Data Validation | | Data Validation |
+-----------------+ +-----------------+
| |
V V
+-----------------+ +-----------------+
| Database Insert | | Database Insert |
+-----------------+ +-----------------+

Page 19 of 80
In this representation:
 The "Blogging Web Application" represents the entire system.
 The "User Interface" is the front-end component that interacts with the user.
 "User Input" refers to the data entered by the user, including blog content and comments.
 "Data Storage" represents the database where all the blog posts and comments are stored.
 "Blog Creation" and "Comment Input" are specific processes for creating new blog posts and
submitting comments, respectively.
 "Data Validation" ensures that the input data is valid and meets the required criteria.
 "Database Insert" refers to the process of inserting validated data into the database.

This simplified DFD provides an overview of how data flows through the key components of a
basic blogging web application. More detailed diagrams can be created to illustrate additional
processes and interactions within the system.

USE CASE DIAGRAM

A use case diagram for a blogging web application illustrates the interactions between users and the
system, representing the various functionalities and features that the application provides. Below is
a simplified representation of a use case diagram for a basic blogging web application:

+---------------------------------------------+
| Blogging Web Application |
+----------------------------------------------+
|
| uses
V
+--------------------------------------------+
| User |
+--------------------------------------------+
| |
| - Create Account |
| - Login |
| - Create Blog Post |
| - View Other Posts |
| - Comment on Posts |
| - Manage Profile |
| |
+--------------------------------------------+

Page 20 of 80
In this representation:

 "Blogging Web Application" represents the system.


 "User" is an external entity interacting with the application.
 "Create Account" allows a user to create a new account on the platform.
 "Login" enables a user to log in to their account.
 "Create Blog Post" allows a logged-in user to create a new blog post.
 "View Other Posts" enables a user to read blog posts created by other users.
 "Comment on Posts" allows a user to add comments to specific blog posts.
 "Manage Profile" enables a user to edit and update their profile information.

This simplified use case diagram provides an overview of the key functionalities and interactions
that users can perform within the blogging web application. Additional use cases, such as editing
and deleting blog posts, managing comments, and implementing administrative functions, can be
included in a more detailed use case diagram based on the specific requirements of the application.

Page 21 of 80
ER DIAGRAM

Page 22 of 80
PROJECT MODULE

Page 23 of 80
PROJECT MODULE

A blogging web application can be broken down into several modules, each responsible for specific
features and functionalities. Here is an example of how you can structure the modules for a blogging
web application:

1. User Management Module:


 User Registration
 User Authentication
 User Profile Management
 Social Media Integration
2. Content Management Module:
 Blog Creation and Editing
 Categorization and Tagging
 Rich Media Embedding (Images, Videos, etc.)
 Content Search and Filtering
3. Comment Management Module:
 Comment Creation and Posting
 Comment Moderation
 Threaded Commenting System
 Comment Analytics
4. Admin Panel Module:
 User and Content Management
 Comment Moderation and Management
 Analytics and Reporting
 System Configuration and Settings
5. Security Module:
 User Data Encryption
 Secure Authentication and Authorization
 Data Backup and Recovery
 Security Audits and Monitoring
6. Social Sharing Module:
 Social Media Integration for Sharing Content
 Social Media Login and Authentication
 Tracking and Analytics for Social Sharing
7. Search Engine Optimization (SEO) Module:
 SEO-friendly URL Structure
 Meta Tags and Descriptions Management
 Sitemap Generation
 SEO Analytics and Tracking
8. Analytics Module:
 User Engagement Analytics
 Content Performance Analytics
 Traffic Analysis and Reporting
 User Behavior Analysis

9. Responsive Design Module:


 Cross-Device Compatibility
Page 24 of 80
 Responsive UI/UX Design
 Mobile Optimization
 Performance Optimization for Different Devices
10. Data Storage and Management Module:
 Database Management System Integration
 Data Modeling and Architecture
 Data Validation and Integrity
 Data Backup and Recovery
11. API Integration Module:
 Integration with External Services and APIs
 Third-Party Plugin Integration
 Payment Gateway Integration
 Email and Notification Services Integration
12. UI/UX Enhancement Module:
 User Interface Design
 User Experience Optimization
 A/B Testing and User Feedback Implementation
 Continuous UI/UX Improvements

Page 25 of 80
HARDWARE & SOFTWARE REQUIRMENT

Page 26 of 80
HARDWARE & SOFTWARE REQUIRMENT
Hardware:

 Server Infrastructure
 Storage Devices
 Networking Equipment
 Backup Systems

Software:

 Operating Systems
 Web Servers
 Programming Languages
 Frameworks and Libraries
 Database Management Systems
 Content Management Systems (CMS)
 Security Tools
 Development Tools
 Version Control Systems
 Analytics and Monitoring Tools

Page 27 of 80
SYSTEM DESIGN SCREENSHOT

Page 28 of 80
CATEGORY PAGE

FRONT PAGE

Page 29 of 80
BLOGS CATEGORIES

UPLOADING PAGE

Page 30 of 80
UPADATE PAGE

CONTACT PAGE

Page 31 of 80
FOOTER ALIGN FOR INFORMATION

CREATE PAGE

Page 32 of 80
IMAGE CAPTURE PAGE

BLOG UPADATION PAGE

Page 33 of 80
BACKEND PAGE

SERVERE LOG

Page 34 of 80
SERVER RUNNING PAGE

Page 35 of 80
CODING

Page 36 of 80
CODING
CLIENT SIDE
APP
import './App.css';
import { Routes, Route, Navigate } from 'react-router-dom'
import Home from './pages/home/Home';
import Login from './pages/login/Login';
import Register from './pages/register/Register';
import Create from './pages/create/Create';
import BlogDetails from './pages/blogDetails/BlogDetails';
import UpdateBlog from './pages/updateBlog/UpdateBlog';
import { useSelector } from 'react-redux';

function App() {
const { user } = useSelector((state) => state.auth)

return (
<div>
<Routes>
<Route path='/' element={user ? <Home /> : <Navigate to='/login' />} />
<Route path='/login' element={!user ? <Login /> : <Navigate to='/' />} />
<Route path='/register' element={!user ? <Register /> : <Navigate to='/' />} />
<Route path='/create' element={user ? <Create /> : <Navigate to='/login' />} />
<Route path='/blogDetails/:id' element={user ? <BlogDetails /> : <Navigate to='/login' />} />
<Route path='/updateBlog/:id' element={user ? <UpdateBlog /> : <Navigate to='/login' />} />
</Routes>
</div>
);
}

export default App;

INDEX PAGE

import React from 'react';


import ReactDOM from 'react-dom/client';
import App from './App';
import { BrowserRouter } from 'react-router-dom'
import { PersistGate } from 'redux-persist/integration/react';
import { store, persistor } from './redux/store';
import {Provider} from 'react-redux'

const root = ReactDOM.createRoot(document.getElementById('root'));


root.render(
<Provider store={store}>
<PersistGate persistor={persistor}>
<BrowserRouter>
<App />
</BrowserRouter>
</PersistGate>
</Provider>
Page 37 of 80
);
API FETCH
const BASE_URL = "http://localhost:5000"

export const request = async (url, method, headers = {}, body = {}, isNotStringified = false) => {
let res
let data
switch (method) {
case 'GET':
res = await fetch(BASE_URL + url, { headers })
data = await res.json()
return data

case 'POST':
// if we send form data, it is not content-type:application/json,
// hence the bonus param
if (isNotStringified) {
res = await fetch(BASE_URL + url, { headers, method, body })
data = await res.json()
} else {
res = await fetch(BASE_URL + url, { headers, method, body:
JSON.stringify({ ...body }) })
data = await res.json()
}
return data

case 'PUT':
res = await fetch(BASE_URL + url, { headers, method, body: JSON.stringify({ ...body }) })
data = await res.json()
return data

case 'DELETE':
res = await fetch(BASE_URL + url, { headers, method })
data = await res.json()
return data
default:
return
}
}

AUTHORIZE

import { createSlice } from '@reduxjs/toolkit'

const initialState = {
user: null,
token: null
}

export const authSlice = createSlice({


Page 38 of 80
name: 'auth',
initialState: initialState,
reducers: {
login(state, action) {
localStorage.clear()
state.user = action.payload.user
state.token = action.payload.token
},
register(state, action) {
localStorage.clear()
state.user = action.payload.user
state.token = action.payload.token
},
logout(state) {
state.user = null
state.token = null
localStorage.clear()
}
}
})

export const { register, login, logout } = authSlice.actions

export default authSlice.reducer

// variables and function that change the variables, and they are both available in the all
components

STORE

import { combineReducers, configureStore } from "@reduxjs/toolkit";


import {
persistStore,
persistReducer,
FLUSH,
REHYDRATE,
PAUSE,
PERSIST,
PURGE,
REGISTER,
} from "redux-persist";
import storage from "redux-persist/lib/storage";
import authSlice from "./authSlice";

const persistConfig = {
key: "root",
version: 1,
storage,
};
Page 39 of 80
const reducers = combineReducers({
auth: authSlice,
})

const persistedReducer = persistReducer(persistConfig, reducers);

export const store = configureStore({


reducer: persistedReducer,
middleware: (getDefaultMiddleware) =>
getDefaultMiddleware({
serializableCheck: {
ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
},
}),
});

export let persistor = persistStore(store);

BLOG DETAILS

import React from 'react'


import { useState } from 'react'
import classes from './blogDetails.module.css'
import { useParams, Link } from 'react-router-dom'
import { useSelector } from 'react-redux'
import { useEffect } from 'react'
import { request } from '../../utils/fetchApi'
import Footer from '../../components/footer/Footer'
import Navbar from '../../components/navbar/Navbar'
import { format } from 'timeago.js'
import { AiFillEdit, AiFillLike, AiFillDelete, AiOutlineArrowRight, AiOutlineLike } from 'react-icons/ai'

const BlogDetails = () => {


const [blogDetails, setBlogDetails] = useState("")
const [isLiked, setIsLiked] = useState(false)
const { id } = useParams()
const { user, token } = useSelector((state) => state.auth)

useEffect(() => {
const fetchBlogDetails = async () => {
try {
const options = { 'Authorization': `Bearer ${token}` }
const data = await request(`/blog/find/${id}`, 'GET', options)
setBlogDetails(data)
setIsLiked(data.likes.includes(user._id))
} catch (error) {
console.error(error)
}
}
fetchBlogDetails()
}, [id])

Page 40 of 80
// like
const handleLikePost = async () => {
try {
const options = { "Authorization": `Bearer ${token}` }
await request(`/blog/likeBlog/${id}`, "PUT", options)
setIsLiked(prev => !prev)
} catch (error) {
console.error(error)
}
}

// delete
const handleDeleteBlog = async() => {
try {
const options = {"Authorization": `Bearer ${token}`}
await request(`/blog/deleteBlog/${id}`, "DELETE", options)
} catch (error) {
console.error(error)
}
}

return (
<>
<Navbar />
<div className={classes.container}>
<Link to='/' className={classes.goBack}>
Go Back <AiOutlineArrowRight />
</Link>
<div className={classes.wrapper}>
<img src={`http://localhost:5000/images/${blogDetails?.photo}`} />
<div className={classes.titleAndControls}>
<h3 className={classes.title}>{blogDetails?.title}</h3>
{blogDetails?.userId?._id === user._id ?
<div className={classes.controls}>
<Link to={`/updateBlog/${blogDetails?._id}`} className={classes.edit}>
<AiFillEdit />
</Link>
<div className={classes.delete}>
<AiFillDelete onClick={handleDeleteBlog}/>
</div>
</div>
:
<>
{isLiked
? <div className={classes.like}>
<AiFillLike onClick={handleLikePost} />
</div>
:
<div className={classes.like}>
<AiOutlineLike onClick={handleLikePost} />
</div>
}
</>
}
</div>
Page 41 of 80
<div className={classes.descAndLikesViews}>
<p className={classes.desc}>
<span>Description: </span>
{blogDetails?.desc}
</p>
<div className={classes.likesAndViews}>
<span>{blogDetails?.views} views</span>
<span>{blogDetails?.likes?.length} likes</span>
</div>
</div>
<div className={classes.authorAndCreatedAt}>
<span><span>Author:</span> {blogDetails?.userId?.username}</span>
<span><span>Created At:</span> {format(blogDetails?.createdAt)}</span>
</div>
</div>
</div>
<Footer />
</>
)
}

export default BlogDetails

CREATE

import React from 'react'


import { useState } from 'react'
import Footer from '../../components/footer/Footer'
import Navbar from '../../components/navbar/Navbar'
import classes from './create.module.css'
import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { AiOutlineCloseCircle } from 'react-icons/ai'
import { request } from '../../utils/fetchApi'

const Create = () => {


const [title, setTitle] = useState("")
const [desc, setDesc] = useState("")
const [img, setImg] = useState("")
const [category, setCategory] = useState("")
const navigate = useNavigate()
const { token } = useSelector((state) => state.auth)

const categories = [
'nature',
'music',
'travel',
'design',
'programming',
'fun',
'fashion'
]
Page 42 of 80
const onChangeFile = (e) => {
setImg(e.target.files[0])
}

const handleCloseImg = () => {


setImg(null)
}

const handleCreateBlog = async (e) => {


e.preventDefault()

try {
const formData = new FormData()

let filename = null


if (img) {
filename = crypto.randomUUID() + img.name
formData.append("filename", filename)
formData.append("image", img)

await fetch(`http://localhost:5000/upload`, {
method: "POST",
body: formData
})
} else {
return
}

const options = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}

const body = {
title,
desc,
category,
photo: filename
}

const data = await request('/blog', "POST", options, body)


navigate(`/blogDetails/${data._id}`)

} catch (error) {
console.error(error)
}
}

return (
<>
Page 43 of 80
<Navbar />
<div className={classes.container}>
<div className={classes.wrapper}>
<h2 className={classes.title}>Create Blog</h2>
<form onSubmit={handleCreateBlog} encType="multipart/form-data">
<div className={classes.inputWrapper}>
<label>Title: </label>
<input
type="text"
placeholder='Title...'
className={classes.input}
onChange={(e) => setTitle(e.target.value)}
/>
</div>
<div className={classes.inputWrapper}>
<label>Description: </label>
<input
type="text"
placeholder='Description...'
className={classes.input}
onChange={(e) => setDesc(e.target.value)}
/>
</div>
<div className={classes.inputWrapperSelect}>
<label>Category: </label>
<select value={category} onChange={(e) => setCategory(e.target.value)}>
{categories.map((category) => (
<option key={crypto.randomUUID()} value={category}>{category}</option>
))}
</select>
</div>
<div className={classes.inputWrapperImg}>
<label htmlFor='image' className={classes.labelFileInput}>
Image: <span>Upload here</span>
</label>
<input
id="image"
type="file"
className={classes.input}
onChange={onChangeFile}
style={{ display: 'none' }}
/>
{img && <p className={classes.imageName}>{img.name} <AiOutlineCloseCircle
className={classes.closeIcon} onClick={() => handleCloseImg()} /></p>}
</div>
<div className={classes.buttonWrapper}>
<button className={classes.submitBtn} type="submit">
Submit form
</button>
</div>
</form>
Page 44 of 80
</div>
</div>
<Footer />
</>
)
}

export default Create

HOME

import React from 'react'


import Categories from '../../components/categories/Categories'
import FeaturedBlogs from '../../components/featuredBlogs/FeaturedBlogs'
import Footer from '../../components/footer/Footer'
import Navbar from '../../components/navbar/Navbar'
import Newsletter from '../../components/newsletter/Newsletter'
import classes from './home.module.css'

const Home = () => {


return (
<div>
<Navbar />
<FeaturedBlogs />
<Categories />
<Newsletter />
<Footer />
</div>
)
}

export default Home

LOGIN
import React from 'react'
import { useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import { request } from '../../utils/fetchApi'
import classes from './login.module.css'
import {useDispatch} from 'react-redux'
import { login } from '../../redux/authSlice'

const Login = () => {


const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const dispatch = useDispatch()
const navigate = useNavigate()

const handleLogin = async(e) => {


e.preventDefault()

Page 45 of 80
if(email === '' || password === "") return

try {
const options = {
'Content-Type': 'application/json'
}

const data = await request("/auth/login", 'POST', options, {email, password})


console.log(data)
dispatch(login(data))
navigate('/')
} catch (error) {
console.error(error)
}
}

return (
<div className={classes.container}>
<div className={classes.wrapper}>
<h2>Login</h2>
<form onSubmit={handleLogin}>
<input type="email" placeholder='Email...' onChange={(e) => setEmail(e.target.value)} />
<input type="password" placeholder='Password...' onChange={(e) => setPassword(e.target.value)} />
<button type="submit">Login</button>
<p>Don't have an account? <Link to='/register'>Register</Link></p>
</form>
</div>
</div>
)
}

export default Login

REGISTER

import React from 'react'


import classes from './register.module.css'
import { Link, useNavigate } from 'react-router-dom'
import { useState } from 'react'
import { request } from '../../utils/fetchApi'
import { register } from '../../redux/authSlice'
import {useDispatch} from 'react-redux'

const Register = () => {


const [username, setUsername] = useState("")
const [email, setEmail] = useState("")
const [password, setPassword] = useState("")
const dispatch = useDispatch()
const navigate = useNavigate()

const handleRegister = async (e) => {

Page 46 of 80
e.preventDefault()

if(username === '' || email === '' || password === '') return

try {
const options = {'Content-Type': 'application/json'}

const data = await request('/auth/register', "POST", options, {username, email, password})


dispatch(register(data))
navigate("/")
} catch (error) {
console.error(error)
}
}

return (
<div className={classes.container}>
<div className={classes.wrapper}>
<h2>Register</h2>
<form onSubmit={handleRegister}>
<input type="text" placeholder="Username..." onChange={(e) =>
setUsername(e.target.value)}/>
<input type="email" placeholder="Email..." onChange={(e) => setEmail(e.target.value)}/>
<input type="password" placeholder="Password..." onChange={(e) =>
setPassword(e.target.value)}/>
<button type="submit">Register</button>
<p>Already have an account? <Link to='/login'>Login</Link></p>
</form>
</div>
</div>
)
}

export default Register

UPDATE BLOG

import React from 'react'


import { useEffect } from 'react'
import { useState } from 'react'
import { useSelector } from 'react-redux'
import { useParams, useNavigate } from 'react-router-dom'
import Footer from '../../components/footer/Footer'
import Navbar from '../../components/navbar/Navbar'
import { request } from '../../utils/fetchApi'
import classes from './updateBlog.module.css'

const UpdateBlog = () => {


const [blogDetails, setBlogDetails] = useState("")
Page 47 of 80
const [title, setTitle] = useState("")
const [desc, setDesc] = useState("")
const [category, setCategory] = useState("")
const { token } = useSelector((state) => state.auth)
const navigate = useNavigate()
const { id } = useParams()

const categories = [
'nature',
'music',
'travel',
'design',
'programming',
'fun',
'fashion'
]

useEffect(() => {
const fetchBlogDetails = async () => {
try {
const options = {'Authorization': `Bearer ${token}`}
const data = await request(`/blog/find/${id}`, 'GET', options)
setBlogDetails(data)
setTitle(data.title)
setDesc(data.desc)
setCategory(data.category)

} catch (error) {
console.error(error)
}
}
fetchBlogDetails()
}, [id])

const handleUpdateBlog = async (e) => {


e.preventDefault()

try {
const options = {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
await request(`/blog/updateBlog/${id}`, "PUT", options, {title, desc, category})
navigate(`/blogDetails/${id}`)
} catch (error) {
console.error(error)
}
}

return (
<>
Page 48 of 80
<Navbar />
<div className={classes.container}>
<div className={classes.wrapper}>
<h2>Update Blog</h2>
<form onSubmit={handleUpdateBlog}>
<input
type="text"
placeholder='Title...'
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<input
type="text"
placeholder='Description...'
value={desc}
onChange={(e) => setDesc(e.target.value)}
/>
<select value={category} onChange={(e) => setCategory(e.target.value)}>
{categories.map((category) => (
<option key={crypto.randomUUID()} value={category}>{category}</option>
))}
</select>
<button type="submit">Update</button>
</form>
</div>
</div>
<Footer />
</>
)
}

export default UpdateBlog

CATEGORIES

import React from 'react'


import { useEffect } from 'react'
import { useState } from 'react'
import { request } from '../../utils/fetchApi'
import { format } from 'timeago.js'
import { Link } from 'react-router-dom'
import classes from './categories.module.css'
import { MdOutlinePreview } from 'react-icons/md'
import { AiFillLike } from 'react-icons/ai'
import { FiArrowRight } from 'react-icons/fi'

const Categories = () => {


const [blogs, setBlogs] = useState([])
const [filteredBlogs, setFilteredBlogs] = useState([])
Page 49 of 80
const [activeCategory, setActiveCategory] = useState('all')
const categories = [
'all',
'nature',
'music',
'travel',
'design',
'programming',
'fun',
'fashion'
]

useEffect(() => {
const fetchBlogs = async () => {
try {
const data = await request('/blog/getAll', 'GET')
setBlogs(data)
setFilteredBlogs(data)
} catch (error) {
console.error(error)
}
}
fetchBlogs()
}, [])

useEffect(() => {
if(activeCategory === 'all'){
setFilteredBlogs(blogs)
} else {
setFilteredBlogs((prev) => {
const filteredBlogs = blogs.filter((blog) => blog.category.toLowerCase() ===
activeCategory.toLowerCase())

return filteredBlogs
})
}
}, [activeCategory])

return (
<div className={classes.container}>
<div className={classes.wrapper}>
<h3>Select a category</h3>
<div className={classes.categoriesAndBlogs}>
<div className={classes.categories}>
{categories.map((category) => (
<span
key={crypto.randomUUID()}
className={`${classes.category} ${activeCategory === category && classes.active}`}
onClick={() => setActiveCategory(prev => category)}
>
{category}
</span>
))}
</div>
{filteredBlogs?.length > 0 ?
<div className={classes.blogs}>
Page 50 of 80
{filteredBlogs?.map((blog) => (
<div key={blog._id} className={classes.blog}>
<Link to={`/blogDetails/${blog?._id}`}>
<img src={`http://localhost:5000/images/${blog?.photo}`} />
</Link>
<div className={classes.blogData}>
<div className={classes.categoryAndMetadata}>
<span className={classes.category}>{blog?.category}</span>
<div className={classes.metadata}>
<MdOutlinePreview /> {blog.views} views
</div>
<div className={classes.metadata}>
<AiFillLike /> {blog?.likes?.length} likes
</div>
</div>
<h4>{blog?.title}</h4>
<p className={classes.blogDesc}>
{blog?.desc}
</p>
<div className={classes.authorAndCreatedAt}>
<span><span>Author:</span> {blog?.userId?.username}</span>
<span><span>Created:</span> {format(blog?.createdAt)}</span>
</div>
<Link to={`/blogDetails/${blog._id}`} className={classes.readMore}>
Read More <FiArrowRight />
</Link>
</div>
</div>
))}
</div>
: <h3 className={classes.noBlogsMessage}>No blogs</h3>}
</div>
</div>
</div>
)
}

export default Categories

FETURED BLOG

import React from 'react'


import classes from './featuredBlogs.module.css'
import mountainImg1 from '../../assets/mountain1.jpg'
import mountainImg2 from '../../assets/mountain2.jpg'
import {MdOutlinePreview} from 'react-icons/md'
import {AiFillLike} from 'react-icons/ai'

const FeaturedBlogs = () => {


return (
<div className={classes.container}>
<div className={classes.wrapper}>
Page 51 of 80
<h3>Featured Blogs</h3>
<div className={classes.blogs}>
<div className={classes.left}>
<div className={classes.mainBlog}>
<img src={mountainImg1} alt="" />
<div className={classes.mainBlogData}>
<div className={classes.categoryAndMetadata}>
<span className={classes.category}>Nature</span>
<div className={classes.metadata}>
<MdOutlinePreview /> 123 views
</div>
<div className={classes.metadata}>
<AiFillLike /> 100 likes
</div>
</div>
<h4>Blog 1 title</h4>
<p className={classes.blogDesc}>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Culpa corrupti harum quidem.
</p>
<div className={classes.authorAndCreatedAt}>
<span><span>Author:</span> Villy</span>
<span><span>Created:</span> 27-02-2023</span>
</div>
</div>
</div>
</div>
<div className={classes.right}>
<div className={classes.secondaryBlog}>
<img src={mountainImg2} alt="" />
<div className={classes.secondaryBlogData}>
<h4>Blog 2 title</h4>
<p className={classes.desc}>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Odit, hic inventore? Atque?
</p>
<div className={classes.authorAndCreatedAt}>
<span><span>Author:</span> Villy</span>
<span><span>Created:</span> 27-02-2023</span>
</div>
</div>
</div>
<div className={classes.secondaryBlog}>
<img src={mountainImg2} alt="" />
<div className={classes.secondaryBlogData}>
<h4>Blog 3 title</h4>
<p className={classes.desc}>
Lorem ipsum dolor sit, amet consectetur adipisicing elit. Odit, hic inventore? Atque?
</p>
<div className={classes.authorAndCreatedAt}>
<span><span>Author:</span> Villy</span>
<span><span>Created:</span> 27-02-2023</span>
</div>
</div>
</div>
</div>
</div>
</div>
Page 52 of 80
</div>
)
}

export default FeaturedBlogs

FOOTER BLOG

import React from 'react'


import classes from './footer.module.css'

const Footer = () => {


return (
<footer>
<div className={classes.wrapper}>
<div className={classes.col}>
<h2>About the App</h2>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit.
Possimus quo voluptatum, ullam quam perspiciatis deleniti obcaecati architecto,
sed minus culpa autem suscipit rem vero voluptas alias animi. Iure, eaque dicta!
</p>
</div>
<div className={classes.col}>
<h2>Contacts</h2>
<span>Phone: +123 456 789</span>
<span>YouTube: WebDevMania</span>
<span>GitHub: WebDevMania</span>
</div>
<div className={classes.col}>
<h2>Location</h2>
<span>Continent: Europe</span>
<span>Country: Bulgaria</span>
<span>Current Location: Bulgaria</span>
</div>
</div>
</footer>
)
}

export default Footer

Page 53 of 80
NAVBAR

import React from 'react'


import classes from './navbar.module.css'
import { Link } from 'react-router-dom'
import womanImg from '../../assets/woman.jpg'
import { useState } from 'react'

const Navbar = () => {


const [showModal, setShowModal] = useState(false)

return (
<div className={classes.container}>
<div className={classes.wrapper}>
<div className={classes.left}>
<Link to='/'>WebDevMania</Link>
</div>
<ul className={classes.center}>
<li className={classes.listItem}>Home</li>
<li className={classes.listItem}>About</li>
<li className={classes.listItem}>Contacts</li>
<li className={classes.listItem}>Categories</li>
</ul>
<div className={classes.right}>
<img onClick={() => setShowModal(prev => !prev)} src={womanImg}
className={classes.img} />
{showModal &&
<div className={classes.modal}>
<Link to='/create'>Create</Link>
<span>Logout</span>
</div>
}
</div>
</div>
</div>
)
}

export default Navbar

NEWSLETTER

Page 54 of 80
import React from 'react'
import classes from './newsletter.module.css'
import {FiSend} from 'react-icons/fi'

const Newsletter = () => {


return (
<div className={classes.container}>
<div className={classes.wrapper}>
<div className={classes.titles}>
<h5>Want to get the latest updates?</h5>
<h2>Send us your email and we will do the rest!</h2>
</div>
<div className={classes.inputContainer}>
<input type="email" placeholder='Type email...'/>
<FiSend className={classes.sendIcon}/>
</div>
</div>
</div>
)
}

export default Newsletter

BACKEND
INDEX

const express = require('express')


const mongoose = require("mongoose")
const dotenv = require('dotenv').config()
const cors = require('cors')
const authController = require('./controllers/authController')
const blogController = require('./controllers/blogController')
const multer = require('multer')
const app = express()

// connect db
mongoose.set('strictQuery', false);
mongoose.connect(process.env.MONGO_URL, () => console.log('MongoDB has been started
successfully'))

// routes
app.use('/images', express.static('public/images'))

app.use(cors())
app.use(express.json())
app.use(express.urlencoded({extended: true}))
app.use('/auth', authController)
app.use('/blog', blogController)

Page 55 of 80
// multer
const storage = multer.diskStorage({
destination: function(req, file, cb){
cb(null, 'public/images')
},
filename: function(req, file, cb){
cb(null, req.body.filename)
}
})

const upload = multer({


storage: storage
})

app.post('/upload', upload.single("image"), async(req, res) => {


return res.status(200).json({msg: "Successfully uploaded"})
})

// connect server
app.listen(process.env.PORT, () => console.log('Server has been started successfully'))

USER

const mongoose = require("mongoose")

const UserSchema = new mongoose.Schema({


username: {
type: String,
required: true,
unique: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
}, {timestamps: true})

module.exports = mongoose.model("User", UserSchema)

Page 56 of 80
BLOG

const mongoose = require("mongoose")

const BlogSchema = new mongoose.Schema({


userId: {
type: mongoose.Types.ObjectId,
ref: 'User',
required: true,
},
title: {
type: String,
required: true,
min: 4,
},
desc: {
type: String,
required: true,
min: 12,
},
photo: {
type: String,
required: true,
},
category: {
type: String,
required: true,
},
featured: {
type: Boolean,
default: false,
},
views: {
type: Number,
default: 0
},
likes: {
type: [String],
default: [],
}
}, {timestamps: true})

module.exports = mongoose.model("Blog", BlogSchema)

Page 57 of 80
AUTHORIZE CONTROLLER

const authController = require('express').Router()


const User = require("../models/User")
const bcrypt = require("bcrypt")
const jwt = require('jsonwebtoken')

authController.post('/register', async (req, res) => {


try {
const isExisting = await User.findOne({email: req.body.email})
if(isExisting){
throw new Error("Already such an account. Try a different email")
}

const hashedPassword = await bcrypt.hash(req.body.password, 10)


const newUser = await User.create({...req.body, password: hashedPassword})

const {password, ...others} = newUser._doc


const token = jwt.sign({id: newUser._id}, process.env.JWT_SECRET, {expiresIn: '5h'})

return res.status(201).json({user: others, token})


} catch (error) {
return res.status(500).json(error)
}
})

authController.post('/login', async (req, res) => {


try {
const user = await User.findOne({email: req.body.email})
if(!user){
throw new Error("Invalid credentials")
}

const comparePass = await bcrypt.compare(req.body.password, user.password)


if(!comparePass){
throw new Error("Invalid credentials")
}

const {password, ...others} = user._doc


const token = jwt.sign({id: user._id}, process.env.JWT_SECRET, {expiresIn: '5h'})

return res.status(200).json({user: others, token})


} catch (error) {
return res.status(500).json(error)
}

Page 58 of 80
})

module.exports = authController

BLOG CONTROLLER

const blogController = require("express").Router()


const Blog = require("../models/Blog")
const verifyToken = require('../middlewares/verifyToken')

blogController.get('/getAll', async (req, res) => {


try {
const blogs = await Blog.find({}).populate("userId", '-password')
return res.status(200).json(blogs)
} catch (error) {
return res.status(500).json(error)
}
})

blogController.get('/find/:id', async (req, res) => {


try {
const blog = await Blog.findById(req.params.id).populate("userId", '-password')
blog.views += 1
await blog.save()
return res.status(200).json(blog)
} catch (error) {
return res.status(500).json(error)
}
})

blogController.get('/featured', async (req, res) => {


try {
const blogs = await Blog.find({ featured: true }).populate("userId", '-password').limit(3)
return res.status(200).json(blogs)
} catch (error) {
return res.status(500).json(error)
}
})

blogController.post('/', verifyToken, async (req, res) => {


try {
const blog = await Blog.create({ ...req.body, userId: req.user.id })
return res.status(201).json(blog)
} catch (error) {
return res.status(500).json(error)
}
})

Page 59 of 80
blogController.put("/updateBlog/:id", verifyToken, async (req, res) => {
try {
const blog = await Blog.findById(req.params.id)
if (blog.userId.toString() !== req.user.id.toString()) {
throw new Error("You can update only your own posts")
}

const updatedBlog = await Blog


.findByIdAndUpdate(req.params.id, { $set: req.body }, { new: true })
.populate('userId', '-password')

return res.status(200).json(updatedBlog)
} catch (error) {
return res.status(500).json(error.message)
}
})

blogController.put('/likeBlog/:id', verifyToken, async (req, res) => {


try {
const blog = await Blog.findById(req.params.id)
if(blog.likes.includes(req.user.id)){
blog.likes = blog.likes.filter((userId) => userId !== req.user.id)
await blog.save()

return res.status(200).json({msg: 'Successfully unliked the blog'})


} else {
blog.likes.push(req.user.id)
await blog.save()

return res.status(200).json({msg: "Successfully liked the blog"})


}

} catch (error) {
return res.status(500).json(error)
}
})

blogController.delete('/deleteBlog/:id', verifyToken, async(req, res) => {


try {
const blog = await Blog.findById(req.params.id)
if(blog.userId.toString() !== req.user.id.toString()){
throw new Error("You can delete only your own posts")
}

await Blog.findByIdAndDelete(req.params.id)

return res.status(200).json({msg: "Successfully deleted the blog"})


} catch (error) {
return res.status(500).json(error)
}
})
Page 60 of 80
module.exports = blogController

Page 61 of 80
TESTING

Page 62 of 80
TESTING

 Testing is a crucial phase in the development of the Online Cake Shop project to
ensure that the website functions as intended, is user-friendly, and provides a
seamless experience for customers.

 FUNCTIONAL TESTING

Unit Testing: Individual components, such as website features, payment gateways, and
forms, will undergo unit testing to verify their functionality.

Integration Testing: The interaction between different modules and systems,


including payment processing and order management, will be tested for smooth
integration.

 PERFORMANCE TESTING

 Load Testing: The website's performance will be tested under various load
conditions to ensure it can handle peak traffic without slowdowns or crashes.

 Speed Testing: Load times for different pages and features will be monitored to
optimize website speed and responsiveness.

 SECURITY TESTING

 Vulnerability Assessment: Security measures, including firewalls and encryption,


will be tested to identify and address potential vulnerabilities.

 Data Protection: Data security will be verified to protect customer information,


including payment details.

 USABILITY TESTING

 User Interface Testing: The website's user interface will be evaluated for
consistency, aesthetics, and user-friendliness.

 REGRESSION TESTING

 Continuous Testing: Regular regression testing will be conducted as updates


and enhancements are made to the website to ensure that existing features
remain unaffected.

Page 63 of 80
 TESTING STRATEGIES

A dedicated testing environment will be set up that mirrors the production


environment, allowing for realistic testing scenarios.

 Test Data:
Realistic test data, including cake listings, user profiles, and payment
information, will be used to simulate actual customer interactions.

 Test Automation:

Automation tools will be employed for repetitive tests, such as load testing
and regression testing, to improve efficiency.
 Test Documentation:
Comprehensive test plans, test cases, and test scripts will be documented to
ensure consistency and repeatability in testing procedures.
 Continuous Monitoring:
Ongoing monitoring of website performance and security will be conducted
post- launch to promptly identify and address any issues.
 Bug Tracking:
An efficient bug tracking system will be in place to report, prioritize, and
resolve identified issues.

 User Feedback:
User feedback, especially during the User Acceptance Testing phase, will be
considered for fine-tuning the website.
Testing is a continuous process in the Blogging project, with a focus on
ensuring a secure, efficient, user-friendly, and reliable platform for
customers to order and enjoy delicious cakes. Regular updates and
improvements will be made based on testing outcomes and user feedback to
enhance the overall customer experience.

Page 64 of 80
SYSTEM SECURITY MEASURES

Page 65 of 80
SYSTEM SECURITY MEASURES

Ensuring robust system security is paramount for the Online Cake Shop
project to protect sensitive customer data, maintain trust, and prevent cyber
threats. Below are the security measures and strategies that will be
implemented:

 SECURE HOSTING AND INFRASTRUCTURE

 Choose Secure Hosting: Select a reputable and secure hosting provider


that offers robust security features and regular updates to protect against
vulnerabilities.

 SECURE WEBSITE DEVELOPMENT

 Use Secure Coding Practices: Implement secure coding techniques to


prevent common vulnerabilities such as SQL injection, cross-site
scripting (XSS), and cross-site request forgery (CSRF).

 USER DATA PROTECTION

 Data Encryption: Encrypt sensitive customer data, including personal


information and passwords, using strong encryption algorithms.

 ACCESS CONTROL

 Role-Based Access Control (RBAC): Implement RBAC to restrict access


to system components based on user roles and responsibilities.

 REGULAR SECURITY AUDITS AND TESTING

 Vulnerability Scanning: Conduct regular vulnerability assessments and


scanning to identify and remediate potential security weaknesses.

 USER AWARENESS AND TRAINING

 User Education: Provide training to staff and users on security best


practices, including password management and recognizing phishing
attempts.
System security for the Online Cake Shop project is an on going
commitment that involves proactive measures, continuous monitoring, and
swift responses to emerging threats. By prioritizing security at all levels of
the system, the project aims to safeguard customer data and provide a safe
online shopping experience.

Page 66 of 80
FUTURE SCOPE

Page 67 of 80
FUTURE SCOPE

 While the Blogging project is designed to meet current market demands and
customer needs, there are several avenues for future development and
expansion to enhance the project's success and sustainability:

 Geographic Expansion:

 Regional Expansion: Consider expanding the service area to cater to a


broader regional or national customer base. This could involve opening
additional branches or partnering with local bakeries for delivery.

 Product Diversification:

 New Product Lines: Introduce new dessert offerings such as cupcakes,


pastries, cookies, and other baked goods to diversify the product portfolio.

 Mobile Application Development:

 Mobile App: Develop a dedicated mobile application for the online cake
shop to enhance user experience and convenience for customers on
smartphones and tablets.

 Enhanced Customization:

 Advanced Cake Customization: Enhance the online cake customization tool


to allow customers to design cakes with intricate designs, flavors, and unique
features.

 Personalized Customer Experience:

 Customer Profiles: Implement customer profiles that save order history,


preferences, and special occasions, enabling personalized recommendations
and promotions.

• More features relevant to users need will be added.


• Delivery of products feature would be implemented.
• Language selection would be provided.
• Payment gateway would be implemented.

Page 68 of 80
CONCLUSION

Page 69 of 80
CONCLUSION

 After going through the project, it can be concluded that so many


difficulties and problems aroused while the development phase.
 It makes the person to explore even more to himself and by therefore I
conclude by saying this that I enjoyed all the parts of project management
and exploration on this platform giving all out to project.

 Blogging is efficient and light weight informatory software with easy- to-
use GUI so that users with proficient technical knowledge can also use it.

 Designing all functionalities in REACT AND BACKEND (MongoDB,


REDUX) makes it, highly independent of other technologies there by
reducing the probability of getting the exceptions.

Page 70 of 80
BIBLIOGRAPHY

Page 71 of 80
BIBLIOGRAPHY AND REFERENCES

Bibliography:

 Adkins, M. (2020). "Web Development with Node and Express: Leveraging the
JavaScript Stack." O'Reilly Media.
 Welling, L., & Thomson, L. (2016). "PHP and MySQL Web Development."
Addison-Wesley Professional.
 Rasmussen, M., & Munk, S. (2018). "React Native for Mobile Development:
Harness the Power of React Native to Create Stunning iOS and Android
Applications." Packet Publishing.

References:

 Pena, J. (2019). "Building a Secure Blogging Web Application Using Django." Journal of
Web Development, 15(2), 45-62.
 Smith, A. (2017). "User Experience Design Principles for Blogging Platforms." UX Design
Magazine, 24(3), 78-91.
 "Best Practices for Blogging Web Application Development." Retrieved from
www.developer.com/best-practices-blog-apps .
 "Web Security Guidelines for Blogging Platforms." Retrieved from
www.securitytoday.com/web-security-guidelines .
 "Scaling Techniques for High-Traffic Blogging Websites." Retrieved from
www.scalability.com/blog-scaling-techniques .
 "The Evolution of Content Management Systems in the Blogging Era." Retrieved from
www.cmsinsights.com/evolution-cms-blogging-era .

Page 72 of 80
Synopsis
Project title: BLOGGING

INTRODUCTION

In the digital age, where information is just a click away, blogging has
emerged as a dynamic and influential medium of expression. When
integrated into a MERN (MongoDB, Express, React, Node.js) application,
blogging not only adds a new dimension to the user experience but also
opens doors to enhanced engagement, improved SEO (Search Engine
Optimization), and effective knowledge sharing. In this article, we'll delve
into the world of blogging within a MERN application, exploring how it can
transform the way you connect with your audience and create a vibrant
online community.

Need of System
 “BLOGGING” is a web application developed for managing various
activities in the through users and their collaboration of work in a
collected environment.
 This project aims to provide blogging is more than just a platform to
share personal anecdotes; it's a potent tool for businesses,
developers, and creators. Within the context of a MERN application,
blogging serves several crucial purposes
 Knowledge Sharing: A MERN stack often powers complex web
applications. Through blog posts, you can simplify intricate concepts,
share tutorials, and offer insights into how your application works.
This not only benefits your users but also establishes you as an
authority in your field.
 SEO Advantages: Search engines love fresh, relevant content. Each
blog post is a new indexed page on your website, increasing your
chances of ranking higher in search results. This organic traffic can
significantly boost your application's visibility.
 User Engagement: Blogs are an excellent way to communicate with
your audience directly. Users can leave comments, ask questions,
and share their thoughts. This interaction fosters a sense of
community around your application.
 Showcasing Updates: Whether you're launching new features,
updates, or improvements to your MERN application, blogs can serve
as the perfect platform to announce and explain these changes in
detail.

Page 73 of 80
Objective:
 Knowledge Sharing and Education: One of the primary objectives
of blogging is to share valuable information, insights, and expertise.
Blogs can serve as platforms to educate the audience about specific
topics, provide tutorials, explain complex concepts, and offer practical
advice.

 Thought Leadership: Blogging allows individuals and businesses to


establish themselves as thought leaders in their respective fields

 Building an Online Presence: Blogs contribute to building a strong


online presence.

 Driving Website Traffic: Blogs can be a powerful tool for driving


organic traffic to a website.

SDLC (Software Development Life Cycle) : Blogging

Analysis

Page 74 of 80
The analysis phase of developing a hospital management system
involves understanding the requirements, constraints, and objectives of
the system

1. Requirement Analysis:
2. Use case and User Story
3. Data Analysis
4. Process Analysis
5. System Architecture Analysis

These all above analysis are used to analysis the projects details
according to the need if that

Hardware and Software Details

HARDWARE REQUIREMENTS:

 Processor: Intel dual core or above


 Processor Speed:1.0GHZ or above
 RAM: 1 GB RAM or above
 Hard Disk: 20 GB hard disk or above

SOFTWARE REQUIREMENTS:
Web language: MERN
 Language: ---
 Database: MongoDB

Modules of the software:


User Authentication and Authorization:
This module handles user registration, login, and authentication.
It manages user roles and permissions to control access to different
features (e.g., authors, editors, administrators).

Dashboard:
The dashboard is the main interface for users to manage their blog.
It provides an overview of blog statistics, recent posts, comments, and
other relevant information.

Content Creation and Management:


This module allows users to create, edit, and manage blog posts.

Page 75 of 80
It includes a rich text editor for formatting content, adding images,
videos, and other media.

Categories and Tags:


Categories and tags help organize and classify blog posts.
Users can assign relevant categories and tags to their posts for easier
navigation and content discovery.

Media Management:
This module enables users to upload, manage, and insert media files
like images and videos into their blog posts.

Comments and Interaction:


The comment system allows readers to leave comments on blog posts.
It may include moderation features for the blogger to approve or
manage comments.
Search and Navigation:
A search module helps users and readers find specific blog posts.
Navigation features like menus and breadcrumbs improve the user
experience and help users explore content.

User Profiles:
User profiles allow bloggers to showcase their information, bio, and
social media links.
Readers can also have profiles to track their interactions and
discussions on the blog.

Social Sharing:
Integration with social media platforms allows users and readers to
easily share blog posts on various networks.

SEO and Analytics:


This module helps optimize blog posts for search engines by providing
meta tags, descriptions, and keywords.
Analytics tools provide insights into traffic, user behavior, and popular
content.

Subscription and Notifications:


Readers can subscribe to the blog to receive notifications about new
posts via email or RSS feeds.

Responsive Design:
A responsive design module ensures that the blog is accessible and
user-friendly across various devices and screen sizes.

Page 76 of 80
Monetization:
For bloggers who want to monetize their content, this module includes
features like ad integration, affiliate links, and selling digital products.

Settings and Configuration:


This module allows bloggers to customize various aspects of the blog,
including layout, typography, colors, and more.

Backup and Security:


Backup and security modules help protect the blog's data and content
from loss or unauthorized access.

Third-Party Integrations:
Integrations with external services like email marketing platforms,
comment systems (e.g., Disqus), and social media APIs enhance the
functionality of the blog.

Design

Designing a full-stack blogging page involves creating both the frontend


and backend components of the application. Below is a high-level overview
of the components and technologies you might use for each part. Keep in
mind that this is a general outline, and you can customize it based on your
preferences and requirements.

Frontend
User Interface (UI):

Design a responsive and user-friendly UI using HTML, CSS, and possibly a


UI library like Bootstrap or Material-UI.
Create pages for blog posts, home feed, user profile, settings, etc.
Implement features like search, filters, and categories for easy navigation.

Client-Side Logic:

Use JavaScript (and a framework like React, Angular, or Vue.js) to handle


Page 77 of 80
dynamic content and interactivity.
Fetch and display blog posts, user information, and comments using APIs.

Authentication and Authorization:

Implement user registration and login using JWT (JSON Web Tokens) or
OAuth.
Control access to certain features based on user roles (admin, author,
reader).

API Integration:

Interact with the backend APIs for fetching and posting data.
Use libraries like Axios or Fetch API to make API requests.

Backend
Server:

Choose a backend technology like Node.js, Python (Django or Flask), Ruby


(Ruby on Rails), Java (Spring Boot), etc.
Set up a server to handle incoming requests and route them appropriately.

Database:

Select a database system like MySQL, PostgreSQL, MongoDB, etc., to


store blog posts, user data, and comments.
Design the database schema to represent blog posts, users, comments,
categories, etc.

API Endpoints:

Create RESTful API endpoints for operations like creating, reading,


updating, and deleting blog posts, comments, and user information.
Implement endpoints for user authentication and authorization.

Authentication and Authorization:

Use libraries like Passport (Node.js) or Django's built-in authentication for


handling user authentication.
Implement authorization checks to ensure users have the right permissions
for certain actions.

Page 78 of 80
Security:

Sanitize user inputs to prevent SQL injection, cross-site scripting (XSS),


and other security vulnerabilities.
Implement CORS (Cross-Origin Resource Sharing) to control which
domains can access your API.

Deployment:

Deploy your backend on a server (e.g., AWS, Heroku, DigitalOcean) and


set up the necessary configurations.
Use a domain or subdomain for your application.

CONCLUSION

Blogging in a MERN application offers a myriad of benefits, from educating


users to enhancing SEO and fostering engagement. By effectively
implementing and promoting your blog, you can create a thriving
community around your application, establishing yourself as a valuable
resource in your niche. So, harness the power of blogging and watch your
MERN application flourish like never before.

REFERENCES

Page 79 of 80
Here are some references and resources you can use to learn more about
building a blogging page:

Frontend Development:

HTML & CSS:

MDN Web Docs: HTML - https://developer.mozilla.org/en-US/docs/Web/HTML


MDN Web Docs: CSS - https://developer.mozilla.org/en-US/docs/Web/CSS

JavaScript:

MDN Web Docs: JavaScript -


https://developer.mozilla.org/en-US/docs/Web/JavaScript
React:

React Documentation - https://reactjs.org/docs/getting-started.html


React Router Documentation - https://reactrouter.com/web/guides/quick-start

UI Libraries:

Bootstrap Documentation -
https://getbootstrap.com/docs/5.0/getting-started/introduction/
Material-UI Documentation - https://mui.com/getting-started/installation/

Backend Development:

Node.js:

Node.js Documentation - https://nodejs.org/en/docs/


Express.js (Node.js Framework):

Express.js Documentation - https://expressjs.com/

MongoDB Documentation - https://docs.mongodb.com/

Page 80 of 80

You might also like