Compare commits
3 Commits
debian12ne
...
manualRelo
Author | SHA1 | Date | |
---|---|---|---|
6a8d13b69b | |||
7abed30091 | |||
850c475329 |
110
backend/routes/api.js
Normal file
110
backend/routes/api.js
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
import express from "express";
|
||||||
|
import {
|
||||||
|
loginUser,
|
||||||
|
createUser,
|
||||||
|
updateUser,
|
||||||
|
deleteUser,
|
||||||
|
getAllUsers,
|
||||||
|
} from "../services/database.js";
|
||||||
|
import { generateToken, authenticate } from "../services/tokenService.js";
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.post("/login", async (req, res) => {
|
||||||
|
try {
|
||||||
|
const result = await loginUser(req.body.username, req.body.password);
|
||||||
|
if (result.success && result.user.role === "admin") {
|
||||||
|
const userToken = await generateToken({
|
||||||
|
role: result.user.role,
|
||||||
|
username: result.user.username,
|
||||||
|
});
|
||||||
|
console.log("User token generated: ", userToken);
|
||||||
|
res.status(200).json({
|
||||||
|
success: true,
|
||||||
|
message: "Login successful",
|
||||||
|
token: userToken,
|
||||||
|
...result,
|
||||||
|
});
|
||||||
|
} else if (result.success && result.user.role === "user") {
|
||||||
|
res.status(403).json(result, { message: "You are not an Admin!" }); // Event Handler is in LoginCard.tsx - there is defined what happens when the status is 403
|
||||||
|
} else {
|
||||||
|
res.status(401).json(result, { message: "Invalid credentials" }); // Event Handler is in LoginCard.tsx - there is defined what happens when the status is 401
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
console.error("Error logging in:", err);
|
||||||
|
res.status(500).json({ success: false, message: "Internal server error" });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get("/getAllUsers", authenticate, async (req, res) => {
|
||||||
|
if (req.user.role === "admin") {
|
||||||
|
getAllUsers()
|
||||||
|
.then((users) => {
|
||||||
|
res.status(200).json(users);
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error("Error fetching users:", err);
|
||||||
|
res
|
||||||
|
.status(500)
|
||||||
|
.json({ success: false, message: "Internal server error" });
|
||||||
|
});
|
||||||
|
console.log("Fetched all users successfully");
|
||||||
|
} else if (req.user.role === "user") {
|
||||||
|
res.status(403).json({ success: false, message: "Access denied" });
|
||||||
|
console.log("Access denied for user role");
|
||||||
|
} else {
|
||||||
|
res.status(500).json({ success: false, message: "Server error" });
|
||||||
|
console.log("Server error while fetching users");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/deleteUser", authenticate, async (req, res) => {
|
||||||
|
if (req.user.role === "admin") {
|
||||||
|
deleteUser(req.body.id)
|
||||||
|
.then((result) => {
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json(result);
|
||||||
|
} else {
|
||||||
|
throw new Error("Failed to delete user");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error("Error deleting user:", err);
|
||||||
|
res
|
||||||
|
.status(500)
|
||||||
|
.json({ success: false, message: "Internal server error" });
|
||||||
|
});
|
||||||
|
console.log("User deleted successfully");
|
||||||
|
} else {
|
||||||
|
console.log("Access denied for user role");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
router.post("/updateUser", authenticate, async (req, res) => {
|
||||||
|
if (req.user.role === "admin") {
|
||||||
|
updateUser(
|
||||||
|
req.body.username,
|
||||||
|
req.body.first_name,
|
||||||
|
req.body.last_name,
|
||||||
|
req.body.password,
|
||||||
|
req.body.email,
|
||||||
|
req.body.id
|
||||||
|
)
|
||||||
|
.then((result) => {
|
||||||
|
if (result.success) {
|
||||||
|
res.status(200).json(result);
|
||||||
|
} else {
|
||||||
|
throw new Error("Failed to update user");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((err) => {
|
||||||
|
console.error("Error updating user:", err);
|
||||||
|
res
|
||||||
|
.status(500)
|
||||||
|
.json({ success: false, message: "Internal server error" });
|
||||||
|
});
|
||||||
|
console.log("User updated successfully");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
export default router;
|
@@ -3,15 +3,8 @@ import express from "express";
|
|||||||
import cors from "cors";
|
import cors from "cors";
|
||||||
const app = express();
|
const app = express();
|
||||||
const port = 5002;
|
const port = 5002;
|
||||||
import {
|
|
||||||
loginUser,
|
|
||||||
createUser,
|
|
||||||
updateUser,
|
|
||||||
deleteUser,
|
|
||||||
getAllUsers,
|
|
||||||
} from "./services/database.js";
|
|
||||||
import { generateToken, authenticate } from "./services/tokenService.js";
|
|
||||||
import cookieParser from "cookie-parser";
|
import cookieParser from "cookie-parser";
|
||||||
|
import router from "./routes/api.js";
|
||||||
|
|
||||||
//view engine ejs
|
//view engine ejs
|
||||||
app.set("view engine", "ejs");
|
app.set("view engine", "ejs");
|
||||||
@@ -20,105 +13,10 @@ app.use(express.json());
|
|||||||
app.use(cors());
|
app.use(cors());
|
||||||
app.use(cookieParser());
|
app.use(cookieParser());
|
||||||
|
|
||||||
app.post("/api/login", async (req, res) => {
|
app.use("/api", router);
|
||||||
try {
|
|
||||||
const result = await loginUser(req.body.username, req.body.password);
|
|
||||||
if (result.success && result.user.role === "admin") {
|
|
||||||
const userToken = await generateToken({
|
|
||||||
role: result.user.role,
|
|
||||||
username: result.user.username,
|
|
||||||
});
|
|
||||||
console.log("User token generated: ", userToken);
|
|
||||||
res.status(200).json({
|
|
||||||
success: true,
|
|
||||||
message: "Login successful",
|
|
||||||
token: userToken,
|
|
||||||
...result,
|
|
||||||
});
|
|
||||||
} else if (result.success && result.user.role === "user") {
|
|
||||||
res.status(403).json(result, { message: "You are not an Admin!" }); // Event Handler is in LoginCard.tsx - there is defined what happens when the status is 403
|
|
||||||
} else {
|
|
||||||
res.status(401).json(result, { message: "Invalid credentials" }); // Event Handler is in LoginCard.tsx - there is defined what happens when the status is 401
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
console.error("Error logging in:", err);
|
|
||||||
res.status(500).json({ success: false, message: "Internal server error" });
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.get("/api/getAllUsers", authenticate, async (req, res) => {
|
|
||||||
if (req.user.role === "admin") {
|
|
||||||
getAllUsers()
|
|
||||||
.then((users) => {
|
|
||||||
res.status(200).json(users);
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
console.error("Error fetching users:", err);
|
|
||||||
res
|
|
||||||
.status(500)
|
|
||||||
.json({ success: false, message: "Internal server error" });
|
|
||||||
});
|
|
||||||
console.log("Fetched all users successfully");
|
|
||||||
} else if (req.user.role === "user") {
|
|
||||||
res.status(403).json({ success: false, message: "Access denied" });
|
|
||||||
console.log("Access denied for user role");
|
|
||||||
} else {
|
|
||||||
res.status(500).json({ success: false, message: "Server error" });
|
|
||||||
console.log("Server error while fetching users");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.post("/api/deleteUser", authenticate, async (req, res) => {
|
|
||||||
if (req.user.role === "admin") {
|
|
||||||
deleteUser(req.body.id)
|
|
||||||
.then((result) => {
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json(result);
|
|
||||||
} else {
|
|
||||||
throw new Error("Failed to delete user");
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
console.error("Error deleting user:", err);
|
|
||||||
res
|
|
||||||
.status(500)
|
|
||||||
.json({ success: false, message: "Internal server error" });
|
|
||||||
});
|
|
||||||
console.log("User deleted successfully");
|
|
||||||
} else {
|
|
||||||
console.log("Access denied for user role");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.post("/api/updateUser", authenticate, async (req, res) => {
|
|
||||||
if (req.user.role === "admin") {
|
|
||||||
updateUser(
|
|
||||||
req.body.username,
|
|
||||||
req.body.first_name,
|
|
||||||
req.body.last_name,
|
|
||||||
req.body.password,
|
|
||||||
req.body.email,
|
|
||||||
req.body.id
|
|
||||||
)
|
|
||||||
.then((result) => {
|
|
||||||
if (result.success) {
|
|
||||||
res.status(200).json(result);
|
|
||||||
} else {
|
|
||||||
throw new Error("Failed to update user");
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
console.error("Error updating user:", err);
|
|
||||||
res
|
|
||||||
.status(500)
|
|
||||||
.json({ success: false, message: "Internal server error" });
|
|
||||||
});
|
|
||||||
console.log("User updated successfully");
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
app.listen(port, () => {
|
app.listen(port, () => {
|
||||||
console.log(`Express backend server is running at Port: ${port}`);
|
console.log(`Express backend server is running at http://localhost:${port}`);
|
||||||
});
|
});
|
||||||
|
|
||||||
// error handling code
|
// error handling code
|
||||||
|
@@ -1,42 +1,33 @@
|
|||||||
services:
|
services:
|
||||||
admin_react-frontend:
|
# admin_react-frontend:
|
||||||
container_name: bikelane-frontend_react-admin
|
# container_name: bikelane-frontend_react-admin
|
||||||
build: ./frontend_admin
|
# build: ./frontend_admin
|
||||||
ports:
|
# ports:
|
||||||
- "5001:5001"
|
# - "5001:5001"
|
||||||
networks:
|
# environment:
|
||||||
- proxynet
|
# - CHOKIDAR_USEPOLLING=true
|
||||||
- bikelane_network
|
# volumes:
|
||||||
environment:
|
# - ./frontend_admin:/app
|
||||||
- CHOKIDAR_USEPOLLING=true
|
# - /app/node_modules
|
||||||
volumes:
|
# restart: unless-stopped
|
||||||
- ./frontend_admin:/app
|
|
||||||
- /app/node_modules
|
|
||||||
restart: unless-stopped
|
|
||||||
|
|
||||||
user_react-frontend:
|
# user_react-frontend:
|
||||||
container_name: bikelane-frontend_react-user
|
# container_name: bikelane-frontend_react-user
|
||||||
build: ./frontend_user
|
# build: ./frontend_user
|
||||||
networks:
|
# ports:
|
||||||
- proxynet
|
# - "5003:5003"
|
||||||
- bikelane_network
|
# environment:
|
||||||
ports:
|
# - CHOKIDAR_USEPOLLING=true
|
||||||
- "5003:5003"
|
# volumes:
|
||||||
environment:
|
# - ./frontend_user:/app
|
||||||
- CHOKIDAR_USEPOLLING=true
|
# - /app/node_modules
|
||||||
volumes:
|
# restart: unless-stopped
|
||||||
- ./frontend_user:/app
|
|
||||||
- /app/node_modules
|
|
||||||
restart: unless-stopped
|
|
||||||
|
|
||||||
bikelane-backend:
|
bikelane-backend:
|
||||||
container_name: bikelane-backend_express
|
container_name: bikelane-backend_express
|
||||||
build: ./backend
|
build: ./backend
|
||||||
ports:
|
ports:
|
||||||
- "5002:5002"
|
- "5002:5002"
|
||||||
networks:
|
|
||||||
- proxynet
|
|
||||||
- bikelane_network
|
|
||||||
environment:
|
environment:
|
||||||
DB_HOST: mysql
|
DB_HOST: mysql
|
||||||
DB_USER: root
|
DB_USER: root
|
||||||
@@ -52,8 +43,6 @@ services:
|
|||||||
container_name: bikelane-mysql
|
container_name: bikelane-mysql
|
||||||
image: mysql:8.0
|
image: mysql:8.0
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
networks:
|
|
||||||
- bikelane_network
|
|
||||||
environment:
|
environment:
|
||||||
MYSQL_ROOT_PASSWORD: D7Ze0lwV9hMrNQHdz1Q8yi0MIQuOO8
|
MYSQL_ROOT_PASSWORD: D7Ze0lwV9hMrNQHdz1Q8yi0MIQuOO8
|
||||||
MYSQL_DATABASE: bikelane
|
MYSQL_DATABASE: bikelane
|
||||||
@@ -64,9 +53,3 @@ services:
|
|||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
mysql-data:
|
mysql-data:
|
||||||
|
|
||||||
networks:
|
|
||||||
proxynet:
|
|
||||||
external: true
|
|
||||||
bikelane_network:
|
|
||||||
external: false
|
|
||||||
|
1
frontend_admin/.env
Normal file
1
frontend_admin/.env
Normal file
@@ -0,0 +1 @@
|
|||||||
|
REACT_APP_SERVER_URL=http://localhost:5002
|
@@ -1,13 +1,12 @@
|
|||||||
# Build Stage
|
FROM node:20-alpine
|
||||||
FROM node:20-alpine AS build
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm install
|
RUN npm install
|
||||||
COPY . .
|
|
||||||
RUN npm run build
|
|
||||||
|
|
||||||
# Production Stage
|
COPY . .
|
||||||
FROM nginx:stable-alpine AS production
|
|
||||||
COPY --from=build /app/build /usr/share/nginx/html
|
|
||||||
EXPOSE 5001
|
EXPOSE 5001
|
||||||
CMD ["nginx", "-g", "daemon off;"]
|
|
||||||
|
CMD ["npm", "start"]
|
||||||
|
67
frontend_admin/other/App copy.tsx
Normal file
67
frontend_admin/other/App copy.tsx
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
import React, { useState } from "react";
|
||||||
|
import "./App.css";
|
||||||
|
import Header from "./Header";
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const [username, setUsername] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
|
||||||
|
const handleSubmit = async (e: React.FormEvent) => {
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("http://localhost:5002/api/login", {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
username,
|
||||||
|
password,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.ok) {
|
||||||
|
console.log("Login successful");
|
||||||
|
// Handle successful login here
|
||||||
|
} else {
|
||||||
|
console.log("Login failed");
|
||||||
|
// Handle login error here
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Login error:", error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<form onSubmit={handleSubmit}>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="username">Username:</label>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
id="username"
|
||||||
|
name="username"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label htmlFor="password">Password:</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
id="password"
|
||||||
|
name="password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<button type="submit">Login</button>
|
||||||
|
</form>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
30
frontend_admin/other/App.tsx
Normal file
30
frontend_admin/other/App.tsx
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
import React, { useState } from "react";
|
||||||
|
import Header from "./components/Header";
|
||||||
|
import LoginCard from "./components/LoginCard";
|
||||||
|
|
||||||
|
function App() {
|
||||||
|
const [showLogin, setShowLogin] = useState(false);
|
||||||
|
|
||||||
|
const handleLoginClick = () => setShowLogin(true);
|
||||||
|
const handleCloseLogin = () => setShowLogin(false);
|
||||||
|
|
||||||
|
const handleLoginSubmit = (username: string, password: string) => {
|
||||||
|
// Hier kannst du fetch einbauen
|
||||||
|
alert(`Login: ${username} / ${password}`);
|
||||||
|
setShowLogin(false);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen bg-white">
|
||||||
|
<Header onLoginClick={handleLoginClick} />
|
||||||
|
<main className="pt-20 w-full h-full flex flex-col items-center justify-start">
|
||||||
|
{/* Hier kommt später der Seiteninhalt */}
|
||||||
|
{showLogin && (
|
||||||
|
<LoginCard onClose={handleCloseLogin} onSubmit={handleLoginSubmit} />
|
||||||
|
)}
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default App;
|
29
frontend_admin/other/components/Header.tsx
Normal file
29
frontend_admin/other/components/Header.tsx
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
import React from "react";
|
||||||
|
import bike from "../../src/assets/bicycle-solid.svg";
|
||||||
|
import user from "../../src/assets/circle-user-solid.svg";
|
||||||
|
|
||||||
|
type HeaderProps = {
|
||||||
|
onLoginClick: () => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const Header: React.FC<HeaderProps> = ({ onLoginClick }) => (
|
||||||
|
<header className="fixed top-0 left-0 w-full h-20 bg-[#101c5e] flex items-center justify-between px-10 z-50 shadow">
|
||||||
|
<div className="flex items-center gap-3">
|
||||||
|
<img src={bike} alt="Bike Logo" className="h-10 w-10" />
|
||||||
|
<span className="text-white text-2xl font-semibold select-none">
|
||||||
|
Bikelane <b>Web</b>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-4">
|
||||||
|
<img src={user} alt="User Icon" className="h-8 w-8" />
|
||||||
|
<button
|
||||||
|
onClick={onLoginClick}
|
||||||
|
className="bg-white text-[#101c5e] font-bold px-5 py-1 rounded-lg text-lg border-2 border-white hover:bg-gray-200 transition"
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
|
||||||
|
export default Header;
|
72
frontend_admin/other/components/LoginCard.tsx
Normal file
72
frontend_admin/other/components/LoginCard.tsx
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
import React, { useRef, useEffect } from "react";
|
||||||
|
|
||||||
|
type LoginCardProps = {
|
||||||
|
onClose: () => void;
|
||||||
|
onSubmit: (username: string, password: string) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const LoginCard: React.FC<LoginCardProps> = ({ onClose, onSubmit }) => {
|
||||||
|
const [username, setUsername] = React.useState("");
|
||||||
|
const [password, setPassword] = React.useState("");
|
||||||
|
const cardRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const handler = (e: MouseEvent) => {
|
||||||
|
if (cardRef.current && !cardRef.current.contains(e.target as Node)) {
|
||||||
|
onClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener("mousedown", handler);
|
||||||
|
return () => document.removeEventListener("mousedown", handler);
|
||||||
|
}, [onClose]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="fixed inset-0 bg-black bg-opacity-30 flex items-center justify-center z-40">
|
||||||
|
<div
|
||||||
|
ref={cardRef}
|
||||||
|
className="bg-gray-200 rounded-xl shadow-lg w-full max-w-md flex flex-col"
|
||||||
|
>
|
||||||
|
<div className="bg-[#101c5e] text-white rounded-t-xl px-8 py-4 text-center text-2xl font-bold">
|
||||||
|
Login
|
||||||
|
</div>
|
||||||
|
<form
|
||||||
|
className="flex flex-col gap-5 px-8 py-6"
|
||||||
|
onSubmit={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
onSubmit(username, password);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<label className="font-bold">
|
||||||
|
username
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
className="mt-2 w-full rounded-full px-5 py-2 bg-gray-400 outline-none"
|
||||||
|
value={username}
|
||||||
|
onChange={(e) => setUsername(e.target.value)}
|
||||||
|
autoFocus
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label className="font-bold">
|
||||||
|
password
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
className="mt-2 w-full rounded-full px-5 py-2 bg-gray-400 outline-none"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="bg-[#101c5e] text-white font-bold rounded-lg py-3 mt-6 text-xl hover:bg-[#203080] transition"
|
||||||
|
>
|
||||||
|
Login
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
export default LoginCard;
|
13
frontend_admin/package-lock.json
generated
13
frontend_admin/package-lock.json
generated
@@ -12,6 +12,7 @@
|
|||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"dotenv": "^17.2.0",
|
||||||
"js-cookie": "^3.0.5",
|
"js-cookie": "^3.0.5",
|
||||||
"lucide-react": "^0.525.0",
|
"lucide-react": "^0.525.0",
|
||||||
"react": "^19.1.0",
|
"react": "^19.1.0",
|
||||||
@@ -2640,6 +2641,18 @@
|
|||||||
"tslib": "^2.0.3"
|
"tslib": "^2.0.3"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/dotenv": {
|
||||||
|
"version": "17.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.0.tgz",
|
||||||
|
"integrity": "sha512-Q4sgBT60gzd0BB0lSyYD3xM4YxrXA9y4uBDof1JNYGzOXrQdQ6yX+7XIAqoFOGQFOTK1D3Hts5OllpxMDZFONQ==",
|
||||||
|
"license": "BSD-2-Clause",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"url": "https://dotenvx.com"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/electron-to-chromium": {
|
"node_modules/electron-to-chromium": {
|
||||||
"version": "1.5.187",
|
"version": "1.5.187",
|
||||||
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.187.tgz",
|
"resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.187.tgz",
|
||||||
|
@@ -15,6 +15,7 @@
|
|||||||
"@tanstack/react-table": "^8.21.3",
|
"@tanstack/react-table": "^8.21.3",
|
||||||
"class-variance-authority": "^0.7.1",
|
"class-variance-authority": "^0.7.1",
|
||||||
"clsx": "^2.1.1",
|
"clsx": "^2.1.1",
|
||||||
|
"dotenv": "^17.2.0",
|
||||||
"js-cookie": "^3.0.5",
|
"js-cookie": "^3.0.5",
|
||||||
"lucide-react": "^0.525.0",
|
"lucide-react": "^0.525.0",
|
||||||
"react": "^19.1.0",
|
"react": "^19.1.0",
|
||||||
|
@@ -1,43 +1,27 @@
|
|||||||
import "./App.css";
|
import "./App.css";
|
||||||
import Layout from "./layout/Layout";
|
import Layout from "./layout/Layout";
|
||||||
|
import { useUsers } from "./utils/useUsers";
|
||||||
import UserTable from "./components/UserTable";
|
import UserTable from "./components/UserTable";
|
||||||
import LoginCard from "./components/LoginCard";
|
import { useEffect } from "react";
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { loadTheme } from "./utils/frontendService";
|
import { loadTheme } from "./utils/frontendService";
|
||||||
|
import { myToast } from "./utils/frontendService";
|
||||||
import "react-toastify/dist/ReactToastify.css";
|
import "react-toastify/dist/ReactToastify.css";
|
||||||
import Cookies from "js-cookie";
|
import Cookies from "js-cookie";
|
||||||
import { AuthContext } from "./utils/context";
|
|
||||||
|
|
||||||
function App() {
|
function App() {
|
||||||
|
const users = useUsers();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
loadTheme();
|
loadTheme();
|
||||||
|
if (Cookies.get("token")) {
|
||||||
|
myToast("User list updated", "success");
|
||||||
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const [isAuthenticated, setIsAuthenticated] = useState(
|
|
||||||
!!Cookies.get("token")
|
|
||||||
);
|
|
||||||
const [, setShowLogin] = useState(false);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<AuthContext.Provider value={{ isAuthenticated, setIsAuthenticated }}>
|
<Layout>
|
||||||
<Layout>
|
<UserTable users={users} />
|
||||||
{isAuthenticated ? (
|
</Layout>
|
||||||
<UserTable isAuthenticated={isAuthenticated} />
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<LoginCard
|
|
||||||
onClose={() => setShowLogin(false)}
|
|
||||||
changeAuth={(loggedIn) => setIsAuthenticated(loggedIn)}
|
|
||||||
/>
|
|
||||||
<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>
|
|
||||||
</AuthContext.Provider>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@@ -1,39 +1,46 @@
|
|||||||
import React, { useContext } from "react";
|
import { useState } from "react";
|
||||||
import Cookies from "js-cookie";
|
import React from "react";
|
||||||
import { AuthContext } from "../utils/context";
|
import LoginCard from "./LoginCard";
|
||||||
import { myToast } from "../utils/frontendService";
|
import { greeting } from "../utils/frontendService";
|
||||||
|
import { changeTheme } from "../utils/frontendService";
|
||||||
|
|
||||||
const Header: React.FC = () => {
|
const Header: React.FC = () => {
|
||||||
const { isAuthenticated, setIsAuthenticated } = useContext(AuthContext);
|
const [loginCardVisible, setLoginCardVisible] = useState(false);
|
||||||
const firstName = Cookies.get("firstName");
|
|
||||||
|
|
||||||
const handleLogout = () => {
|
const closeLoginCard = () => {
|
||||||
Cookies.remove("token");
|
setLoginCardVisible(false);
|
||||||
Cookies.remove("firstName");
|
|
||||||
setIsAuthenticated(false);
|
|
||||||
myToast("Logged out successfully!", "info");
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let loginBtnVal: string = "Hello, " + greeting() + "!";
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<header className="w-full flex justify-between items-center px-8 py-4 bg-gradient-to-r from-blue-100 via-blue-200 to-blue-100 dark:from-gray-900 dark:via-gray-950 dark:to-gray-900 shadow-lg">
|
<header className="bg-blue-600 dark:bg-gray-900 text-white p-4 shadow-md">
|
||||||
<h1 className="text-2xl font-bold text-blue-700 dark:text-blue-200 tracking-wide">
|
<div className="container mx-auto flex justify-between items-center">
|
||||||
🚲 Bikelane Dashboard
|
<h1 className="text-xl font-bold">
|
||||||
</h1>
|
Bikelane <strong>Admin Panel</strong>
|
||||||
<div className="flex items-center gap-4">
|
</h1>
|
||||||
{isAuthenticated && (
|
<nav>
|
||||||
<>
|
<ul className="flex space-x-4">
|
||||||
<span className="text-lg font-semibold text-blue-700 dark:text-blue-200">
|
<li>
|
||||||
Hello, {firstName || "User"}
|
<a className="hover:underline">
|
||||||
</span>
|
<button
|
||||||
<button
|
onClick={() => changeTheme()}
|
||||||
onClick={handleLogout}
|
className="bg-blue-700 dark:bg-gray-800 shadow-md hover:bg-blue-800 dark:hover:bg-gray-700 transition padding px-4 py-2 rounded-md text-white font-semibold"
|
||||||
className="px-4 py-2 bg-red-600 text-white rounded shadow hover:bg-red-700 transition"
|
>
|
||||||
>
|
Change Theme
|
||||||
Logout
|
</button>
|
||||||
</button>
|
<button
|
||||||
</>
|
onClick={() => setLoginCardVisible(true)}
|
||||||
)}
|
className="bg-blue-700 dark:bg-gray-800 shadow-md hover:bg-blue-800 dark:hover:bg-gray-700 transition padding px-4 py-2 rounded-md text-white font-semibold"
|
||||||
|
>
|
||||||
|
{loginBtnVal ?? "Login"}
|
||||||
|
</button>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
|
<div>{loginCardVisible && <LoginCard onClose={closeLoginCard} />}</div>
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
@@ -1,85 +1,93 @@
|
|||||||
import React, { useState, useContext } from "react";
|
import React from "react";
|
||||||
import Cookies from "js-cookie";
|
import Cookies from "js-cookie";
|
||||||
import { AuthContext } from "../utils/context";
|
import { logout, loginUser } from "../utils/userHandler";
|
||||||
import { myToast } from "../utils/frontendService";
|
type LoginCardProps = {
|
||||||
|
|
||||||
interface LoginCardProps {
|
|
||||||
onClose: () => void;
|
onClose: () => void;
|
||||||
changeAuth?: (loggedIn: boolean) => void;
|
};
|
||||||
}
|
|
||||||
|
|
||||||
const LoginCard: React.FC<LoginCardProps> = ({ onClose, changeAuth }) => {
|
|
||||||
const [username, setUsername] = useState("");
|
|
||||||
const [password, setPassword] = useState("");
|
|
||||||
const [error, setError] = useState("");
|
|
||||||
const { setIsAuthenticated } = useContext(AuthContext);
|
|
||||||
|
|
||||||
const handleLogin = async (e: React.FormEvent) => {
|
|
||||||
e.preventDefault();
|
|
||||||
setError("");
|
|
||||||
try {
|
|
||||||
const response = await fetch("http://45.133.75.67:5002/api/login", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ username, password }),
|
|
||||||
});
|
|
||||||
const data = await response.json();
|
|
||||||
if (response.ok && data.token) {
|
|
||||||
Cookies.set("token", data.token);
|
|
||||||
Cookies.set("firstName", data.user.first_name);
|
|
||||||
setIsAuthenticated(true);
|
|
||||||
if (changeAuth) changeAuth(true);
|
|
||||||
onClose();
|
|
||||||
myToast("Login successful!", "success");
|
|
||||||
} else {
|
|
||||||
myToast("Login failed!", "error");
|
|
||||||
setError(data.message || "Login fehlgeschlagen");
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
setError("Netzwerkfehler");
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
const LoginCard: React.FC<LoginCardProps> = ({ onClose }) => {
|
||||||
return (
|
return (
|
||||||
<div className="fixed inset-0 z-50 pointer-events-none">
|
<div className="fixed inset-0 flex items-center justify-center bg-black/35">
|
||||||
{/* Overlay */}
|
<div className="max-w-sm bg-white dark:bg-gray-900 rounded-xl shadow-md p-8 relative">
|
||||||
<div className="absolute inset-0 bg-white bg-opacity-40 backdrop-blur-sm pointer-events-auto"></div>
|
<button
|
||||||
{/* Card oben am Dashboard */}
|
className="absolute top-4 right-4 bg-red-500 text-white w-8 h-8 rounded-full flex items-center justify-center font-bold shadow hover:bg-red-600 transition focus:outline-none focus:ring-2 focus:ring-red-400"
|
||||||
<form
|
onClick={onClose}
|
||||||
onSubmit={handleLogin}
|
aria-label="Close"
|
||||||
className="absolute left-1/2 -translate-x-1/2 top-10 z-10 bg-white dark:bg-gray-900 rounded-2xl shadow-2xl px-8 py-10 flex flex-col gap-6 min-w-[340px] max-w-[90vw] border border-blue-200 dark:border-gray-800 pointer-events-auto"
|
>
|
||||||
>
|
×
|
||||||
<h2 className="text-2xl font-bold text-center text-blue-700 dark:text-blue-200 mb-2">
|
</button>
|
||||||
|
<h2 className="text-black dark:text-white text-2xl font-bold mb-6 text-center">
|
||||||
Login
|
Login
|
||||||
</h2>
|
</h2>
|
||||||
{error && (
|
<form
|
||||||
<div className="text-red-600 text-center font-semibold">{error}</div>
|
onSubmit={async (event) => {
|
||||||
)}
|
event.preventDefault();
|
||||||
<input
|
const formData = new FormData(event.currentTarget);
|
||||||
type="text"
|
const username = formData.get("username");
|
||||||
placeholder="Benutzername"
|
const password = formData.get("password");
|
||||||
value={username}
|
loginUser(username as string, password as string);
|
||||||
onChange={(e) => setUsername(e.target.value)}
|
}}
|
||||||
className="border border-blue-300 dark:border-gray-700 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800 dark:text-white"
|
className="space-y-4 text-black dark:text-white"
|
||||||
required
|
>
|
||||||
/>
|
<div>
|
||||||
<input
|
<label
|
||||||
type="password"
|
htmlFor="username"
|
||||||
placeholder="Passwort"
|
className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
|
||||||
value={password}
|
>
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
Username
|
||||||
className="border border-blue-300 dark:border-gray-700 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-blue-400 dark:bg-gray-800 dark:text-white"
|
</label>
|
||||||
required
|
<input
|
||||||
/>
|
type="text"
|
||||||
<div className="flex gap-3 mt-2 justify-center">
|
name="username"
|
||||||
|
required
|
||||||
|
id="username"
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label
|
||||||
|
htmlFor="password"
|
||||||
|
className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-1"
|
||||||
|
>
|
||||||
|
Password
|
||||||
|
</label>
|
||||||
|
<input
|
||||||
|
type="password"
|
||||||
|
name="password"
|
||||||
|
required
|
||||||
|
id="password"
|
||||||
|
className="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
{Cookies.get("name") ? (
|
||||||
|
<p></p>
|
||||||
|
) : (
|
||||||
|
<input
|
||||||
|
type="submit"
|
||||||
|
value="Login"
|
||||||
|
className="w-full bg-blue-600 text-white font-semibold py-2 rounded-md hover:bg-blue-700 transition"
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
{Cookies.get("name") ? (
|
||||||
<button
|
<button
|
||||||
type="submit"
|
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"
|
||||||
className="bg-blue-600 hover:bg-blue-700 text-white font-semibold px-5 py-2 rounded-lg shadow transition"
|
onClick={logout}
|
||||||
>
|
>
|
||||||
Login
|
Logout
|
||||||
</button>
|
</button>
|
||||||
</div>
|
) : (
|
||||||
</form>
|
<p className="text-center text-gray-500 dark:text-gray-400 mt-4">
|
||||||
|
Don't have an account?{" "}
|
||||||
|
<a
|
||||||
|
href="/register"
|
||||||
|
className="text-blue-600 dark:text-blue-400 hover:underline"
|
||||||
|
>
|
||||||
|
Register here
|
||||||
|
</a>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
@@ -1,6 +1,6 @@
|
|||||||
import { MoreVertical } from "lucide-react";
|
import { MoreVertical } from "lucide-react";
|
||||||
import { useEffect, useState } from "react";
|
import React, { useEffect, useState } from "react";
|
||||||
import { useUsers } from "../utils/useUsers.ts";
|
import { deleteUser, updateUserFunc } from "../utils/userHandler.ts";
|
||||||
|
|
||||||
interface User {
|
interface User {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -14,25 +14,16 @@ interface User {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface UserTableProps {
|
interface UserTableProps {
|
||||||
isAuthenticated: boolean;
|
users: User[];
|
||||||
}
|
}
|
||||||
|
|
||||||
const UserTable: React.FC<UserTableProps> = ({ isAuthenticated }) => {
|
const UserTable: React.FC<UserTableProps> = ({ users }) => {
|
||||||
const [openMenu, setOpenMenu] = useState<number | null>(null);
|
const [openMenu, setOpenMenu] = useState<number | null>(null);
|
||||||
|
const [userList, setUserList] = useState<User[]>(users);
|
||||||
const {
|
|
||||||
users,
|
|
||||||
refresh: refreshUsers,
|
|
||||||
setUsers,
|
|
||||||
deleteUser,
|
|
||||||
updateUser: updateUserFunc,
|
|
||||||
} = useUsers();
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isAuthenticated) {
|
setUserList(users);
|
||||||
refreshUsers();
|
}, [users]);
|
||||||
}
|
|
||||||
}, [isAuthenticated]);
|
|
||||||
|
|
||||||
const handleMenuClick = (userId: number) => {
|
const handleMenuClick = (userId: number) => {
|
||||||
setOpenMenu(openMenu === userId ? null : userId);
|
setOpenMenu(openMenu === userId ? null : userId);
|
||||||
@@ -41,10 +32,8 @@ const UserTable: React.FC<UserTableProps> = ({ isAuthenticated }) => {
|
|||||||
const handleMenuClose = () => setOpenMenu(null);
|
const handleMenuClose = () => setOpenMenu(null);
|
||||||
|
|
||||||
const handleInputChange = (id: number, field: keyof User, value: string) => {
|
const handleInputChange = (id: number, field: keyof User, value: string) => {
|
||||||
setUsers((prevUsers) =>
|
setUserList((prev) =>
|
||||||
prevUsers.map((user) =>
|
prev.map((user) => (user.id === id ? { ...user, [field]: value } : user))
|
||||||
user.id === id ? { ...user, [field]: value } : user
|
|
||||||
)
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -82,9 +71,9 @@ const UserTable: React.FC<UserTableProps> = ({ isAuthenticated }) => {
|
|||||||
</tr>
|
</tr>
|
||||||
</thead>
|
</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">
|
<tbody className="bg-white text-black dark:bg-gray-900 dark:text-white divide-y divide-gray-100 dark:divide-gray-800 z-10">
|
||||||
{(users ?? []).map((user, idx) => {
|
{userList.map((user, idx) => {
|
||||||
// If this is one of the last 2 rows, open menu upwards
|
// If this is one of the last 2 rows, open menu upwards
|
||||||
const openUp = idx >= users.length - 2;
|
const openUp = idx >= userList.length - 2;
|
||||||
return (
|
return (
|
||||||
<tr
|
<tr
|
||||||
key={user.id}
|
key={user.id}
|
||||||
|
@@ -1,5 +1,6 @@
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import Header from "../components/Header";
|
import Header from "../components/Header";
|
||||||
|
import Cookies from "js-cookie";
|
||||||
import Sidebar from "../components/Sidebar";
|
import Sidebar from "../components/Sidebar";
|
||||||
import { ToastContainer } from "react-toastify";
|
import { ToastContainer } from "react-toastify";
|
||||||
|
|
||||||
@@ -8,15 +9,23 @@ type LayoutProps = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const Layout: React.FC<LayoutProps> = ({ children }) => {
|
const Layout: React.FC<LayoutProps> = ({ children }) => {
|
||||||
|
const isLoggedIn = !!Cookies.get("name");
|
||||||
|
|
||||||
return (
|
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">
|
<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 />
|
||||||
<ToastContainer />
|
<ToastContainer />
|
||||||
<div className="flex flex-1">
|
<div className="flex flex-1">
|
||||||
<Sidebar />
|
{isLoggedIn && (
|
||||||
<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}
|
{/* Sidebar */}
|
||||||
</main>
|
<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>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
</div>
|
</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">
|
<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">
|
<div className="flex flex-col items-center gap-2">
|
||||||
|
@@ -1,9 +0,0 @@
|
|||||||
import React from "react";
|
|
||||||
|
|
||||||
export const AuthContext = React.createContext<{
|
|
||||||
isAuthenticated: boolean;
|
|
||||||
setIsAuthenticated: (auth: boolean) => void;
|
|
||||||
}>({
|
|
||||||
isAuthenticated: false,
|
|
||||||
setIsAuthenticated: () => {},
|
|
||||||
});
|
|
@@ -1,3 +0,0 @@
|
|||||||
import { createContext } from "react";
|
|
||||||
|
|
||||||
export const AuthContext = createContext(false);
|
|
@@ -2,7 +2,7 @@ import Cookies from "js-cookie";
|
|||||||
import { toast, type ToastOptions } from "react-toastify";
|
import { toast, type ToastOptions } from "react-toastify";
|
||||||
|
|
||||||
export const greeting = () => {
|
export const greeting = () => {
|
||||||
return Cookies.get("username") ?? "Login";
|
return Cookies.get("name") ?? "Login";
|
||||||
};
|
};
|
||||||
|
|
||||||
export const loadTheme = () => {
|
export const loadTheme = () => {
|
||||||
|
@@ -1,6 +1,4 @@
|
|||||||
import { useState, type Dispatch, type SetStateAction } from "react";
|
import { useState, useEffect } from "react";
|
||||||
import Cookies from "js-cookie";
|
|
||||||
import { myToast } from "./frontendService";
|
|
||||||
|
|
||||||
export interface User {
|
export interface User {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -13,139 +11,20 @@ export interface User {
|
|||||||
role: string;
|
role: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type UserReturn = {
|
export function useUsers(): User[] {
|
||||||
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[]>([]);
|
const [users, setUsers] = useState<User[]>([]);
|
||||||
|
|
||||||
const token = Cookies.get("token");
|
useEffect(() => {
|
||||||
|
const data = localStorage.getItem("users");
|
||||||
const headers = {
|
if (data) {
|
||||||
"Content-Type": "application/json",
|
try {
|
||||||
Authorization: `Bearer ${token}`,
|
const parsed = JSON.parse(data);
|
||||||
};
|
setUsers(parsed.result || []);
|
||||||
|
} catch {
|
||||||
const fetchUsers = async () => {
|
setUsers([]);
|
||||||
try {
|
|
||||||
const response = await fetch("http://45.133.75.67: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) => {
|
return users;
|
||||||
fetch("http://45.133.75.67: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://45.133.75.67: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),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
@@ -1,37 +1,48 @@
|
|||||||
import Cookies from "js-cookie";
|
import Cookies from "js-cookie";
|
||||||
import { myToast } from "./frontendService";
|
import { myToast } from "./frontendService";
|
||||||
|
|
||||||
export const loginUser = async (
|
export const loginUser = (username: string, password: string) => {
|
||||||
username: string,
|
fetch(`http://localhost:5002/api/login`, {
|
||||||
password: string
|
method: "POST",
|
||||||
): Promise<boolean> => {
|
headers: { "Content-Type": "application/json" },
|
||||||
try {
|
body: JSON.stringify({ username, password }),
|
||||||
const response = await fetch("http://45.133.75.67:5002/api/login", {
|
})
|
||||||
method: "POST",
|
.then(async (response) => {
|
||||||
headers: { "Content-Type": "application/json" },
|
if (response.ok) {
|
||||||
body: JSON.stringify({ username, password }),
|
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");
|
||||||
|
} else if (response.status === 403) {
|
||||||
|
myToast("You are not an Admin!", "error");
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((error) => {
|
||||||
|
console.log("Login failed: ", error);
|
||||||
});
|
});
|
||||||
if (response.ok) {
|
|
||||||
const data = await response.json();
|
|
||||||
Cookies.set("token", data.token); // Set cookie here
|
|
||||||
Cookies.set("username", username); // Set username cookie
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
} catch {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const logout = () => {
|
export const logout = () => {
|
||||||
Cookies.remove("username");
|
Cookies.remove("name");
|
||||||
Cookies.remove("token");
|
Cookies.remove("token");
|
||||||
localStorage.removeItem("users");
|
localStorage.removeItem("users");
|
||||||
myToast("Logged out successfully!", "info");
|
myToast("Logged out successfully!", "success");
|
||||||
};
|
};
|
||||||
|
|
||||||
export const deleteUser = (id: number) => {
|
export const deleteUser = (id: number) => {
|
||||||
fetch("http://45.133.75.67:5002/api/deleteUser", {
|
fetch("http://localhost:5002/api/deleteUser", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify({ id: id }),
|
body: JSON.stringify({ id: id }),
|
||||||
headers: {
|
headers: {
|
||||||
@@ -41,9 +52,9 @@ export const deleteUser = (id: number) => {
|
|||||||
})
|
})
|
||||||
.then((response) => {
|
.then((response) => {
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
replaceUsers();
|
replaceUsers("User deleted successfully!");
|
||||||
} else {
|
} else {
|
||||||
alert("Failed to delete user");
|
myToast("Failed to delete user", "error");
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.catch((error) => {
|
.catch((error) => {
|
||||||
@@ -51,9 +62,9 @@ export const deleteUser = (id: number) => {
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
export const replaceUsers = async () => {
|
export const replaceUsers = async (alertMessage: string) => {
|
||||||
localStorage.removeItem("users");
|
localStorage.removeItem("users");
|
||||||
await fetch("http://45.133.75.67:5002/api/getAllUsers", {
|
await fetch("http://localhost:5002/api/getAllUsers", {
|
||||||
method: "GET",
|
method: "GET",
|
||||||
headers: {
|
headers: {
|
||||||
Authorization: `Bearer ${Cookies.get("token")}`,
|
Authorization: `Bearer ${Cookies.get("token")}`,
|
||||||
@@ -62,7 +73,7 @@ export const replaceUsers = async () => {
|
|||||||
.then((res) => res.json())
|
.then((res) => res.json())
|
||||||
.then((users) => {
|
.then((users) => {
|
||||||
localStorage.setItem("users", JSON.stringify(users));
|
localStorage.setItem("users", JSON.stringify(users));
|
||||||
window.location.reload();
|
myToast(alertMessage, "success");
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -88,7 +99,7 @@ export const updateUserFunc = async (userID: number) => {
|
|||||||
|
|
||||||
if (!usernameEl || !firstNameEl || !lastNameEl || !emailEl) {
|
if (!usernameEl || !firstNameEl || !lastNameEl || !emailEl) {
|
||||||
console.error("Required form elements not found");
|
console.error("Required form elements not found");
|
||||||
alert("Form elements not found");
|
myToast("Form elements not found", "error");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,7 +115,7 @@ export const updateUserFunc = async (userID: number) => {
|
|||||||
console.log("Sending user data:", userData);
|
console.log("Sending user data:", userData);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch("http://45.133.75.67:5002/api/updateUser", {
|
const response = await fetch("http://localhost:5002/api/updateUser", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: JSON.stringify(userData),
|
body: JSON.stringify(userData),
|
||||||
headers: {
|
headers: {
|
||||||
@@ -118,7 +129,7 @@ export const updateUserFunc = async (userID: number) => {
|
|||||||
|
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
console.log("User updated successfully");
|
console.log("User updated successfully");
|
||||||
replaceUsers();
|
replaceUsers("User updated successfully!");
|
||||||
} else {
|
} else {
|
||||||
const errorText = await response.text();
|
const errorText = await response.text();
|
||||||
console.error("Server error:", response.status, errorText);
|
console.error("Server error:", response.status, errorText);
|
||||||
|
@@ -1,13 +1,12 @@
|
|||||||
# Build Stage
|
FROM node:20-alpine
|
||||||
FROM node:20-alpine AS build
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
COPY package*.json ./
|
COPY package*.json ./
|
||||||
RUN npm install
|
RUN npm install
|
||||||
COPY . .
|
|
||||||
RUN npm run build
|
|
||||||
|
|
||||||
# Production Stage
|
COPY . .
|
||||||
FROM nginx:stable-alpine AS production
|
|
||||||
COPY --from=build /app/build /usr/share/nginx/html
|
|
||||||
EXPOSE 5003
|
EXPOSE 5003
|
||||||
CMD ["nginx", "-g", "daemon off;"]
|
|
||||||
|
CMD ["npm", "start"]
|
||||||
|
6
package-lock.json
generated
6
package-lock.json
generated
@@ -1,6 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "bikelane",
|
|
||||||
"lockfileVersion": 3,
|
|
||||||
"requires": true,
|
|
||||||
"packages": {}
|
|
||||||
}
|
|
Reference in New Issue
Block a user