smplify token validation

This commit is contained in:
tylen
2025-11-01 22:19:09 +02:00
parent b8a0fd9179
commit cef340a679
3 changed files with 24 additions and 19 deletions

View File

@@ -3,7 +3,8 @@ import { API_URL } from '../constants/constants';
import { hashPassword } from './hashPassword';
const useFetchUser = () => {
const [, setCookie] = useCookies(['apiToken']);
const [, setApiCookie] = useCookies(['apiToken']);
const [, setUserNameCookie] = useCookies(['userName'])
const userSet = async (userName: string): Promise<boolean> => {
try {
@@ -41,7 +42,7 @@ const useFetchUser = () => {
const data = await response.json();
if (data.success) {
setCookie('apiToken', data.token, { path: '/' });
setApiCookie('apiToken', data.token, { path: '/' });
console.log(`Password created for ${userName}`);
return ''; // Password creation success
}
@@ -70,7 +71,7 @@ const useFetchUser = () => {
const data = await response.json();
if (data.token) {
setCookie('apiToken', data.token, { path: '/' });
setApiCookie('apiToken', data.token, { path: '/' });
console.log(`User ${userName} signed in.`);
return true; // Sign-in success
}
@@ -81,7 +82,7 @@ const useFetchUser = () => {
}
};
const validToken = async (token: string | undefined, userName: string | undefined): Promise<boolean> => {
const validToken = async (token: string | undefined): Promise<boolean> => {
try {
const response = await fetch(`${API_URL}/login/validateToken`, {
method: 'POST',
@@ -89,14 +90,17 @@ const useFetchUser = () => {
'Content-Type': 'application/json',
},
body: JSON.stringify({
token,
userName
token
}),
});
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
const data = await response.json();
if (!data.userName) throw new Error(`Could not retrieve userName from token`);
setUserNameCookie('userName', data.userName, { path: '/' });
return data.tokenValid
} catch (error) {
console.error('Error validating token:', error);