frontend: create user auth
This commit is contained in:
124
frontend/src/utils/fetchUser.tsx
Normal file
124
frontend/src/utils/fetchUser.tsx
Normal file
@@ -0,0 +1,124 @@
|
||||
import { useState } from 'react';
|
||||
import { useCookies } from 'react-cookie';
|
||||
|
||||
interface User {
|
||||
password?: string;
|
||||
}
|
||||
|
||||
interface UserData {
|
||||
[key: string]: User;
|
||||
}
|
||||
|
||||
const useFetchUser = () => {
|
||||
const [cookies, setCookie] = useCookies(['apiToken']);
|
||||
|
||||
const userSet = async (userName: string): Promise<boolean> => {
|
||||
try {
|
||||
const response = await fetch(`/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
|
||||
} catch (error) {
|
||||
console.error('Error checking user password status:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const passwordCreate = async (userName: string, password: string): Promise<string> => {
|
||||
// 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.';
|
||||
}
|
||||
|
||||
try {
|
||||
const hashedPassword = await hashPassword(password); // Implement this function to hash the password
|
||||
const response = await fetch(`/users/createPassword`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userName,
|
||||
password: hashedPassword,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setCookie('apiToken', data.token, { path: '/' });
|
||||
console.log(`Password created for ${userName}`);
|
||||
return ''; // Password creation success
|
||||
}
|
||||
return 'Не удалось создать пароль'; // Password creation failure
|
||||
} catch (error) {
|
||||
console.error('Error creating password:', error);
|
||||
return 'Пароль не создан:' + error;
|
||||
}
|
||||
};
|
||||
|
||||
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`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
userName,
|
||||
password: hashedPassword,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.token) {
|
||||
setCookie('apiToken', data.token, { path: '/' });
|
||||
console.log(`User ${userName} signed in.`);
|
||||
return true; // Sign-in success
|
||||
}
|
||||
return false; // Sign-in failed
|
||||
} catch (error) {
|
||||
console.error('Error logging in:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const validToken = async (token: string | undefined): Promise<boolean> => {
|
||||
try {
|
||||
const response = await fetch(`/login/validateToken`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
token,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.tokenValid) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} 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 };
|
||||
};
|
||||
|
||||
export default useFetchUser;
|
||||
Reference in New Issue
Block a user