Return the previous page after logging in

Asked

Viewed 438 times

1

I set up a site where the user logs in by placing any Login and Password and storing it in Localstorage. Which part of the site he tries to access, always redirects to the Login page if he has not logged in at least 1 time. (Example: if it tries to access: localhost:5000/chamado -> it will be redirected to login localhost:5000 or localhost:5000/login. If he tries to access the page localhost:5000/home -> it will be redirected to login localhost:5000 or localhost:5000/login.

But my question is to do so, if he tried to access the /chamado, it is redirected to log in, and after logging in, go back to /chamado. Or if he wants to access /home, return to login page, after it logs in, go back to page home.

I work using Node.js, and have built pages in EJS and JS (Javascript) files. And at first I created a method that it only directs to Home page after logging in, regardless of the part the user tries to log in.

At the end of the code, inside the then, has the window.location: home; That always after logging it will redirect to ''home' page, but I wanted somehow it to return to page that user tried to access first. For example: /chamado.

login ejs.

function verifyIfUserIsLogged() {
    const user = localStorage.getItem('user');
    const password = localStorage.getItem('password');

    if (user && password) { //verifica se tem login e password, e se tiver, direciona para rota X (no caso é a home)
        window.location = '/home';
    }
}

function setUserAtLocalStorage(e) {
    var user = document.getElementById("user").value; //pega o valor que está no user/input
    var password = document.getElementById("password").value; //pega o valor que está no password/input

    if(!user || !password ){ //! significa negação
        return alert("Dados inválidos!");
    }

    var body = {
        login: user,
        password: password
    };

    fetch('/login', { //faz uma requisição http
        method: 'post',
        headers: {
            'Accept': 'application/json, text/plain, */*', //o tipo de conteudo que vai ser aceito
            'Content-Type': 'application/json' //tipo de conteudo que está enviando
        },
        body: JSON.stringify(body)
    }).then(res => { //espera a requisição ser feita - promise
        localStorage.setItem('user', user); //salva no local storage
        localStorage.setItem('password', password);
        window.location = 'home'; //retorna a home
    });
}

verifyIfUserIsLogged(); //chama a função

2 answers

1

You can use a very simple logic: save the current user location, with window.location.pathname by exmeplo, and in the Promise redirects to that page:

// se o caminho for a raiz "/", definir como "/home", senão pega o caminho atual
var path = window.location.pathname == '/' ? '/home' : window.location.pathname;
fetch('/login', { //faz uma requisição http
                method: 'post',
                headers: {
                    'Accept': 'application/json, text/plain, */*', //o tipo de conteudo que vai ser aceito
                    'Content-Type': 'application/json' //tipo de conteudo que está enviando
                },
                body: JSON.stringify(body)
            }).then(res => { //espera a requisição ser feita - promise
                localStorage.setItem('user', user); //salva no local storage
                localStorage.setItem('password', password);
                window.location = path; //retorna a home
            });

If you want to stay on the page after authenticating, you can do a reload also

  • And when you navigate to another route, "/test" for example, what is the value in the variable "path"?

  • I did that too. And if I change that 'home'' in the 'path'' to 'called', for example, then it starts to return always to 'called'' after the user logs in.

0

I did this way Ricardo Punctual, but he keeps returning to home page. To give you an idea, I put a function on the page called.ejs that validates whether the user has already logged on to Localstorage or not.

<script>
            const verifyIfUserIsLogged = () => {
            const user = localStorage.getItem('user');
            const password = localStorage.getItem('password');

            if (!user || !password) {
                window.location = '/';
            }
            
        }

        verifyIfUserIsLogged();

 </script>

It returns to login.ejs and after logging in, it goes to home.ejs Below was the login.ejs:

 <script>
    function verifyIfUserIsLogged() {
        const user = localStorage.getItem('user');
        const password = localStorage.getItem('password');

        if (user && password) { //verifica se tem login e password, e se tiver, direciona para rota X (no caso é a home)
            window.location = '/home';
        }
    }

    function setUserAtLocalStorage(e) {
        var user = document.getElementById("user").value; //pega o valor que está no user/input
        var password = document.getElementById("password").value; //pega o valor que está no password/input
        
        if(!user || !password ){ //! significa negação
            return alert("Dados inválidos!");
        }

        var body = {
            login: user,
            password: password
        };
        
        var path = window.location.pathname == '/' ? '/home' : window.location.pathname;

        fetch('/login', { //faz uma requisição http
            method: 'post',
            headers: {
                'Accept': 'application/json, text/plain, */*', //o tipo de conteudo que vai ser aceito
                'Content-Type': 'application/json' //tipo de conteudo que está enviando
            },
            body: JSON.stringify(body)
        }).then(res => { //espera a requisição ser feita - promise
            localStorage.setItem('user', user); //salva no local storage
            localStorage.setItem('password', password);
            window.location = path; //retorna a home
        });
    }
    verifyIfUserIsLogged(); //chama a função
</script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.