Skip to content

Commit

Permalink
Merge pull request #10 from midas1214/main
Browse files Browse the repository at this point in the history
implement UI for the four pages, download and upload
  • Loading branch information
Te99y authored Nov 10, 2024
2 parents 07b1bef + 4b5023a commit 861d248
Show file tree
Hide file tree
Showing 12 changed files with 773 additions and 77 deletions.
File renamed without changes.
41 changes: 41 additions & 0 deletions frontend/src/assets/css/login.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
.login-block {
max-width: 300px;
margin: 20px auto;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
background-color: #f9f9f9;
text-align: center;
}

.login-block input {
width: 100%;
padding: 10px;
margin: 10px -10px;
border: 1px solid #ccc;
border-radius: 5px;
}

.button-group {
display: flex;
justify-content: space-between;
}

.button-group button {
width: 45%;
padding: 10px;
background-color: #61dafb;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
}

.button-group button:hover {
background-color: #21a1f1;
}

.error {
color: red;
margin-top: 10px;
}
File renamed without changes.
56 changes: 37 additions & 19 deletions frontend/src/pages/login.tsx → frontend/src/components/login.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// src/login.tsx
import React, { useState } from 'react';
import './login.css'; // Optional: For styling
import '../assets/css/login.css'; // Optional: For styling

interface AuthForm {
username: string;
Expand All @@ -18,36 +18,54 @@ const Login: React.FC = () => {
setFormData({ ...formData, [name]: value });
};

// Handle login with GET request to /user/login
// Handle login with PUT request to /authenticate
const handleLogin = async () => {
setError(null); // Reset any previous errors
try {
console.log('Attempting login with:', formData);

// Create query parameters
const queryParams = new URLSearchParams({
username: formData.username,
password: formData.password,
});
// Prepare the request body
const requestBody = {
User: {
name: formData.username,
isAdmin: false, // Adjust this if needed based on your logic
},
Secret: {
password: formData.password,
},
};

const response = await fetch(`http://localhost:5000/user/login?${queryParams}`, {
method: 'GET',
});
// const response = await fetch('http://localhost:5000/authenticate', {
// method: 'PUT',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify(requestBody),
// });

if (response.ok) {
const { token } = await response.json();
if (true) {
const token = "bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c";
// if (response.status === 200) {
// const { token } = await response.json();
alert('Login successful!');
setIsLoggedIn(true);
localStorage.setItem('authToken', token); // Store the token
} else {
const errorData = await response.json();
setError(errorData.message || 'Failed to login.');
localStorage.setItem('authToken', token); // Store the token for future use
// } else if (response.status === 400) {
// setError('Missing fields or improperly formed request.');
// } else if (response.status === 401) {
// setError('Invalid username or password.');
// } else if (response.status === 501) {
// setError('Authentication not supported by the system.');
// } else {
// setError('Failed to login due to an unknown error.');
}
} catch (err) {
console.error('Error during login:', err);
setError('Network error. Please try again later.');
}
};

// Handle sign-up with POST request to /user
// Handle sign-up logic (kept as-is)
const handleSignUp = async () => {
try {
console.log('Attempting sign-up with:', formData);
Expand All @@ -72,7 +90,7 @@ const Login: React.FC = () => {
}
};

// Handle logout with GET request to /logout
// Handle logout logic (kept as-is)
const handleLogout = async () => {
try {
console.log('Attempting logout...');
Expand Down Expand Up @@ -103,7 +121,7 @@ const Login: React.FC = () => {
</div>
) : (
<form onSubmit={(e) => e.preventDefault()}>
<h2>User Login / Sign Up</h2>
<h2>User Login</h2>
<div>
<input
type="text"
Expand Down
132 changes: 132 additions & 0 deletions frontend/src/components/searchByName.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
import React, { useState, useEffect } from 'react';

interface PackageMetadata {
ID: string;
Name: string;
Version: string;
}

const SearchByName: React.FC = () => {
const [packageName, setPackageName] = useState('');
const [results, setResults] = useState<PackageMetadata[]>([]);
const [authToken, setAuthToken] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [offset, setOffset] = useState<number>(0);

// Retrieve auth token from localStorage on component mount
useEffect(() => {
const token = localStorage.getItem('authToken');
if (token) {
setAuthToken(token);
} else {
alert('Authentication token not found. Please log in.');
}
}, []);

const handleSearch = async (e: React.FormEvent) => {
e.preventDefault();
setError(null);

if (!authToken) {
alert('Authentication token is missing. Please log in.');
return;
}

try {
const requestBody = [{ Name: packageName }];

// const response = await fetch(`/packages?offset=${offset}`, {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// 'X-Authorization': authToken,
// },
// body: JSON.stringify(requestBody),
// });

const response1 = JSON.stringify({
status: 200,
data: [
{
packageName: 'example-package',
version: '1.0.0',
description: 'Sample description for testing purposes.',
fileUrl: 'https://example.com/uploads/example-package-v1.0.0.zip',
uploadDate: '2024-11-03T14:30:00Z',
debloatEnabled: true,
},
{
packageName: 'another-package',
version: '2.0.1',
description: 'Another example package for testing.',
fileUrl: 'https://example.com/uploads/another-package-v2.0.1.zip',
uploadDate: '2024-11-02T10:15:00Z',
debloatEnabled: false,
},
],
headers: {
offset: '10',
},
});

// Parse the response as JSON
const response = JSON.parse(response1);

if (response.status === 200) {
const data: PackageMetadata[] = await response.json();
setResults(data);
const newOffset = parseInt(response.headers.get('offset') || '0', 10);
setOffset(newOffset);
} else if (response.status === 400) {
setError('Search failed: Missing fields or invalid query.');
} else if (response.status === 403) {
setError('Search failed: Authentication failed due to invalid or missing AuthenticationToken.');
} else if (response.status === 413) {
setError('Search failed: Too many packages returned.');
} else {
setError('Search failed with an unknown error.');
}
} catch (err) {
console.error('Error during search:', err);
setError('An error occurred while searching for packages.');
}
};

return (
<div style={{ maxWidth: '600px', margin: '0 auto', padding: '20px' }}>
<h2>Search for Packages</h2>
<form onSubmit={handleSearch}>
<label>
Package Name:
<input
type="text"
value={packageName}
onChange={(e) => setPackageName(e.target.value)}
required
style={{ width: '100%', padding: '8px', margin: '10px 0' }}
/>
</label>
<button type="submit" style={{ padding: '10px 20px', backgroundColor: '#007bff', color: '#fff', border: 'none', cursor: 'pointer' }}>
Search
</button>
</form>

{error && <p style={{ color: 'red' }}>{error}</p>}

{results.length > 0 && (
<div style={{ marginTop: '20px' }}>
<h3>Search Results</h3>
<ul>
{results.map((pkg) => (
<li key={pkg.ID}>
<strong>Name:</strong> {pkg.Name} | <strong>Version:</strong> {pkg.Version} | <strong>ID:</strong> {pkg.ID}
</li>
))}
</ul>
</div>
)}
</div>
);
};

export default SearchByName;
Loading

0 comments on commit 861d248

Please sign in to comment.