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)});
Related
I am storing the username and password in an array(datas),,then after registering and logging in, I am only able to have the username appear in the login page.. How can i make the username appear in all of my html pages?Like storing it in a session variable so i could have the username in all of my other pages. Thank you!
<script>
let datas = [];
const addData = (ev) => {
ev.preventDefault();
let data = {
username: document.getElementById('rusername').value,
password: document.getElementById('rpassword').value
}
datas.push(data);
document.forms[0].reset();
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById('register_button').addEventListener('click', addData);
});
function isUserValid(e) {
e.preventDefault();
var username = document.getElementById('lusername').value;
var password = document.getElementById('lpassword').value;
var found_user = datas.find(d => d.username === username && d.password === password);
if (found_user) {
document.getElementsByClassName('loguser')[0].innerHTML = found_user.username;
}
}
document.getElementById("login_button").addEventListener("click", isUserValid);
</script>
<body>
<div class="loguser">
User
</div>
<div class="wrapper">
<div class="login_box">
<div class="login_header">
<img src="images/alimama.png" alt=""> <br> Login or Register!
</div>
<div id="login">
<form action="" method="POST">
<input id="lusername" type="text" name="lusername" placeholder="Username" required>
<br>
<input id="lpassword" type="password" name="lpassword" placeholder="Password">
<br>
<input type="submit" id="login_button" name="login_button" value="Login">
<br>
Need an account? Register here!
</form>
</div>
<div id="register">
<form action="" method="POST">
<input id="rusername" type="text" name="rusername" placeholder="Username" required>
<br>
<input id="rpassword" type="password" name="rpassword" placeholder="Password" required>
<br>
<input id="register_button" type="submit" name="register_button" value="Register">
<br>
Already have an account? Sign in here!
</form>
</div>
</div>
</body>
You can use your browser's localstorage to store the values and retrieve them on other pages. Another option would be to use cookies, but I believe this would be a little more complicated.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
Here's the documentation that talks a little more about. I think this will help you =)
An important point is that this will be saved in the user's browser, if you need this data, I recommend using a database
Use localStorage, is really simple. To set the value use this:
window.localStorage.setItem('actualUserName', document.getElementById('lusername').value);
And to retrieve the value use this:
window.localStorage.getItem('actualUserName');
More info: https://developer.mozilla.org/es/docs/Web/API/Window/localStorage
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.
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>
I have the following page with a javascript file, when the user enters the wrong username/password the message "wrong username password" is output to page; however, the message does not stay on the page. For some reason the page gets refresh.
<html>
<head>
<script src="letmein.js"></script>
</head>
<body>
<h1 id="h1">JavaScript Test Page</h1>
<p id="p">Click the link to login into the application</p>
<p>login</p>
<form id="myForm" name="myForm" onSubmit="letmein();">
<p>username:
<input type="text" name="username">
</p>
<p>password:
<input type="text" name="password">
</p>
<input type="submit" value="Login">
</form>
<p id="hidden"></p>
clear
</body>
</html>
javascript file
var username = "admin";
var password = "letmein";
var counter = 0;
//login form authentication
function letmein() {
var formUser = document.forms['myForm']['username'].value;
var formPass = document.forms['myForm']['password'].value;
if(formUser === username && formPass === password) {
window.open("file:///home/jorge/usersearch.html");
}
counter++;
document.getElementById("hidden").innerHTML = "Wrong username or password!"
if(counter === 3) {
alert("Access Denied!");
}
}
//close window
function closeWindow() {
close();
};
I think clicking the button submits the form. You need to return false on onSubmit in order to avoid submitting the form.
<html>
<head>
<script src="letmein.js"></script>
</head>
<body>
<h1 id="h1">JavaScript Test Page</h1>
<p id="p">Click the link to login into the application</p>
<p>login</p>
<form id="myForm" name="myForm" onSubmit="letmein(); return false;">
<p>username:
<input type="text" name="username">
</p>
<p>password:
<input type="text" name="password">
</p>
<input type="submit" value="Login">
</form>
<p id="hidden"></p>
clear
</body>
</html>
You need to stop the form's default action. For example:
function letmein(e) {
if(validationFails) {
e.preventDefault(); //this will stop the form from submitting
}
}
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>