Return to previous page after signing in

1

I've set up a site where the user logs in by entering 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 it tries to access page localhost:5000/home -> it will be redirected to login localhost:5000 or localhost:5000/login .

But my doubt is to do so, if he tried to access /chamado , he is redirected to login, and after login, return to /chamado . Or if he wants to access /home , return to login page, after he logs in, return to page home .

I work using Node.js, and I mounted pages in EJS and JS (JavaScript) files. And in the beginning I created a method that it only directs to Home page after login, regardless of which part the user tries to log in.

At the end of the code, within then , has window.location : home ; That always after logging it will redirect to the '' home '' page, but I somehow wanted it to return to the page that the user tried to access first. As 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
    
asked by anonymous 31.08.2018 / 18:53

2 answers

1

You can use a very simple logic: it saves the user's current location, with window.location.pathname for example, and on return on 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 you authenticate, you can reload also

    
31.08.2018 / 19:01
0

I did that way Ricardo Pontual, but he keeps returning to home page. For you to have an idea, I put a function on the page named.ejs that it validates if the user has already logged in 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 login, it goes to home.ejs Below is how 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>
    
31.08.2018 / 19:19