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