I serve a HTML page, which presents within my users-authentication system.
The HTML page should be unreachable when non-authenticated client tries to access it.
So, I have the following JS code:
let isAuthenticated = false;
let username;
(async () => {
// Retrieve username if logged-in
try {
const serverResponse = await fetch('api/auth/getUsername', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${localStorage.getItem('auth_token') || ''}`,
},
});
const serverResponseData = await serverResponse.json();
if (serverResponseData.success) {
isAuthenticated = true;
username = serverResponseData.data.username;
} else {
return window.location.href = '/';
}
} catch { } finally {
$(document).ready(() => {
// Username and auth buttons elements
const $authButtonsContainerELM = $('#authButtonsContainer');
const $navUserContainerELM = $('#navUserContainer');
const $usernameText = $('#usernameText');
if (isAuthenticated) {
$authButtonsContainerELM.css('display', 'none');
$navUserContainerELM.css('display', 'flex');
$usernameText.html(username);
} else {
$authButtonsContainerELM.css('display', 'flex');
$navUserContainerELM.css('display', 'none');
}
});
}
})();
And here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>post blog</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery.min.js">x3C/script>');</script>
<script src="./JS/index.js"></script>
<div>blbalalal</div>
</body>
</html>
Note that the actual HTML code in my source is a bit more complex of-course.
So basically when I go as not authenticated in my browser, I try to access this page.
What happens is, I can see the HTML page for 1 sec then I got redirect back to /
path. But I do see the HTML. How can I execute my JS code before the HTML loads?
question from:
https://stackoverflow.com/questions/65944252/restrict-client-from-html-page-using-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…