smplify token validation
This commit is contained in:
parent
b8a0fd9179
commit
cef340a679
@ -78,10 +78,10 @@ def registerUserEndpoints(app, database):
|
|||||||
data = request.json
|
data = request.json
|
||||||
token = data.get('token')
|
token = data.get('token')
|
||||||
user_name = data.get('userName')
|
user_name = data.get('userName')
|
||||||
query = "SELECT * FROM sessions WHERE Token=%s AND Name=%s"
|
query = "SELECT * FROM sessions WHERE Token=%s"
|
||||||
try:
|
try:
|
||||||
result = database.query(query, params=(token, user_name))
|
result = database.query(query, params=(token,))
|
||||||
app.logger.info(f'Got result: {result}')
|
app.logger.info(f'Got result: {result}')
|
||||||
return jsonify(tokenValid=bool(result)), 200
|
return jsonify(userName=result[0][1], tokenValid=True), 200
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify(success=False, message=str(e)), 500
|
return jsonify(success=False, message=str(e)), 500
|
||||||
|
|||||||
@ -6,8 +6,8 @@ import { useNotification } from '../NotificationContext';
|
|||||||
|
|
||||||
const InitialSetup = () => {
|
const InitialSetup = () => {
|
||||||
const [cookie, setCookie] = useCookies();
|
const [cookie, setCookie] = useCookies();
|
||||||
const [selectedName, setSelectedName] = useState<string | undefined>(cookie.userName);
|
const [selectedName, setSelectedName] = useState<string | undefined>(undefined);
|
||||||
const [token] = useState<string | undefined>(cookie.apiToken)
|
//const [token] = useState<string | undefined>(cookie.apiToken)
|
||||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
const [isPasswordSet, setIsPasswordSet] = useState(false); // To track if password is set
|
const [isPasswordSet, setIsPasswordSet] = useState(false); // To track if password is set
|
||||||
@ -27,13 +27,14 @@ const InitialSetup = () => {
|
|||||||
checkUserPassword(name);
|
checkUserPassword(name);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const validateToken = async () => {
|
||||||
|
const isTokenValid = await validToken(cookie.apiToken);
|
||||||
|
setIsSubmitted(isTokenValid);
|
||||||
|
};
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const validateToken = async () => {
|
if (cookie.apiToken !== undefined) validateToken();
|
||||||
const isTokenValid = await validToken(token, selectedName);
|
}, [cookie.apiToken]);
|
||||||
setIsSubmitted(isTokenValid);
|
|
||||||
};
|
|
||||||
if (token !== undefined && selectedName !== undefined) validateToken();
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
|
|
||||||
const handlePasswordCreate = async () => {
|
const handlePasswordCreate = async () => {
|
||||||
@ -42,7 +43,7 @@ const InitialSetup = () => {
|
|||||||
notify(message, 'error')
|
notify(message, 'error')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setIsSubmitted(true);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleSignIn = async () => {
|
const handleSignIn = async () => {
|
||||||
@ -51,7 +52,7 @@ const InitialSetup = () => {
|
|||||||
notify('Не удалось войти. Может пароль не тот?', 'error')
|
notify('Не удалось войти. Может пароль не тот?', 'error')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
setIsSubmitted(true);
|
validateToken()
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -3,7 +3,8 @@ import { API_URL } from '../constants/constants';
|
|||||||
import { hashPassword } from './hashPassword';
|
import { hashPassword } from './hashPassword';
|
||||||
|
|
||||||
const useFetchUser = () => {
|
const useFetchUser = () => {
|
||||||
const [, setCookie] = useCookies(['apiToken']);
|
const [, setApiCookie] = useCookies(['apiToken']);
|
||||||
|
const [, setUserNameCookie] = useCookies(['userName'])
|
||||||
|
|
||||||
const userSet = async (userName: string): Promise<boolean> => {
|
const userSet = async (userName: string): Promise<boolean> => {
|
||||||
try {
|
try {
|
||||||
@ -41,7 +42,7 @@ const useFetchUser = () => {
|
|||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (data.success) {
|
if (data.success) {
|
||||||
setCookie('apiToken', data.token, { path: '/' });
|
setApiCookie('apiToken', data.token, { path: '/' });
|
||||||
console.log(`Password created for ${userName}`);
|
console.log(`Password created for ${userName}`);
|
||||||
return ''; // Password creation success
|
return ''; // Password creation success
|
||||||
}
|
}
|
||||||
@ -70,7 +71,7 @@ const useFetchUser = () => {
|
|||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
|
|
||||||
if (data.token) {
|
if (data.token) {
|
||||||
setCookie('apiToken', data.token, { path: '/' });
|
setApiCookie('apiToken', data.token, { path: '/' });
|
||||||
console.log(`User ${userName} signed in.`);
|
console.log(`User ${userName} signed in.`);
|
||||||
return true; // Sign-in success
|
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 {
|
try {
|
||||||
const response = await fetch(`${API_URL}/login/validateToken`, {
|
const response = await fetch(`${API_URL}/login/validateToken`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
@ -89,14 +90,17 @@ const useFetchUser = () => {
|
|||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
token,
|
token
|
||||||
userName
|
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
|
||||||
const data = await response.json();
|
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
|
return data.tokenValid
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Error validating token:', error);
|
console.error('Error validating token:', error);
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user