[go: up one dir, main page]

0% found this document useful (0 votes)
66 views36 pages

Real Time Chat 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 36

A project Report submitted to

DEPARTMENT OF COMPUTER SCIENCE & INFORMATION TECHNOLOGY

MASTER OF COMPUTER APPLICATIONS (MCA IV)

By

GOURAV YADAV

Roll No: 22072123

Enrollment No: GGV/22/05020

Under the Guidance of

Dr. BABITA MANJHI

DEPARTMENT OF COMPUTER SCIENCE & INFORMATION TECHNOLOGY

GURU GHASIDAS VISHWAVIDYALAYA, BILASPUR


Session: 2022-2024
CERTIFICATE OF SUPERVISOR(S) /GUIDE

This is to certify that the work incorporated in the project Real-time Chat is a record of six month
project work assigned by Spitech pvt. ltd, successfully carried out by GOURAV YADAV bearing
Enrollment No GGV/22/05020 under my guidance and supervision for the award of Degree of Master
of Computer Applications (MCA) of DEPARTMENT OF COMPUTER SCIENCE & INFORMATION
TECHNOLOGY, GURU GHASIDAS VISHWAVIDYALAYA, BILASPUR C.G., INDIA. To the best of my
knowledge and belief the report embodies the work of the candidate him/herself and has duly been
successfully completed.

Signature of the Supervisor/Guide Signature of HOD

Name:………………………………. Name:……………………………….
DELCLARATION BY THE CANDIDATE

I, GOURAV YADAV ,Student of IV Semester MCA, DEPARTMENT OF COMPUTER SCIENCE & INFORMATION
TECHNOLOGY, GURU GHASIDAS VISHWAVIDYALAYA, BILASPUR, bearing Enrolment Number
GGV/22/05020 here by declare that the project titled Real-time Chat has been carried out by me under
the Guidance/Supervision of Dr. Babita manjhi, Designation of Guide submitted in partial fulfillment
of the requirements for the award of the Degree of Master of Computer Applications (MCA) by the
Department Of Computer Science & Information Technology, Guru Ghasidas Vishwavidyalaya, Bilaspur
during the academic year 2022-24 .This report has not been submitted to any other
Organization/University for any award of Degree/Diploma.

(Signature of Candidate)

Date:

Place:
ACKNOWLEDGEMENT

I have great pleasure in the submission of this project report entitled Real-time Chat in partial
fulfillment of the degree of Master of Computer Applications. While Submitting this Project
report, I take this opportunity to thank those directly or indirectly related to project work.

I would like to thank my guide Dr. Babita Manjhi, who has provided the opportunity and
organizing project for me. Without his active co-operation and guidance, it would have become
very difficult to complete task in time.

I would like to express sincere thanks to Dr. Ratnesh Prasad Srivastava, Head of Department Of
Computer Science & Information Technology, Guru Ghasidas Vishwavidyalaya, Bilaspur C.G

Acknowledgement is due to my parents, family members, friends and all those persons who have
helped me directly or indirectly in the successful completion of the project work.

(GOURAV YADAV)
CERTIFICATE BY THE EXAMINER

This is to certified that the project work entitled " Real-time Chat " submitted by GOURAV YADAV
has completed under the supervision of Dr. Babita Manjhi Dept. of "Computer Science &
Information Technology", GGU Bilaspur (C.G.) has been examined by the undersigned as a part Of
the examination for the award of the MCA Degree in Dept. of "Computer Science & Information
Technology" in GURU GHASIDAS CENTRAL UNIVERSITY BILASPUR (C.G.).

"Project Examined & Approved"

………………………………. ……………………………….

Internal Examiner External Examiner


Date: Date:

……………………………………………………………………
Signature of H.O.D (CSIT)

GURU GHASIDAS CENTRAL UNIVERSITY BILASPUR (C.G.)


Table of Contents
1. Introduction
o Purpose
o Scope
o Overview
2. System Architecture
o High-Level Architecture
o Component Breakdown
o Data Flow
3. Technologies Used
o Frontend Technologies
o Backend Technologies
o Database
o Real-Time Communication Protocols
o Security and Encryption
4. Installation and Setup
o Prerequisites
o Local Development Setup
o Production Deployment
o Environment Configuration
5. Features
o Core Features
o Advanced Features
o User Interface Details
6. API Documentation
o Authentication
o Messaging API
o User Management
o Group Chats
o Multimedia Sharing
7. Database Schema
o Schema Overview
o Collections/Tables
o Relationships
o Indexing Strategy
8. Real-Time Communication
o WebSocket Implementation
o Event Handling
o Typing Indicators
o Message Delivery and Read Receipts
9. Security Considerations
o Authentication and Authorization
o Data Encryption
o Secure Communication
o User Privacy
10. Testing
o Unit Testing
o Integration Testing
o End-to-End Testing
o Performance Testing
11. Monitoring and Maintenance
o Logging and Monitoring
o Error Handling
o Scalability and Load Testing
o Backup and Recovery
12. Troubleshooting
o Common Issues
o Debugging Tips
o FAQs
13. Future Enhancements
o Planned Features
o Potential Improvements
o Roadmap
14. Conclusion
o Summary
o Final Notes

1. Introduction

Purpose

This documentation provides a detailed guide for developers, administrators, and users
involved in the design, development, deployment, and maintenance of the real-time chat
application. It aims to clarify the technical aspects, features, and functionalities of the
application.

Scope

This documentation covers all aspects of the real-time chat application, from the architecture
and technology stack to deployment and future enhancements. It is intended for both
technical and non-technical stakeholders.

Overview

The real-time chat application facilitates instant communication between users, supporting
both one-on-one and group chats. It includes features such as message delivery and read
receipts, typing indicators, multimedia sharing, and user presence tracking.

2. What is Real-Time Chat?

Definition:
Real-time chat refers to the capability of a digital communication system that allows users to
send and receive messages instantly, without noticeable delay. Unlike traditional messaging
systems where communication might be asynchronous (such as email), real-time chat enables
synchronous communication where participants can engage in a live conversation.

Key Characteristics:

 Instant Delivery: Messages are transmitted and received almost instantaneously.


 Synchronous Communication: Both parties can interact in real time, creating a fluid
conversation.
 User Presence Indicators: Real-time systems often include indicators such as "online" or
"typing..." to enhance the interactive experience.
 Low Latency: Real-time chat systems are optimized to minimize the delay (latency) between
sending and receiving messages.

3. System Architecture

High-Level Architecture

The real-time chat system follows a client-server architecture, where the frontend (client)
communicates with the backend (server) via APIs and real-time communication protocols
like WebSockets.

 Client: Built with React, handling the user interface and interaction.
 Server: Node.js with Express, managing API requests, WebSocket connections, and
business logic.
 Database: MongoDB, storing user data, messages, and chat history.
 Real-Time Protocol: WebSockets, enabling low-latency communication between the
client and server.

Component Breakdown

 Frontend Components: User Interface, State Management, WebSocket Handling,


API Integration.
 Backend Components: REST API, WebSocket Server, Authentication Service,
Database Interface.
 Database: Collections for Users, Messages, Chat Rooms, etc.

Data Flow

 User Registration/Login: Users register or log in, authenticated via JWT.


 Message Flow: Messages are sent from the client to the server via WebSockets and
stored in the database.
 Real-Time Updates: Server pushes real-time updates to clients using WebSockets.

4. Technologies Used

Frontend Technologies

 React: For building the user interface.


 Redux or Context API: For state management.
 Material-UI or Bootstrap: For UI components and styling.
 WebSockets: For real-time communication.

Backend Technologies

 Node.js: For the server runtime environment.


 Express.js: For routing and middleware.
 Socket.io or ws: For managing WebSocket connections.

Database

 MongoDB: NoSQL database for storing user information, chat history, and metadata.
 Mongoose: ORM for MongoDB, defining schemas and managing data relationships.

Real-Time Communication Protocols

 WebSockets: A protocol providing full-duplex communication channels over a single


TCP connection.

Security and Encryption

 JWT (JSON Web Tokens): For secure user authentication.


 SSL/TLS: For encrypting data in transit between client and server.

5. Installation and Setup

Prerequisites

 Node.js: Version 14.x or later.


 MongoDB: Local or cloud instance.
 Git: For version control.

Local Development Setup

1. Clone the repository.


2. Install dependencies using npm install.
3. Set up environment variables (.env file).
4. Start the development server with npm start.
5. Run MongoDB locally or connect to a cloud database.

Production Deployment

 Docker: Containerize the application for deployment.


 CI/CD Pipeline: Use Jenkins, GitHub Actions, or other tools for automated
deployment.
 Hosting: Deploy on platforms like AWS, Heroku, or DigitalOcean.

Environment Configuration
 Define environment variables for API keys, database URIs, and secret keys in a .env
file.

6. Features

Core Features

 Instant Messaging: Users can send and receive messages in real-time.


 Group Chats: Support for creating and managing group conversations.
 User Presence: Display online/offline status.
 Message Status Indicators: Sent, delivered, and read receipts.

Advanced Features

 Multimedia Sharing: Users can send images, videos, and files.


 Search Functionality: Search through chat history.
 Notifications: Real-time notifications for new messages.

User Interface Details

 Chat Interface: A clean, responsive design with easy navigation.


 User Profiles: Customizable user profiles with avatars.
 Settings: Options to customize chat experience, notifications, and privacy settings.

7. API Documentation

Authentication

 Endpoints: /api/register, /api/login, /api/logout.


 Methods: POST, GET.
 Security: JWT tokens for authentication.

Messaging API

 Endpoints: /api/messages, /api/messages/{id}.


 Methods: POST, GET, DELETE.
 Real-Time Events: message:send, message:receive.

User Management

 Endpoints: /api/users, /api/users/{id}.


 Methods: GET, PUT, DELETE.

Group Chats

 Endpoints: /api/groups, /api/groups/{id}.


 Methods: POST, GET, PUT, DELETE.

Multimedia Sharing
 Endpoints: /api/upload, /api/files/{id}.
 Methods: POST, GET.

8. Database Schema

Schema Overview

 Users Collection: Stores user credentials, profile information, and settings.


 Messages Collection: Stores individual messages, timestamps, and sender/receiver
IDs.
 Groups Collection: Stores group information, member IDs, and settings.

Collections/Tables

 Users: { userId, username, email, passwordHash, avatarUrl, status }


 Messages: { messageId, senderId, receiverId, content, timestamp, status }
 Groups: { groupId, groupName, memberIds, createdDate }

Relationships

 User-Messages: One-to-Many (a user can send many messages).


 Group-Messages: Many-to-Many (a message can belong to many users in a group).

Indexing Strategy

 Indexes: Created on user IDs and timestamps for efficient querying.

9. Real-Time Communication

WebSocket Implementation

 Connection Handling: Establish and manage WebSocket connections for each user
session.
 Event Handling: Listen for and emit events such as message:send, user:typing,
and message:read.

Typing Indicators

 Event: user:typing – Broadcasts to other users in the conversation that a user is


typing.

Message Delivery and Read Receipts

 Event: message:status – Updates the status of messages (sent, delivered, read).

10. Security Considerations

Authentication and Authorization


 JWT: Used to secure API endpoints and manage user sessions.
 Role-Based Access Control (RBAC): Implemented for admin, user, and guest roles.

Data Encryption

 At Rest: Encrypt sensitive data in the database (e.g., passwords with bcrypt).
 In Transit: Use HTTPS for all client-server communication.

Secure Communication

 WebSocket Security: Implement token-based authentication for WebSocket


connections.
 Rate Limiting: Prevent abuse by limiting the number of API requests per user.

User Privacy

 GDPR Compliance: Ensure that user data management complies with data protection
regulations.

11. Testing

Unit Testing

 Frameworks: Use Jest or Mocha for testing individual components and functions.
 Coverage: Ensure high code coverage, focusing on critical paths like authentication
and messaging.

Integration Testing

 Tools: Use tools like Postman or Insomnia to test API integrations.


 Test Scenarios: Simulate end-to-end user actions to verify system behavior.

End-to-End Testing

 Frameworks: Use Cypress or Selenium for automated UI testing.


 Test Scenarios: Cover critical user journeys, including message sending, group chat
creation, and user login.

Performance Testing

 Load Testing: Use tools like Apache JMeter to test how the application performs
under load.
 Scalability Testing: Simulate large numbers of concurrent users to ensure the system
scales appropriately.

12. Monitoring and Maintenance

Logging and Monitoring


 Tools: Implement logging with tools like Winston and monitor the system with
Prometheus or Grafana.
 Log Management: Store and analyze logs for errors, usage patterns, and performance
bottlenecks.

Error Handling

 Error Tracking: Use tools like Sentry or Rollbar for real-time error tracking and
alerts.
 Retry Mechanisms: Implement automatic retries for transient errors in message
delivery.

Scalability and Load Testing

 Horizontal Scaling: Set up auto-scaling for servers to handle increasing loads.


 Database Sharding: Implement database sharding to distribute data across multiple
servers.

Backup and Recovery

 Backup Strategy: Regularly back up the database and critical configurations.


 Disaster Recovery Plan: Have a plan in place for data restoration and service
continuity in case of failure.

13. Troubleshooting

Common Issues

 WebSocket Disconnections: Issues with network or server causing disconnections.


 Database Latency: Slow query performance affecting real-time communication.
 Authentication Failures: Token expiration or invalid token issues.

Debugging Tips

 Console Logging: Use detailed logging at critical points in the application to identify
issues.
 Network Tools: Use tools like Wireshark to monitor and debug network traffic.

FAQs

 Why are messages not being delivered? Possible network issues, server downtime,
or WebSocket disconnections.
 How to reset a user password? Implement a password reset flow via email or secure
token.

14. Future Enhancements

Planned Features

 Voice and Video Chat: Integrating real-time voice and video communication.
 AI-Powered Chatbots: Implementing AI to handle common user queries and
automate responses.
 End-to-End Encryption: Adding full end-to-end encryption for enhanced privacy.

Potential Improvements

 UI/UX Enhancements: Continuous improvement based on user feedback.


 Localization: Support for multiple languages and regions.
 Performance Optimization: Reducing latency and improving message delivery
speed.

Roadmap

 Phase 1: Core feature development (Messaging, Group Chats, User Presence).


 Phase 2: Advanced feature implementation (Multimedia Sharing, AI Integration).
 Phase 3: Global rollout and scaling.

15. Technological Exploration

a. Investigate Emerging Technologies

 Artificial Intelligence:
o Advanced NLP: Explore how advancements in natural language processing
can enhance chatbots, automate conversations, and predict user intent.
o Sentiment Analysis: Investigate AI that can understand user emotions and
adjust responses accordingly, making chats more empathetic and effective.
 Blockchain and Decentralization:
o Decentralized Chat: Explore the possibilities of creating decentralized chat
platforms where user data is stored on a blockchain, enhancing privacy and
security.
o Smart Contracts: Consider using smart contracts for automating transactions
or agreements within chat environments, especially in business or e-commerce
contexts.
 Immersive Technologies:
o AR/VR Integration: Develop concepts for chat applications that use
augmented or virtual reality to create immersive communication experiences,
like virtual meeting rooms or interactive 3D messaging.
 5G and Edge Computing:
o Low-Latency Communication: Utilize 5G and edge computing to enable
ultra-low latency in real-time chat, making voice, video, and text interactions
more seamless.
o Real-Time Processing: Explore how edge computing can be used to process
data closer to the user, reducing the lag in chat responses and enabling more
complex real-time interactions.

16. Core Technologies Behind Real-Time Chat


a. WebSockets:

 What It Is: A communication protocol that provides full-duplex communication channels


over a single TCP connection.
 Why It’s Important: WebSockets allow for the continuous flow of messages between the
client and server, making them ideal for real-time applications. Unlike traditional HTTP
requests, WebSockets maintain an open connection, reducing the need for constant
reestablishing of connections, which increases efficiency.

b. Server-Sent Events (SSE):

 What It Is: A server push technology enabling a server to send updates to a client over an
HTTP connection.
 Why It’s Important: While similar to WebSockets, SSE is often easier to implement for
simpler real-time chat systems where the communication is predominantly one-way (server
to client).

c. REST APIs and GraphQL:

 What It Is: REST and GraphQL are protocols used for fetching data from a server.
 Why It’s Important: These technologies enable the retrieval and submission of chat data,
user information, and more. While not real-time, they often work in conjunction with
WebSockets to provide the full range of needed functionalities.

d. Message Queues:

 What It Is: A messaging system that allows the decoupling of sender and receiver by placing
messages in a queue.
 Why It’s Important: Queues can manage the flow of messages, ensure that they are
processed in the right order, and allow for scaling when dealing with large numbers of users.

e. Database Technologies:

 Real-Time Databases: Databases like Firebase are designed for real-time data
synchronization, making them ideal for chat applications where data needs to be instantly
available across multiple clients.
 MongoDB: Often used in real-time chat applications for storing chat logs, user profiles, and
other related data due to its scalability and flexibility with JSON-like documents.

17. Features of Real-Time Chat Applications

a. Instant Messaging:

 Text Communication: The primary feature allowing users to send and receive text messages
in real time.
 Typing Indicators: Shows when a user is typing, enhancing the interactive nature of the chat.

b. User Presence:
 Online/Offline Status: Indicates if users are available for chat.
 Last Seen: Shows when a user was last active, providing context for their availability.

c. Group Chat:

 Multiple Participants: Supports chat with multiple users simultaneously.


 Group Management: Features for creating, managing, and moderating groups, including
adding/removing members, setting permissions, and more.

d. Multimedia Sharing:

 File Sharing: Allows users to share images, videos, documents, and other files within the
chat.
 Rich Media Integration: Support for previewing multimedia within the chat interface itself.

e. Message Delivery and Read Receipts:

 Sent, Delivered, Read Indicators: Visual feedback that informs the sender when their
message has been sent, delivered, and read by the recipient.

f. Push Notifications:

 In-App and System Notifications: Alerts users to new messages, ensuring they stay informed
even when not actively using the app.

g. Search and Filter:

 Message Search: Enables users to search through past conversations for specific keywords
or phrases.
 User Search: Allows quick access to contacts or chat groups.

h. Security and Privacy:

 End-to-End Encryption: Protects messages by ensuring that only the sender and recipient
can read them.
 Authentication: Secure user login processes, often enhanced with multi-factor
authentication (MFA).

i. Customization:

 Themes and Layouts: Options for users to personalize the appearance of the chat interface.
 Notification Settings: Customizable settings for notifications, including sound, vibration, and
Do Not Disturb modes.

j. Bots and Automation:

 Chatbots: Automated programs that can handle common queries, provide information, or
even simulate conversations.
 AI-Driven Responses: AI can generate smart replies or suggestions based on the context of
the conversation.
k. Voice and Video Calls:

 Integrated Calls: Many real-time chat apps offer voice and video calling directly within the
chat, expanding the communication options beyond text.

18. User Experience (UX) and User Interface (UI) Considerations

a. Intuitive Design:

 Simple Navigation: The layout should be easy to navigate, with clear icons and labels.
 Responsive Design: The chat interface should work seamlessly across devices, whether on
mobile, desktop, or tablet.

b. Accessibility:

 Support for Assistive Technologies: Ensuring the chat app is usable by people with
disabilities, including screen readers and keyboard navigation.
 High Contrast Mode: Options for users with visual impairments to adjust the contrast for
better readability.

c. Real-Time Feedback:

 Visual Cues: Use of animations, sounds, or other visual indicators to provide immediate
feedback when a user sends a message or performs an action.

18. Performance and Scalability

a. Low Latency:

 Optimized Networking: Using technologies like WebSockets to maintain a continuous, low-


latency connection between client and server.
 Edge Computing: Processing data closer to the user to reduce latency and improve real-time
performance.

b. Load Balancing:

 Scalability: Distributing the chat load across multiple servers to ensure that the system can
handle a large number of users simultaneously without performance degradation.
 Failover Strategies: Implementing backup systems that take over in case of server failure,
ensuring that the chat remains available even during disruptions.

c. Data Caching:

 Improved Speed: Using caching mechanisms to store frequently accessed data closer to the
user, reducing the time it takes to load messages or user information.
19. Security Considerations

a. End-to-End Encryption:

 Data Protection: Encrypting messages so that only the intended recipient can decrypt and
read them, preventing eavesdropping by third parties.
 Transport Layer Security (TLS): Ensuring that data transmitted between the client and server
is encrypted using TLS.

b. Secure Authentication:

 Multi-Factor Authentication (MFA): Requiring multiple forms of verification (e.g., password,


biometric) to ensure that only authorized users can access their accounts.
 OAuth and SSO: Using secure authentication protocols like OAuth or Single Sign-On (SSO) to
streamline and secure the login process.

c. Data Privacy and Compliance:

 GDPR Compliance: Ensuring that the chat application adheres to data privacy regulations
like the General Data Protection Regulation (GDPR), protecting users’ personal data.
 User Control Over Data: Giving users control over their data, including the ability to delete
conversations and manage privacy settings.

20. Future Trends in Real-Time Chat

a. Artificial Intelligence (AI):

 Context-Aware Chatbots: AI-powered bots that can understand and respond to complex
queries by interpreting the context of the conversation.
 Sentiment Analysis: Using AI to gauge the sentiment of messages and adjust responses or
flag issues accordingly.

b. Blockchain and Decentralization:

 Decentralized Chat Systems: Using blockchain technology to create chat platforms where
data is not stored in a central location, enhancing privacy and security.
 Smart Contracts: Automating agreements within chat environments using blockchain-based
smart contracts, useful in business or legal contexts.

c. Immersive Experiences:

 Augmented Reality (AR) and Virtual Reality (VR): Integrating AR/VR to create immersive
chat experiences, such as virtual meeting rooms or 3D interactive environments.

d. Real-Time Translation:
 Multilingual Support: Advanced AI-powered translation engines that provide real-time
translation of messages, allowing users who speak different languages to communicate
seamlessly.

e. Hyper-Personalization:

 Behavioral Insights: Using machine learning to analyze user behavior and preferences,
tailoring the chat experience to individual users.

. Challenges and Considerations

a. Scalability:

 Infrastructure Costs: Balancing the cost of infrastructure with the need to scale, particularly
as user bases grow.
 Managing Peak Traffic: Ensuring the chat system can handle spikes in traffic, such as during
events or emergencies.

b. Security Risks:

 Data Breaches: Protecting against cyber-attacks that could compromise

22. Conclusion

Summary

The real-time chat application provides a robust platform for instant communication,
combining a modern tech stack with real-time features. The documentation outlines the
system architecture, features, and technologies used, providing a clear guide for developers
and administrators.

Final Notes

Continuous monitoring, user feedback, and iterative development are key to maintaining and
improving the application. Future enhancements and scalability are essential for meeting
evolving user needs and technological advancements.
IMPLEMENTATION CODE
CHAT.jsx
import React, { useEffect, useState, useRef } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { io } from "socket.io-client";
import styled from "styled-components";
import { allUsersRoute, host } from "../utils/APIRoutes";
import ChatContainer from "../components/ChatContainer";
import Contacts from "../components/Contacts";
import Welcome from "../components/Welcome";

export default function Chat() {


const navigate = useNavigate();
const socket = useRef();
const [contacts, setContacts] = useState([]);
const [currentChat, setCurrentChat] = useState(undefined);
const [currentUser, setCurrentUser] = useState(undefined);
useEffect(async () => {
if (!localStorage.getItem(process.env.REACT_APP_LOCALHOST_KEY)) {
navigate("/login");
} else {
setCurrentUser(
await JSON.parse(
localStorage.getItem(process.env.REACT_APP_LOCALHOST_KEY)
)
);
}
}, []);
useEffect(() => {
if (currentUser) {
socket.current = io(host);
socket.current.emit("add-user", currentUser._id);
}
}, [currentUser]);

useEffect(async () => {
if (currentUser) {
if (currentUser.isAvatarImageSet) {
const data = await axios.get(${allUsersRoute}/${currentUser._id});
setContacts(data.data);
} else {
navigate("/setAvatar");
}
}
}, [currentUser]);
const handleChatChange = (chat) => {
setCurrentChat(chat);
};
return (
<>
<Container>
<div className="container">
<Contacts contacts={contacts} changeChat={handleChatChange} />
{currentChat === undefined ? (
<Welcome />
):(

<ChatContainer currentChat={currentChat} socket={socket} />


)}
</div>
</Container>
</>
);
}

const Container = styled.div`


height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
justify-content: center;
gap: 1rem;
align-items: center;
background-color: #131324;
.container {
height: 85vh;
width: 85vw;
background-color: #00000076;
display: grid;
grid-template-columns: 25% 75%;
@media screen and (min-width: 720px) and (max-width: 1080px) {
grid-template-columns: 35% 65%;
}
}
`;
LOGIN.jsx
import React, { useState, useEffect } from "react";
import axios from "axios";
import styled from "styled-components";
import { useNavigate, Link } from "react-router-dom";
import Logo from "../assets/logo.svg";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import { loginRoute } from "../utils/APIRoutes";

export default function Login() {


const navigate = useNavigate();
const [values, setValues] = useState({ username: "", password: "" });
const toastOptions = {
position: "bottom-right",
autoClose: 8000,
pauseOnHover: true,
draggable: true,
theme: "dark",
};
useEffect(() => {
if (localStorage.getItem(process.env.REACT_APP_LOCALHOST_KEY)) {
navigate("/");
}
}, []);

const handleChange = (event) => {


setValues({ ...values, [event.target.name]: event.target.value });
};
const validateForm = () => {
const { username, password } = values;
if (username === "") {
toast.error("Email and Password is required.", toastOptions);
return false;
} else if (password === "") {
toast.error("Email and Password is required.", toastOptions);
return false;
}
return true;
};

const handleSubmit = async (event) => {


event.preventDefault();
if (validateForm()) {
const { username, password } = values;
const { data } = await axios.post(loginRoute, {
username,
password,
});
if (data.status === false) {
toast.error(data.msg, toastOptions);
}
if (data.status === true) {
localStorage.setItem(
process.env.REACT_APP_LOCALHOST_KEY,
JSON.stringify(data.user)
);
navigate("/");
}
}
};

return (
<>
<FormContainer>
<form action="" onSubmit={(event) => handleSubmit(event)}>
<div className="brand">
<img src={Logo} alt="logo" />
<h1>snappy</h1>
</div>
<input
type="text"
placeholder="Username"
name="username"
onChange={(e) => handleChange(e)}
min="3"
/>
<input
type="password"
placeholder="Password"
name="password"
onChange={(e) => handleChange(e)}
/>
<button type="submit">Log In</button>
<span>
Don't have an account ? <Link to="/register">Create One.</Link>
</span>
</form>
</FormContainer>
<ToastContainer />
</>
);
}

const FormContainer = styled.div`


height: 100vh;
width: 100vw;
display: flex;
flex-direction: column;
justify-content: center;
gap: 1rem;
align-items: center;
background-color: #131324;
.brand {
display: flex;
align-items: center;
gap: 1rem;
justify-content: center;
img {
height: 5rem;
}
h1 {
color: white;
text-transform: uppercase;
}
}

form {
display: flex;
flex-direction: column;
gap: 2rem;
background-color: #00000076;
border-radius: 2rem;
padding: 5rem;
}
input {
background-color: transparent;
padding: 1rem;
border: 0.1rem solid #4e0eff;
border-radius: 0.4rem;
color: white;
width: 100%;
font-size: 1rem;
&:focus {
border: 0.1rem solid #997af0;
outline: none;
}
}
button {
background-color: #4e0eff;
color: white;
padding: 1rem 2rem;
border: none;
font-weight: bold;
cursor: pointer;
border-radius: 0.4rem;
font-size: 1rem;
text-transform: uppercase;
&:hover {
background-color: #4e0eff;
}
}
span {
color: white;
text-transform: uppercase;
a{
color: #4e0eff;
text-decoration: none;
font-weight: bold;
}
}
`;
RESISTER.jsx
import React, { useState, useEffect } from "react";

import axios from "axios";

import styled from "styled-components";

import { useNavigate, Link } from "react-router-dom";

import Logo from "../assets/logo.svg";

import { ToastContainer, toast } from "react-toastify";

import "react-toastify/dist/ReactToastify.css";

import { registerRoute } from "../utils/APIRoutes";

export default function Register() {

const navigate = useNavigate();

const toastOptions = {

position: "bottom-right",

autoClose: 8000,

pauseOnHover: true,

draggable: true,

theme: "dark",

};

const [values, setValues] = useState({

username: "",

email: "",

password: "",

confirmPassword: "",

});

useEffect(() => {

if (localStorage.getItem(process.env.REACT_APP_LOCALHOST_KEY)) {

navigate("/");

}, []);
const handleChange = (event) => {

setValues({ ...values, [event.target.name]: event.target.value });

};

const handleValidation = () => {

const { password, confirmPassword, username, email } = values;

if (password !== confirmPassword) {

toast.error(

"Password and confirm password should be same.",

toastOptions

);

return false;

} else if (username.length < 3) {

toast.error(

"Username should be greater than 3 characters.",

toastOptions

);

return false;

} else if (password.length < 8) {

toast.error(

"Password should be equal or greater than 8 characters.",

toastOptions

);

return false;

} else if (email === "") {

toast.error("Email is required.", toastOptions);

return false;

return true;
};

const handleSubmit = async (event) => {

event.preventDefault();

if (handleValidation()) {

const { email, username, password } = values;

const { data } = await axios.post(registerRoute, {

username,

email,

password,

});

if (data.status === false) {

toast.error(data.msg, toastOptions);

if (data.status === true) {

localStorage.setItem(

process.env.REACT_APP_LOCALHOST_KEY,

JSON.stringify(data.user)

);

navigate("/");

};

return (

<>

<FormContainer>

<form action="" onSubmit={(event) => handleSubmit(event)}>

<div className="brand">

<img src={Logo} alt="logo" />


<h1>snappy</h1>

</div>

<input

type="text"

placeholder="Username"

name="username"

onChange={(e) => handleChange(e)}

/>

<input

type="email"

placeholder="Email"

name="email"

onChange={(e) => handleChange(e)}

/>

<input

type="password"

placeholder="Password"

name="password"

onChange={(e) => handleChange(e)}

/>

<input

type="password"

placeholder="Confirm Password"

name="confirmPassword"

onChange={(e) => handleChange(e)}

/>

<button type="submit">Create User</button>

<span>

Already have an account ? <Link to="/login">Login.</Link>

</span>

</form>
</FormContainer>

<ToastContainer />

</>

);

const FormContainer = styled.div`

height: 100vh;

width: 100vw;

display: flex;

flex-direction: column;

justify-content: center;

gap: 1rem;

align-items: center;

background-color: #131324;

.brand {

display: flex;

align-items: center;

gap: 1rem;

justify-content: center;

img {

height: 5rem;

h1 {

color: white;

text-transform: uppercase;

form {

display: flex;
flex-direction: column;

gap: 2rem;

background-color: #00000076;

border-radius: 2rem;

padding: 3rem 5rem;

input {

background-color: transparent;

padding: 1rem;

border: 0.1rem solid #4e0eff;

border-radius: 0.4rem;

color: white;

width: 100%;

font-size: 1rem;

&:focus {

border: 0.1rem solid #997af0;

outline: none;

button {

background-color: #4e0eff;

color: white;

padding: 1rem 2rem;

border: none;

font-weight: bold;

cursor: pointer;

border-radius: 0.4rem;

font-size: 1rem;

text-transform: uppercase;

&:hover {

background-color: #4e0eff;
}

span {

color: white;

text-transform: uppercase;

a{

color: #4e0eff;

text-decoration: none;

font-weight: bold;

`;

You might also like