frontend: big upgrade

This commit is contained in:
tylen 2025-10-31 17:30:08 +02:00
parent 3f074e895d
commit 5baeee1f97
10 changed files with 90 additions and 49 deletions

29
frontend/Dockerfile Normal file
View File

@ -0,0 +1,29 @@
# Use the official Node.js image.
FROM node:18 AS build
# Set the working directory
WORKDIR /app
# Copy package.json and package-lock.json (or yarn.lock) to the working directory
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of the application
COPY . .
# Build the application
RUN npm run build
# Start a new stage to serve the application
FROM nginx:alpine
# Copy the build output to Nginx's public folder
COPY --from=build /app/dist /usr/share/nginx/html
# Expose port 80
EXPOSE 80
# Start Nginx when the container runs
CMD ["nginx", "-g", "daemon off;"]

View File

@ -8,6 +8,7 @@
"name": "frontend",
"version": "0.0.0",
"dependencies": {
"crypto-js": "^4.2.0",
"js-cookie": "^3.0.5",
"react": "^19.2.0",
"react-cookie": "^8.0.1",
@ -15,6 +16,7 @@
},
"devDependencies": {
"@eslint/js": "^9.33.0",
"@types/crypto-js": "^4.2.2",
"@types/react": "^19.1.10",
"@types/react-dom": "^19.1.7",
"@vitejs/plugin-react": "^5.0.0",
@ -1408,6 +1410,13 @@
"@babel/types": "^7.28.2"
}
},
"node_modules/@types/crypto-js": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.2.2.tgz",
"integrity": "sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/estree": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz",
@ -1978,6 +1987,12 @@
"node": ">= 8"
}
},
"node_modules/crypto-js": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q==",
"license": "MIT"
},
"node_modules/csstype": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",

View File

@ -10,6 +10,7 @@
"preview": "vite preview"
},
"dependencies": {
"crypto-js": "^4.2.0",
"js-cookie": "^3.0.5",
"react": "^19.2.0",
"react-cookie": "^8.0.1",
@ -17,6 +18,7 @@
},
"devDependencies": {
"@eslint/js": "^9.33.0",
"@types/crypto-js": "^4.2.2",
"@types/react": "^19.1.10",
"@types/react-dom": "^19.1.7",
"@vitejs/plugin-react": "^5.0.0",

View File

@ -65,7 +65,7 @@ function Hosting() {
<tr key={id}>
<td>{item.name}</td>
<td>{item.capacity}</td>
<td>{<ReserveButton update={update} reservedBy={item.reservedBy} id={id} />}</td>
<td>{<ReserveButton update={update} reservedBy={item.reservedBy} id={Number(id)} />}</td>
</tr>
))}
</tbody>

View File

@ -7,25 +7,29 @@ import { useNotification } from '../NotificationContext';
const InitialSetup = () => {
const [cookie, setCookie] = useCookies();
const [selectedName, setSelectedName] = useState<string | undefined>(cookie.userName);
const [token, setToken] = useState<string | undefined>(cookie.token)
const [token] = useState<string | undefined>(cookie.apiToken)
const [isSubmitted, setIsSubmitted] = useState(false);
const [password, setPassword] = useState('');
const [isPasswordSet, setIsPasswordSet] = useState(false); // To track if password is set
const [isSignIn, setIsSignIn] = useState(false); // To track if it should prompt for sign-in
const { userSet, passwordCreate, signUser, validToken } = useFetchUser(); // Destructure functions from the hook
const notify = useNotification();
useEffect(() => {
document.body.style.overflow = 'hidden';
return () => {
document.body.style.overflow = 'unset';
const validateToken = async () => {
const isTokenValid = await validToken(token, selectedName);
setIsSubmitted(isTokenValid);
};
}, []);
validateToken();
if (selectedName) {
checkUserPassword(selectedName)
}
}, [selectedName]);
const handleSelect = (event: React.ChangeEvent<HTMLSelectElement>) => {
const name = event.target.value;
setCookie('userName', name, { path: '/' });
setSelectedName(name);
checkUserPassword(name);
};
@ -33,7 +37,6 @@ const InitialSetup = () => {
const checkUserPassword = async (name: string) => {
const passwordStatus = await userSet(name);
setIsPasswordSet(passwordStatus);
setIsSignIn(!passwordStatus); // If password is not set, show sign-up
};
const handlePasswordCreate = async () => {
@ -54,25 +57,17 @@ const InitialSetup = () => {
setIsSubmitted(true);
};
if (isSubmitted) {
console.log('Selected', selectedName);
return null; // or you can redirect to another component or page
}
useEffect(() => {
const validateToken = async () => {
const isTokenValid = await validToken(token);
setIsSubmitted(isTokenValid);
};
validateToken();
}, [token]);
return (
<div style={styles.container}>
<h2 style={styles.title}>Выбери себя</h2>
<select style={styles.dropdown} onChange={handleSelect} value={selectedName || ''}>
<option value="" disabled>Select your name</option>
<option value="" disabled>{(cookie.userName == undefined) ? 'Пятка' : cookie.userName}</option>
{GUESTS.map((name) => (
<option key={name} value={name}>
{name}

View File

@ -1,5 +1,5 @@
export const API_URL = 'https://example.backend.com/hosting';
export const API_URL = 'https://nyipyatki-backend.davydovcloud.com';
export const GUESTS = [
"Медведь",
"Ксения",

View File

@ -1,5 +1,6 @@
import { useState, useEffect } from 'react';
import type { Hosting } from '../types';
import { API_URL } from '../constants/constants';
const mockData: Hosting = {
1: {
@ -33,7 +34,7 @@ const useFetchHosting = () => {
setLoading(true);
setError(null);
try {
const response = await fetch('/hosting');
const response = await fetch(`${API_URL}/hosting`);
if (response.status != 200) {
throw new Error('Network response was not ok');
}
@ -48,7 +49,7 @@ const useFetchHosting = () => {
setLoading(true);
setError(null);
try {
const response = await fetch(`/hosting/${id}`, {
const response = await fetch(`${API_URL}/hosting/${id}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',

View File

@ -1,20 +1,13 @@
import { useState } from 'react';
import { useCookies } from 'react-cookie';
interface User {
password?: string;
}
interface UserData {
[key: string]: User;
}
import { API_URL } from '../constants/constants';
import { hashPassword } from './hashPassword';
const useFetchUser = () => {
const [cookies, setCookie] = useCookies(['apiToken']);
const [, setCookie] = useCookies(['apiToken']);
const userSet = async (userName: string): Promise<boolean> => {
try {
const response = await fetch(`/users/isSet?userName=${encodeURIComponent(userName)}`);
const response = await fetch(`${API_URL}/users/isSet?userName=${encodeURIComponent(userName)}`);
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
return data; // Assuming the server returns true/false
@ -28,12 +21,12 @@ const useFetchUser = () => {
// Simple validation: password should not be empty and should have a minimum length
if (!password || password.length < 6) {
console.error('Password should be at least 6 characters long.');
return 'Password should be at least 6 characters long.';
return 'Пароль должен иметь, как минимум 6 символов';
}
try {
const hashedPassword = await hashPassword(password); // Implement this function to hash the password
const response = await fetch(`/users/createPassword`, {
const hashedPassword = hashPassword(password)
const response = await fetch(`${API_URL}/users/createPassword`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -61,8 +54,8 @@ const useFetchUser = () => {
const signUser = async (userName: string, password: string): Promise<boolean> => {
try {
const hashedPassword = await hashPassword(password); // Implement this function to hash the password
const response = await fetch(`/login`, {
const hashedPassword = hashPassword(password); // Implement this function to hash the password
const response = await fetch(`${API_URL}/login`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@ -88,36 +81,29 @@ const useFetchUser = () => {
}
};
const validToken = async (token: string | undefined): Promise<boolean> => {
const validToken = async (token: string | undefined, userName: string | undefined): Promise<boolean> => {
try {
const response = await fetch(`/login/validateToken`, {
const response = await fetch(`${API_URL}/login/validateToken`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
token,
userName
}),
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
if (data.tokenValid) {
return true;
}
return false;
return data.tokenValid
} catch (error) {
console.error('Error validating token:', error);
return false;
}
}
const hashPassword = async (password: string): Promise<string> => {
// Placeholder implementation, replace with actual hashing logic (e.g. bcrypt)
return Promise.resolve(password); // Just return the password for now
};
return { userSet, passwordCreate, signUser, validToken };
};

View File

@ -0,0 +1,10 @@
// src/utils/passwordHasher.ts
import SHA256 from 'crypto-js/sha256';
/**
* Hashes a password using SHA-256.
* @param {string} password - The plain text password.
* @returns {string} - The hashed password in hex format.
*/
export const hashPassword = (password: string): string => {
return SHA256(password).toString(); // Returns the hash in hex format
};

View File

@ -4,4 +4,7 @@ import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
allowedHosts: ['nyipyatki-dev.davydovcloud.com'],
}
})