If statement re-direct not working as expected - javascript

I'm trying to learn javascript through dummy scenarios, the below will not be used in a live context. All of the html pages are on my home server which is why i havent used http:// etc in the link.
I'm trying to have the below code take me to the "index" page if I type in the correct username and password and remain on the "home" page if I type it incorrectly but with an alert stating "Invalid Login". If I type in the correct username and password i'm redirected correctly however I'm also redirected to the index page if I enter in an incorrect username/password after the alert is correctly triggered.
How can I stop the index page loading for the wrong username/password? I'm sure its probably something simple i'm missing!
This is the html of the homepage
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<div id="container">
<div id="loginbox">
<form id="login" action="home.html">
Username: <input type="text" name="user" id="user"><br>
Password: <input type="password" name="password" id="password"><br>
<input type="submit" value="Login" onclick="checkUserName()">
</form>
</div>
</div>
and this is the script
function checkUserName() {
var User = document.getElementById("user").value;
var Password = document.getElementById("password").value;
if (User === "user123" && Password === "password123") {
window.location = "index.html";
}
else {
alert("Invalid Login");
}
}
Cheers!

You dont want to submit the form in this case. You just need to invoke the js function on click of login. So use a normal button instead a submit.
<button onclick="checkUserName()">login</button>
When you use a submit button, the form will get submitted unless you are not preventing the default action by e.preventDefault() or by returning false from the js function being called
function checkUserName() {
var User = document.getElementById("user").value;
var Password = document.getElementById("password").value;
if (User === "user123" && Password === "password123") {
window.location = "index.html";
}
else {
alert("Invalid Login");
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
</head>
<body>
<div id="container">
<div id="loginbox">
<form id="login" action="home.html">
Username: <input type="text" name="user" id="user"><br>
Password: <input type="password" name="password" id="password"><br>
<button onclick="checkUserName()">login</button>
</form>
</div>
</div>

Related

firebase.auth().onAuthStateChanged not executed after sign-in?

I have created users on firebase by using:
the Firebase Admin SDK (in python). The users show up in the firebase console.
Now I am trying to log the user in using javascript on a login page. However, when I run the code shown below it always ends up in the else loop in my script, which I think indicates that the the user is not logged in.
The desired behavior is:
User enters email/password, they submit form, it logs them in, and then it redirects them to the index page. Instead it doesn't do anything.
<!doctype html>
<html lang="en">
<head>
<script src="https://www.gstatic.com/firebasejs/ui/4.5.1/firebase-ui-auth.js"></script>
<link type="text/css" rel="stylesheet" href="https://www.gstatic.com/firebasejs/ui/4.5.1/firebase-ui-auth.css" />
</head>
<body>
<script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-analytics.js"></script>
<script>
const firebaseConfig = {
//my stuff here
};
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script src="https://www.gstatic.com/firebasejs/7.15.1/firebase-auth.js"></script>
<div class="container">
<h2>Sign In</h2>
<form id="loginform" action="" method="post">
<div class="form-group">
<label for="email">Email</label> <input class="form-control" id="email" name="email" required="required" type="text" value="cameron.snow#gmail.com">
</div>
<div class="form-group">
<label for="password">Password</label> <input class="form-control" id="password" name="password" required="required" type="password" value="">
</div>
<div class="form-group">
<input class="btn btn-primary" id="submit" name="submit" type="submit" value="Login">
</div>
</form>
<script>
document.getElementById('submit').addEventListener('click', loginUser);
function loginUser(){
let email = document.getElementById('email').value;
let password = document.getElementById('password').value;
firebase.auth().signInWithEmailAndPassword(email, password).catch(e=>{
alert(e)
});
};
firebase.auth().onAuthStateChanged(user=>{
if(user){
console.log(user)
user.getIdToken().then(function (token) {
//save the token in a cookie
document.cookie = "token=" + token;
window.location.href = "/";
});
} else{
console.log("What up dude?");
}
});
</script>
</div>
</body>
</html>
*edit:
I have checked that in the script that my email and password variables are working correctly. I have also checked that the:
firebase.auth().signInWithEmailAndPassword(email, password).catch(e=>{
alert(e)});
piece is working as well and the return is what I expect... so the issue has to be in the onAuthStateChanged() part.
You shouldn't add window.location.href = "/"; in the onAuthStateChanged() as that will create an infinite loop of re-rendering into the index page.
Instead, you should redirect to the index page directly after a successful login process
firebase.auth().signInWithEmailAndPassword(email, password).then(()=> {
window.location.href = "/";
}).catch(e=>{
alert(e)});

Validating login page - return to homepage if password is correct, if not stay on the same page

I have set up a registration page where the details are all saved to local storage in the browser. When the user is told to login using the registered details, they must be redirected to the homepage if the validation is successful.
Validation is working fine and i am getting system feedback if the password is wrong for example. I am not quite sure how i can be taken to the homepage ONLY if the password is correct.
Full code below
<!DOCTYPE html>
<html>
<head>
<link href ="styles.css" type = "text/css" rel="stylesheet">
<title>CSV File to HTML Table Using AJAX jQuery</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<!-- Header-->
<div id="header">
<button type="button" class="button">Basket</button>
</div>
<!-- Main Login Form-->
<div class="SignLog"><h2>Sign up or Log in</h2></div>
<body onload="checkLogin()">
<div id="loginPara" class="login">
<form id="login" action = index.html onsubmit="return false">
<input type="text" placeholder="Enter Email Address" name="userid" id="emailin"><br>
<input type="password" placeholder="Create a password" name="pswrd" id=passwordin><br>
<input type="button" onclick="login()" value="Login" id="loginbutton"/>
<p>-------------------------- or----------------------------</p>
<input type="button" value="Register" id="registerbutton"/>
<br>
<p>By continuing you agree to our <a>T&Cs</a>. Please also check out our <a>Privacy Policy</a>. We use your data to offer you a personalised experience and to better understand and improve our services. For more information <a>see here</a>.</p>
</form>
<div id="loginFailure" style="color:red;"><p></p>
</div>
</div>
<!-- LOCAL STORAGE IS CHECKED TO SEE IF USER IS REGISTERED.-->
<script>
function checkLogin() {
if(localStorage.loggedinUsrEmail !== undefined) {
var usrObj = JSON.parse(localStorage[localStorage.loggedinUsremail]);
document.getElementById("loginPara").innerHTM = usrObj.firstName + " logged in."
}
}
function login() {
var email = document.getElementById("emailin").value;
if(localStorage[email] === undefined){
document.getElementById("loginFailure").innerHTML = "Email not recognized" ;
return;
}
else{
var usrObj = JSON.parse(localStorage[email]);
var password = document.getElementById("passwordin").value;
if(password === usrObj.password) {
document.getElementById("loginPara").innerHTML =usrObj.firstname + " logged in.";
document.getElementById("loginFailure").innerHTML = "";
localStorage.loggedinUsrEmail =usrObj.email;
}
else{
document.getElementById("loginFailure").innerHTML = "Password incorrect.";
}
}
}
</script>
</body>
To redirect you can use:
if (password === usrObj.password) {
window.location = "https://example.com";
}
Please be aware, that checking passwords in the browser gives you no security.

Javascript window.open works but window.location does not

I'm working on a simple login page. When the user types in the correct username and password it redirects them to another page. So far I have tried:
window.location, window.location.replace window.href and window.open the only one that works is window.open, however I'm trying to make is so it does not open a newtab, it just redirects them to another page.
Html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="master.css">
<title>Day Four</title>
</head>
<body>
<h1>Log In</h1>
<form onsubmit="valid()">
<label for="username">Username:</label>
<input id = 'user-name' type="text" name="" value="" required>
<label for="password">Password:</label>
<input id = 'pass-word' type="password" name="" value="" required>
<input id = 'log-in'type="submit" name="" value="Log In">
</form>
</div>
</body>
<script src="mainJs.js" charset="utf-8"></script>
</html>
JS
function valid(){
var username = document.querySelector('#user-name').value;
var password = document.querySelector('#pass-word').value;
if(username === 'test' && password === '1'){
window.open("gradebook.html")
}else{
alert("Wrong username or password")
}
}
Edit: I know it's not secure. I put the code that works window.open("gradebook.html") seeing how the other ones don't do anything.
I also don't get any errors in the console when using the other ones.
It looks like the problem was with the form tags. If I remove the form tags everything starts working as it should.
All you need to do is set window.location to the new URL.
document.querySelector("button").addEventListener("click", function(){
window.location = "http://cnn.com";
});
<button>Click Me</button>

More Simple Password System Stuff

Sorry guys, first time playing around with this. Here's the HTML:
<!DOCTYPE html>
<html>
<head>
<title>SuM BUTtonsS DOe</title>
<link rel="stylesheet" href="buttons.css"/>
</head>
<body>
<p>Please enter the password</p>
<form id="enter" onSubmit="javascript:passCheck()">
<input id="password" type="password" placeholder="Password">
</form>
<p id="incorrect"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
}
}
</script>
</body>
</html>
When I enter the wrong password, INCORRECT PASSWORD comes up, but only for a fraction of a second. Then it's gone again. No idea why.
UPDATE:
<!DOCTYPE html>
<html>
<head>
<title>SuM BUTtonsS DOe</title>
<link rel="stylesheet" href="buttons.css"/>
</head>
<body>
<p>Please enter the password</p>
<form id="enter" onSubmit="javascript:passCheck()">
<input id="password" type="password" placeholder="Password">
</form>
<p id="incorrect"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
return false;
}
}
</script>
</body>
</html>
On submit, the form will trigger the default action, which in this case is to submit the contents to the same page (for lack of an action property).
So what you're seeing is the JavaScript runs and changes the style to show the error message, then the page reloads.
To ensure the page doesn't reload put return false at the end of passCheck. Better would be to use addEventListener and event.preventDefault(), but that's a little bit more involved.
<p>Please enter the password</p>
<form id="enter" onSubmit="passCheck(); return false;">
<input id="password" type="password" placeholder="Password">
<input type="submit" value="Submit"/>
</form>
<p id="incorrect" style="display: none"><em>INCORRECT PASSWORD</em></p>
<script type="text/javascript">
function passCheck() {
var input = document.getElementById('password').value;
if (input == 'herro') {
window.alert("IT WORKS!!");
}
else {
var incorrect = document.getElementById('incorrect');
incorrect.style.display = "block";
}
}
</script>

How to adapt current code to run without using a form?

How would I adapt this code to run without using the form, but the prompt() method instead? By including a prompt instead of a form to ask for user input.
<html>
<head>
<title>Login page</title>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt; color:#00FF00;>Simple Login Page</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form)/*function to check userid & password*/ {
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
window.open('target.html')/*opens the target page while Id & password matches*/
}
else {
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
Thanks!

Categories