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

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
};