0% found this document useful (0 votes)
11 views6 pages

? Updated Workflow Voting

The document outlines an updated voting system workflow using Twilio for OTP verification, detailing both frontend and backend components. It describes the structure and functionality of various React components, such as VoterLogin, VerifyId, and VoterDashboard, along with server-side logic for sending and verifying OTPs. Additionally, it highlights the use of Supabase for vote storage and retrieval, and emphasizes secure handling of sensitive Twilio credentials.

Uploaded by

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

? Updated Workflow Voting

The document outlines an updated voting system workflow using Twilio for OTP verification, detailing both frontend and backend components. It describes the structure and functionality of various React components, such as VoterLogin, VerifyId, and VoterDashboard, along with server-side logic for sending and verifying OTPs. Additionally, it highlights the use of Supabase for vote storage and retrieval, and emphasizes secure handling of sensitive Twilio credentials.

Uploaded by

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

🤩 UPDATED WORKFLOW: VOTING SYSTEM WITH TWILIO OTP (With Code & In-

depth Explanation at Every Stage)


━━━━━━━━━━━━━━━━━━━━━━━━━━━

🔹 main.tsx – React App Entry Brief: Initializes the React app


and renders the main component.
ReactDOM.createRoot(document.getElementById('root')!).render( <React.StrictM
ode> </React.StrictMode> );
Explanation:
 First file executed in the React application.
 Sets up the root of the React DOM tree..
 Its Uses <React.StrictMode> to identify potential issues.
 Targets in index.HTML.
 Passes control to App.tsx for routing.
━━━━━━━━━━━━━━━━━━━━━━━━━━━

🔹 App.tsx Routing Between Pages Brief: Manages navigation


between pages using React Router.
 Routing & Layout Setup: The app uses react-router-dom for client-side
routing with paths defined for login, dashboards, and a fallback 404 page. All
routes are wrapped inside a Layout component for consistent UI structure.
 Protected Routes: Custom VoterRoute and AdminRoute components ensure
only authenticated users with the right roles (isVoter or isAdmin) can access
specific pages, redirecting unauthorized users to appropriate login or home
pages.
 Global Providers: The app is wrapped in multiple providers—
QueryClientProvider for managing server state with react-query, TooltipProvider
for UI tooltips, and AuthProvider for authentication context.
 Notification System: Both <Toaster /> and <Sonner /> components are
included for displaying toast notifications, possibly from different UI libraries (like
Radix UI or Sonner).

Working:

 Provides route-based navigation using React Router.


 Renders different components based on URL path.
 /login shows phone input.
 /verify for OTP verification.
 /dashboard shows voting options.
 /admin reserved for result viewing.

━━━━━━━━━━━━━━━━━━━━━━━━━━━
🔹 VoterLogin.tsx – Phone Number Input and Trigger OTP Brief: UI for
entering phone number and requesting OTP.
function VoterLogin() { const [phone, setPhone] = useState(''); const navigate =
useNavigate();
const sendOtp = async () => { const res = await fetch('/api/send-otp', { method:
'POST', headers: { 'Content-Type': 'application/json' }, body:
JSON.stringify({ phone }), });
if (res.ok) {
navigate('/verify', { state: { phone } });
} else {
alert('Failed to send OTP');
}
};
return ( <input type="tel" placeholder="Enter phone number" onChange={e =>
setPhone(e.target.value)} /> Send OTP ); }
Explanation:
 User enters phone number.
 Triggers sendOtp() to call backend.
 POSTs phone number to /api/send-otp.
 Navigates to /verify if successful.
 Else shows alert.
 Uses React Router's useNavigate.

Working:

 Renders an input field for user to enter phone number.


 On clicking Send OTP, triggers sendOtp function.
 sendOtp sends a POST request to /api/send-otp with phone number.
 If successful, navigates user to OTP verification page.
 Phone number is passed to next page via state.
 Uses fetch API and useNavigate from React Router.

━━━━━━━━━━━━━━━━━━━━━━━━━━━

🔹 send-otp.ts (Backend) – Twilio Integration to Send OTP Brief: Server-side


endpoint that sends OTP via Twilio.

import twilio from 'twilio';


const client = twilio(process.env.TWILIO_SID!, process.env.TWILIO_TOKEN!);
const OTP_STORE = new Map();
router.post('/send-otp', async (req, res) => { const { phone } = req.body; const
otp = Math.floor(100000 + Math.random() * 900000).toString();
OTP_STORE.set(phone, otp);
try { await client.messages.create({ body: Your OTP is ${otp}, from:
process.env.TWILIO_PHONE!, to: phone, }); res.json({ success: true }); } catch
(err) { res.status(500).json({ success: false }); } });
Explanation:
 Twilio client initialized with credentials.
 Generates 6-digit random OTP.
 Saves OTP in memory with phone number.
 Sends OTP via Twilio SMS.
 Handles success and failure cases.
 API endpoint used by frontend /send-otp.
 Uses environment variables securely.
 Replace Map with Redis for production scale.
━━━━━━━━━━━━━━━━━━━━━━━━━━━

🔹 VerifyId.tsx – OTP Input by User Brief: Lets user input the


received OTP for verification.
Explanation:
 Page for entering OTP.
 Uses state to capture OTP.
 Uses useLocation to get phone number from previous route.
 Sends phone + OTP to backend verify endpoint.
 Redirects to /dashboard if success.
 Shows alert if OTP is invalid.

Working:

 Allows user to input OTP received on their phone.


 Reads the phone number from React Router state.
 On button click, sends phone and OTP to backend via /api/verify-otp.
 If OTP is valid, redirects user to dashboard.
 Uses useLocation and useNavigate from React Router.
 Alerts user if OTP is incorrect.

━━━━━━━━━━━━━━━━━━━━━━━━━━━

🔹 verify-otp.ts (Backend) – OTP Verification Logic


router.post('/verify-otp', (req, res) => { const { phone, otp } = req.body; const
validOtp = OTP_STORE.get(phone);
if (otp === validOtp) { OTP_STORE.delete(phone); res.json({ success: true }); }
else { res.status(401).json({ success: false }); } });
Explanation:
 Validates OTP sent from frontend.
 Retrieves correct OTP from OTP_STORE.
 Deletes OTP after success (one-time use).
 Sends back JSON success flag.
 Uses HTTP 401 if mismatch.
 Should integrate expiry timestamp for better security.

verify-otp.ts (Backend) – OTP Verification Logic Brief: Verifies if entered


OTP matches the one sent.

Working:

 Accepts phone and OTP from frontend.


 Checks if the OTP matches the one stored for that phone number.
 If valid, deletes OTP (one-time use) and returns success.
 If invalid, sends a 401 unauthorized response.
 Protects against reuse and basic brute-force attempts.
 Can be improved with expiry timestamps.

━━━━━━━━━━━━━━━━━━━━━━━━━━━

🔹 VoterDashboard.tsx – Casting Vote Brief: Interface for


authenticated users to cast their vote.
Working:
 Allows authenticated users to submit their vote.
 Uses Supabase to insert vote into database.
 Records phone number and selected candidate.
const castVote = async () => { const { error } = await
supabase.from('votes').insert([ { voter_id: phone, candidate } ]); if (!error)
alert('Vote submitted!'); };
Explanation:
 Sends vote data to Supabase.
 Includes voter phone and chosen candidate.
 Displays alert after successful insert.
 Can add logic to block duplicate voting.
 Requires backend validation for single vote per user.
 Voter data is persisted in Supabase.
━━━━━━━━━━━━━━━━━━━━━━━━━━━

AdminDashboard.tsx – View Voting Results Brief: Admin


panel to see voting results and analytics.
Working:
 Retrieves all votes from Supabase on component load.
 Stores them in component state.
useEffect(() => { const fetchVotes = async () => { const { data } = await
supabase.from('votes').select('*'); setVotes(data); }; fetchVotes(); }, []);
Explanation:
 Fetches all votes from Supabase.
 Stores them in state for display.
 Can be filtered/grouped by candidate.
 Could be shown in chart/table format.
 Access-controlled route for admin.
 Shows live tally of all cast votes.
━━━━━━━━━━━━━━━━━━━━━━━━━━━

.env File – Twilio Credentials Brief: Holds Twilio API credentials


used to send OTP.
Working:
 Stores sensitive Twilio keys securely.
 TWILIO_SID: Twilio account identifier.

TWILIO_SID=ACxxxxxxxxxxxx TWILIO_TOKEN=your_token
TWILIO_PHONE=+1234567890
Explanation:
 Securely stores Twilio credentials.
 Used by Twilio client in backend.
 Should never be committed to Git.
 Loaded using dotenv package.
 Keeps API secrets out of source code.

You might also like