update bugs
This commit is contained in:
@@ -1,21 +1,29 @@
|
||||
import "./App.css";
|
||||
import Layout from "./layout/Layout";
|
||||
import { useUsers } from "./utils/useUsers";
|
||||
import UserTable from "./components/UserTable";
|
||||
import { useEffect } from "react";
|
||||
import { useContext, useEffect } from "react";
|
||||
import { loadTheme } from "./utils/frontendService";
|
||||
import "react-toastify/dist/ReactToastify.css";
|
||||
import { AuthContext } from "./utils/context";
|
||||
|
||||
function App() {
|
||||
const users = useUsers();
|
||||
|
||||
useEffect(() => {
|
||||
loadTheme();
|
||||
}, []);
|
||||
|
||||
const auth = useContext(AuthContext);
|
||||
|
||||
return (
|
||||
<Layout>
|
||||
<UserTable users={users} />
|
||||
{auth ? (
|
||||
<UserTable />
|
||||
) : (
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<h2 className="text-2xl font-bold text-gray-700 dark:text-gray-300">
|
||||
Please log in to view the user table.
|
||||
</h2>
|
||||
</div>
|
||||
)}
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
|
@@ -4,7 +4,11 @@ import LoginCard from "./LoginCard";
|
||||
import { greeting } from "../utils/frontendService";
|
||||
import { changeTheme } from "../utils/frontendService";
|
||||
|
||||
const Header: React.FC = () => {
|
||||
export interface HeaderProps {
|
||||
changeAuth?: (isLoggedIn: boolean) => void;
|
||||
}
|
||||
|
||||
const Header: React.FC<HeaderProps> = ({ changeAuth }) => {
|
||||
const [loginCardVisible, setLoginCardVisible] = useState(false);
|
||||
|
||||
const closeLoginCard = () => {
|
||||
@@ -40,7 +44,7 @@ const Header: React.FC = () => {
|
||||
</ul>
|
||||
</nav>
|
||||
</div>
|
||||
<div>{loginCardVisible && <LoginCard onClose={closeLoginCard} />}</div>
|
||||
<div>{loginCardVisible && <LoginCard changeAuth={changeAuth} onClose={closeLoginCard} />}</div>
|
||||
</header>
|
||||
);
|
||||
};
|
||||
|
@@ -3,9 +3,10 @@ import Cookies from "js-cookie";
|
||||
import { logout, loginUser } from "../utils/userHandler";
|
||||
type LoginCardProps = {
|
||||
onClose: () => void;
|
||||
changeAuth?: (isLoggedIn: boolean) => void;
|
||||
};
|
||||
|
||||
const LoginCard: React.FC<LoginCardProps> = ({ onClose }) => {
|
||||
const LoginCard: React.FC<LoginCardProps> = ({ onClose, changeAuth }) => {
|
||||
return (
|
||||
<div className="fixed inset-0 flex items-center justify-center bg-black/35">
|
||||
<div className="max-w-sm bg-white dark:bg-gray-900 rounded-xl shadow-md p-8 relative">
|
||||
@@ -26,6 +27,10 @@ const LoginCard: React.FC<LoginCardProps> = ({ onClose }) => {
|
||||
const username = formData.get("username");
|
||||
const password = formData.get("password");
|
||||
loginUser(username as string, password as string);
|
||||
if (changeAuth) {
|
||||
changeAuth(true);
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
className="space-y-4 text-black dark:text-white"
|
||||
>
|
||||
@@ -69,10 +74,16 @@ const LoginCard: React.FC<LoginCardProps> = ({ onClose }) => {
|
||||
/>
|
||||
)}
|
||||
</form>
|
||||
{Cookies.get("name") ? (
|
||||
{Cookies.get("token") ? (
|
||||
<button
|
||||
className="w-full bg-black dark:bg-gray-800 text-white font-semibold py-2 rounded-md hover:bg-green-400 dark:hover:bg-green-600 transition"
|
||||
onClick={logout}
|
||||
onClick={() => {
|
||||
logout();
|
||||
if (changeAuth) {
|
||||
changeAuth(false);
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
>
|
||||
Logout
|
||||
</button>
|
||||
|
@@ -1,6 +1,7 @@
|
||||
import { MoreVertical } from "lucide-react";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { deleteUser, updateUserFunc } from "../utils/userHandler.ts";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import { useUsers } from "../utils/useUsers.ts";
|
||||
import { AuthContext } from "../utils/context.tsx";
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
@@ -13,27 +14,39 @@ interface User {
|
||||
role: string;
|
||||
}
|
||||
|
||||
interface UserTableProps {
|
||||
users: User[];
|
||||
}
|
||||
|
||||
const UserTable: React.FC<UserTableProps> = ({ users }) => {
|
||||
const UserTable = () => {
|
||||
const [openMenu, setOpenMenu] = useState<number | null>(null);
|
||||
const [userList, setUserList] = useState<User[]>(users);
|
||||
|
||||
const {
|
||||
users,
|
||||
refresh: refreshUsers,
|
||||
setUsers,
|
||||
deleteUser,
|
||||
updateUser: updateUserFunc,
|
||||
} = useUsers();
|
||||
|
||||
const refresh = () => {
|
||||
refreshUsers();
|
||||
};
|
||||
|
||||
const auth = useContext(AuthContext);
|
||||
|
||||
useEffect(() => {
|
||||
setUserList(users);
|
||||
}, [users]);
|
||||
refresh();
|
||||
}, [auth]);
|
||||
|
||||
const handleMenuClick = (userId: number) => {
|
||||
setOpenMenu(openMenu === userId ? null : userId);
|
||||
};
|
||||
|
||||
|
||||
const handleMenuClose = () => setOpenMenu(null);
|
||||
|
||||
const handleInputChange = (id: number, field: keyof User, value: string) => {
|
||||
setUserList((prev) =>
|
||||
prev.map((user) => (user.id === id ? { ...user, [field]: value } : user))
|
||||
setUsers((prevUsers) =>
|
||||
prevUsers.map((user) =>
|
||||
user.id === id ? { ...user, [field]: value } : user
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
@@ -71,9 +84,9 @@ const UserTable: React.FC<UserTableProps> = ({ users }) => {
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="bg-white text-black dark:bg-gray-900 dark:text-white divide-y divide-gray-100 dark:divide-gray-800 z-10">
|
||||
{userList.map((user, idx) => {
|
||||
{(users ?? []).map((user, idx) => {
|
||||
// If this is one of the last 2 rows, open menu upwards
|
||||
const openUp = idx >= userList.length - 2;
|
||||
const openUp = idx >= users.length - 2;
|
||||
return (
|
||||
<tr
|
||||
key={user.id}
|
||||
|
@@ -1,31 +1,44 @@
|
||||
import React from "react";
|
||||
import React, { useEffect } from "react";
|
||||
import Header from "../components/Header";
|
||||
import Cookies from "js-cookie";
|
||||
import Sidebar from "../components/Sidebar";
|
||||
import { ToastContainer } from "react-toastify";
|
||||
import { AuthContext } from "../utils/context";
|
||||
|
||||
type LayoutProps = {
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
const Layout: React.FC<LayoutProps> = ({ children }) => {
|
||||
const isLoggedIn = !!Cookies.get("name");
|
||||
const [loggedIn, setLoggedIn] = React.useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const token = Cookies.get("token");
|
||||
if (token) {
|
||||
setLoggedIn(true);
|
||||
} else {
|
||||
setLoggedIn(false);
|
||||
}
|
||||
}, [loggedIn]);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col min-h-screen bg-gradient-to-br from-blue-50 via-blue-100 to-blue-200 dark:from-gray-900 dark:via-gray-950 dark:to-gray-900">
|
||||
<Header />
|
||||
<Header changeAuth={
|
||||
(isLoggedIn: boolean) => setLoggedIn(isLoggedIn)
|
||||
} />
|
||||
<ToastContainer />
|
||||
<div className="flex flex-1">
|
||||
{isLoggedIn && (
|
||||
<>
|
||||
{/* Sidebar */}
|
||||
<Sidebar />
|
||||
{/* Main content */}
|
||||
<main className="flex-1 p-10 bg-white/80 dark:bg-gray-900/80 rounded-l-3xl shadow-2xl m-6 overflow-auto text-black dark:text-white">
|
||||
{children}
|
||||
</main>
|
||||
</>
|
||||
)}
|
||||
<AuthContext.Provider value={loggedIn}>
|
||||
{/* Main content */}
|
||||
{loggedIn && (
|
||||
<>
|
||||
<Sidebar />
|
||||
<main className="flex-1 p-10 bg-white/80 dark:bg-gray-900/80 rounded-l-3xl shadow-2xl m-6 overflow-auto text-black dark:text-white">
|
||||
{children}
|
||||
</main>
|
||||
</>
|
||||
)}
|
||||
</AuthContext.Provider>
|
||||
</div>
|
||||
<footer className="bg-gradient-to-r from-blue-800 via-blue-900 to-blue-800 dark:from-gray-900 dark:via-gray-950 dark:to-gray-900 text-blue-100 dark:text-gray-400 py-6 px-5 text-center rounded-t-3xl shadow-xl mt-8 tracking-wide border-t border-blue-700 dark:border-gray-800">
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
|
3
frontend_admin/src/utils/context.tsx
Normal file
3
frontend_admin/src/utils/context.tsx
Normal file
@@ -0,0 +1,3 @@
|
||||
import { createContext } from 'react';
|
||||
|
||||
export const AuthContext = createContext(false);
|
@@ -1,4 +1,6 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useState, type Dispatch, type SetStateAction } from "react";
|
||||
import Cookies from "js-cookie";
|
||||
import { myToast } from "./frontendService";
|
||||
|
||||
export interface User {
|
||||
id: number;
|
||||
@@ -11,20 +13,141 @@ export interface User {
|
||||
role: string;
|
||||
}
|
||||
|
||||
export function useUsers(): User[] {
|
||||
export type UserReturn = {
|
||||
users: User[];
|
||||
refresh: () => void;
|
||||
setUsers: Dispatch<SetStateAction<User[]>>;
|
||||
deleteUser: (id: number) => void;
|
||||
updateUser: (id: number) => void;
|
||||
};
|
||||
|
||||
export function useUsers(): UserReturn {
|
||||
const [users, setUsers] = useState<User[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const data = localStorage.getItem("users");
|
||||
if (data) {
|
||||
try {
|
||||
const parsed = JSON.parse(data);
|
||||
setUsers(parsed.result || []);
|
||||
} catch {
|
||||
setUsers([]);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
const token = Cookies.get("token");
|
||||
|
||||
return users;
|
||||
const headers = {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${token}`,
|
||||
};
|
||||
|
||||
const fetchUsers = async () => {
|
||||
try {
|
||||
const response = await fetch("http://localhost:5002/api/getAllUsers", {
|
||||
method: "GET",
|
||||
headers: headers,
|
||||
});
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
setUsers(data.result);
|
||||
myToast("Users fetched successfully", "success");
|
||||
} else {
|
||||
console.error("Failed to fetch users");
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching users:", error);
|
||||
}
|
||||
}
|
||||
|
||||
const deleteUser = (id: number) => {
|
||||
fetch("http://localhost:5002/api/deleteUser", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ id: id }),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||
},
|
||||
})
|
||||
.then((response) => {
|
||||
if (response.ok) {
|
||||
setUsers((prevUsers) => prevUsers.filter((user) => user.id !== id));
|
||||
myToast("User deleted successfully", "success");
|
||||
} else {
|
||||
alert("Failed to delete user");
|
||||
}
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log("Error deleting user: ", error);
|
||||
});
|
||||
};
|
||||
|
||||
const updateUserFunc = async (userID: number) => {
|
||||
console.log("UpdateFunc" + userID);
|
||||
|
||||
// Validate that required DOM elements exist
|
||||
const usernameEl = document.getElementById(
|
||||
`username-${userID}`
|
||||
) as HTMLInputElement;
|
||||
const firstNameEl = document.getElementById(
|
||||
`first_name-${userID}`
|
||||
) as HTMLInputElement;
|
||||
const lastNameEl = document.getElementById(
|
||||
`last_name-${userID}`
|
||||
) as HTMLInputElement;
|
||||
const emailEl = document.getElementById(
|
||||
`email-${userID}`
|
||||
) as HTMLInputElement;
|
||||
const passwordEl = document.getElementById(
|
||||
`password-${userID}`
|
||||
) as HTMLInputElement;
|
||||
|
||||
if (!usernameEl || !firstNameEl || !lastNameEl || !emailEl) {
|
||||
console.error("Required form elements not found");
|
||||
alert("Form elements not found");
|
||||
return;
|
||||
}
|
||||
|
||||
const userData = {
|
||||
id: userID,
|
||||
username: usernameEl.value,
|
||||
first_name: firstNameEl.value,
|
||||
last_name: lastNameEl.value,
|
||||
email: emailEl.value,
|
||||
password: passwordEl?.value || "", // password might be optional
|
||||
};
|
||||
|
||||
console.log("Sending user data:", userData);
|
||||
|
||||
try {
|
||||
const response = await fetch("http://localhost:5002/api/updateUser", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(userData),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||
},
|
||||
});
|
||||
|
||||
console.log("Response status:", response.status);
|
||||
console.log("Response ok:", response.ok);
|
||||
|
||||
if (response.ok) {
|
||||
console.log("User updated successfully");
|
||||
setUsers((prevUsers) =>
|
||||
prevUsers.map((user) =>
|
||||
user.id === userID ? { ...user, ...userData } : user
|
||||
)
|
||||
);
|
||||
|
||||
myToast("User updated successfully", "success");
|
||||
} else {
|
||||
const errorText = await response.text();
|
||||
console.error("Server error:", response.status, errorText);
|
||||
alert(`Failed to update user: ${response.status} - ${errorText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Network error updating user:", error);
|
||||
alert("Network error occurred while updating user");
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
return {
|
||||
users: users,
|
||||
setUsers: setUsers,
|
||||
refresh: () => fetchUsers(),
|
||||
deleteUser: (id: number) => deleteUser(id),
|
||||
updateUser: (id: number) => updateUserFunc(id),
|
||||
}
|
||||
}
|
||||
|
@@ -12,16 +12,6 @@ export const loginUser = (username: string, password: string) => {
|
||||
const data = await response.json();
|
||||
Cookies.set("token", data.token, { expires: 7 });
|
||||
Cookies.set("name", data.user.first_name, { expires: 7 });
|
||||
await fetch("http://localhost:5002/api/getAllUsers", {
|
||||
method: "GET",
|
||||
headers: {
|
||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||
},
|
||||
})
|
||||
.then((res) => res.json())
|
||||
.then((users) => {
|
||||
localStorage.setItem("users", JSON.stringify(users));
|
||||
});
|
||||
myToast("Logged in successfully!", "success");
|
||||
} else if (response.status === 401) {
|
||||
myToast("Invalid username or password!", "error");
|
||||
|
6
package-lock.json
generated
Normal file
6
package-lock.json
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"name": "bikelane",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {}
|
||||
}
|
Reference in New Issue
Block a user