Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
98 views
in Technique[技术] by (71.8m points)

Restrict client from html page using javascript

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would suggest you to store the auth_token in a cookie... Instead of localStorage. So the cookie would be sent along the HTTP request... And the decision to serve the protected content would be made server-side.

But if you insist... Just to practice... You could hide the HTML by default via CSS for that split second:

Add the hiddenOnLoad class to the HTML markup:

<body class="hiddenOnLoad">

Which would just hide everything:

body.hiddenOnLoad *{
  display: none !important;
}

And inside $(document).ready()... It the authentication succeeded:

if(isAuthenticated){
  $("body").removeClass("hiddenOnLoad")
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...