Select Git revision
Breaches.js
Darla Maestas authored
Breaches.js 6.96 KiB
import React, { useState } from 'react'
import {
CButton,
CCard,
CCardBody,
CCardHeader,
CCol,
CForm,
CFormInput,
CInputGroup,
CInputGroupText,
CRow,
} from '@coreui/react'
import CIcon from '@coreui/icons-react'
import { cilTrash, cilPlus, cilCloudDownload } from '@coreui/icons'
import axios from 'axios'
import PasswordStrengthChecker from 'src/components/PasswordStrength'
const Breaches = () => {
const [password, setPassword] = useState('')
const [file, setFile] = useState(null)
const [accounts, setAccounts] = useState([{ password: '' }])
const [result, setResult] = useState(null)
const handlePasswordChange = (e) => setPassword(e.target.value)
const handleFileChange = (e) => setFile(e.target.files[0])
const handleAccountChange = (index, e) => {
const newAccounts = [...accounts]
newAccounts[index].password = e.target.value
setAccounts(newAccounts)
}
const handleAddAccount = () => setAccounts([...accounts, { password: '' }])
const handleRemoveAccount = (index) => {
const newAccounts = [...accounts]
newAccounts.splice(index, 1)
setAccounts(newAccounts)
}
const handleDownloadTemplate = () => {
const templateData = 'Password\nexample@example.com'
const blob = new Blob([templateData], { type: 'text/csv;charset=utf-8' })
const link = document.createElement('a')
link.href = URL.createObjectURL(blob)
link.download = 'password_template.csv'
document.body.appendChild(link)
link.click()
document.body.removeChild(link)
}
const handleAddToDatabase = async (e) => {
e.preventDefault()
const token = localStorage.getItem('token')
console.log('Token retrieved from local storage:', token)
const formData = new FormData()
if (password) formData.append('password', password)
if (file) formData.append('file', file)
accounts.forEach((account, index) => {
if (account.password) formData.append(`passwords[${index}]`, account.password)
})
// Log the form data before sending
console.log('Form Data:', formData)
const headers = {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data',
}
try {
await axios.post('http://localhost:8000/api/breaches/upload/passwords/', formData, { headers,
})
alert('Data submitted successfully')
setPassword('')
setFile(null)
setAccounts([{ password: '' }])
} catch (error) {
console.error('Error uploading data:', error)
alert('Error submitting data')
}
}
const handleSubmitCheck = async (e) => {
e.preventDefault()
if (password) {
try {
const apiUrl = `http://localhost:8000/haveibeenpwned/passwords/${password}/`
const response = await fetch(apiUrl)
const data = await response.json()
console.log('Result from API:', data) // Log the result
if (data.error) {
// No breach detected
setResult([])
setCount(0)
} else {
// Breach detected
let _ct = data.count
setCount(_ct)
setResult(data.response)
console.log(breachCount)
}
} catch (error) {
console.error('Error fetching data:', error)
}
}
}
const [isStrong, initRobustPassword] = useState(null)
const initPwdInput = async (childData) => {
initRobustPassword(childData)
}
const [breachCount, setCount] = useState(null)
return (
<CRow>
<CCol lg={12}>
<CCard className={'mb-4'}>
<CCardHeader>Quick Check</CCardHeader>
<CCardBody>
<CForm>
<CInputGroup className="mb-3">
<CFormInput
placeholder="Enter Your Password"
type="password"
value={password}
onChange={handlePasswordChange}
/>
</CInputGroup>
<PasswordStrengthChecker password={password} actions={initPwdInput} />
<CButton color="success" onClick={handleSubmitCheck}>
Check
</CButton>
</CForm>
{/* Conditional rendering for results */}
{breachCount !== null && (
<h2 style={{ margin: '12px 0' }}>
The Password has been breached {breachCount.toLocaleString()} times
</h2>
)} {result && result.length > 0 ? (
<div>
<table className="table table-striped table-responsive table-bordered mt-3">
<thead>
<tr>
<th style={{ padding: '10px' }}>Breach Name</th>
<th style={{ padding: '10px' }}>Breach Date</th>
{/* Add more table headers if needed */}
</tr>
</thead>
<tbody>
{result.map((breach) => (
<tr key={breach.Name}>
<td style={{ padding: '10px' }}>{breach.Name}</td>
<td style={{ padding: '10px' }}>{breach.BreachDate}</td>
{/* Add more table cells if needed */}
</tr>
))}
</tbody>
</table>
</div>
) : result && result.length === 0 ? (
<h4 className={'mt-3'}>No breach detected for the provided password</h4>
) : null}
</CCardBody>
</CCard>
<CCard>
<CCardHeader>Monitor Passwords</CCardHeader>
<CCardBody>
{accounts.map((account, index) => (
<CInputGroup key={index} className="mb-3">
<CFormInput
type="password"
placeholder="Add/check Password"
name="password"
value={account.password}
onChange={(e) => handleAccountChange(index, e)}
/>
<CButton
type="button"
color="danger"
variant="outline"
onClick={() => handleRemoveAccount(index)}
>
<CIcon icon={cilTrash} />
</CButton>
</CInputGroup>
))}
<CButton color="primary" className="mb-3" onClick={handleAddAccount}>
<CIcon icon={cilPlus} /> Add Another Account
</CButton>
<CInputGroup className="mb-3">
<CFormInput type="file" id="fileInput" onChange={handleFileChange} accept=".csv" />
</CInputGroup>
<CButton color="secondary" className="mb-3" onClick={handleDownloadTemplate}>
<CIcon icon={cilCloudDownload} /> Download CSV Template
</CButton>
<div className="d-grid gap-2">
<CButton color="info" onClick={handleAddToDatabase}>
Add to Database
</CButton>
</div>
</CCardBody>
</CCard>
</CCol>
</CRow> )
}
export default Breaches