This is a error about function not defined - javascript

In my html file, I have defined onclick event for forgot password() function which is defined in another js file sigin.js but on live server it is giving error:
VM19 signin.html:20 Uncaught ReferenceError: forgotPass is not defined
at HTMLAnchorElement.onclick (VM19 signin.html:20:67)
This is my html code:
Signin
<img src="users.png">
<h2>Sign in</h2>
<input type="text" id="username" class="input-box" placeholder="username"><br>
<input type="email" id= "email" class="input-box" placeholder="email id"><br>
<input type="password" id="password" class="input-box" placeholder="passsword"><br>
forget password?
<button type="submit" id="signIn" class="signin-btn">Sign in</button>
<hr>
<p class="or" style="color: rgb(255, 0, 64);">Or sign in with</p>
<i class="fab fa-facebook-f"></i>
<i class="fab fa-instagram"></i>
<i class="fab fa-twitter"></i>
<i class="fab fa-linkedin-in"></i><br>
<p style="color: rgb(255, 0, 64);">Don't have an account? Create account</p>
</form>
</div>
//This is my js file:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
import { getDatabase,ref,update } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
import { getAuth, signInWithEmailAndPassword,sendPasswordResetEmail } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyDmNExTV5gaczHbcsrTXjNvab7vmug0rIw",
authDomain: "authentication-app-2de5b.firebaseapp.com",
databaseURL: "https://authentication-app-2de5b-default-rtdb.firebaseio.com",
projectId: "authentication-app-2de5b",
storageBucket: "authentication-app-2de5b.appspot.com",
messagingSenderId: "932491620237",
appId: "1:932491620237:web:5a2f2038c025dd3a8997c4"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const auth = getAuth();
var signIn = document.getElementById("signin-form");
signIn.addEventListener('submit',(e)=>{
e.preventDefault();
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var username = document.getElementById("username").value ;
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
const date = new Date();
update(ref(database,'users/'+ user.uid),{
last_login : date
})
alert("Sign in successfully!!");
document.getElementById("signin-form").reset();
// ...
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage);
});
})
function forgotPass(){
const email = document.getElementById("email").value;
sendPasswordResetEmail(email)
.then(() => {
// Password reset email sent!
// ..
alert("Password reset link sent to your email successfully!!");
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage);
// ..
})
}
I have tried a lot but I don't found any solution for this problem. Please try to find out the problem so that I can go ahead:)

You also have not passed in auth to your sendPasswordResetEmail method which will cause an API error.
It's odd that your debugger/IDE didn't pick up that you were missing an argument, perhaps it's because you're using inline JS.
It's always good to move JS into seperate files callable from the HTML file. You can do this with html script tags.

Related

How to solve 'Uncaught SyntaxError: Unexpected reserved word (at index.html:93:36)' in Firebase?

<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--<link href="index.css" rel="stylesheet" />-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<!--<script src="./src/index.js"></script>-->
<title>DB Test</title>
</head>
<body>
<a><h1>DB Test</h1></a>
<div class="input-box">
<input id="email" type="text" name="username" placeholder="email">
<label for="email">Email</label>
</div>
<div class="input-box">
<input id="password" type="password" name="password" placeholder="pw">
<label for="password">password</label>
</div>
<div class="input-box">
<input id="loc" type="text" name="loc" placeholder="loc">
<label for="loc">location</label>
</div>
<div class="input-box">
<input id="phone_num" type="text" name="phone_num" placeholder="phone_num">
<label for="phone_num">phone_num</label>
</div>
<div class="input-box">
<input id="JMT" type="text" name="JMT" placeholder="JMT">
<label for="JMT">JMT</label>
</div>
<input type="button" id="button" value="submit" onclick="newuser();">
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
import { getAuth, createUserWithEmailAndPassword } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
//import { getFirestore, collection, getDocs, addDoc } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-firestore.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
...
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth();
const loc = document.getElementById('loc').value;
const phone_num = document.getElementById('phone_num').value;
var JMT = document.getElementById('JMT').value.split(",");
var JMT_map = new Map();
for (var i = 0; i < JMT.length; i++){
JMT_map.set(JMT[i], 1)
}
window.newuser = () => {
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
console.log(password)
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
alert("Success")
location.replace('./test.html')
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert("Error")
})
try {
*const docRef = await addDoc(collection(db, "users")*, {
phone: phone_num,
position: loc,
JMT: JMT_map
});
console.log("Document written with ID: ", docRef.id);
} catch (e) {
console.error("Error adding document: ", e);
}
}
</script>
</body>
</html>
I use firebase now,and I want to make 'newuser' function work for authentication and add new data in firestore database. But 'Uncaught SyntaxError: Unexpected reserved word (at index.html:93:36)' occurs now, and 'index.html:42 Uncaught ReferenceError: newuser is not defined at HTMLInputElement.onclick' occurs. How to solve this problem?
The following should do the trick. As explained in my comment above, you need to chain the different Firebase asynchronous method calls (which return a Promise). (This technique is absolutely KEY when working with Firebase. I would kindly suggest you go through the documentation on Promises and chaining).
window.newuser = () => {
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
console.log(password)
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
// ... get loc, phone_number, etc.
return addDoc(collection(db, "users"), {
phone: phone_num,
position: loc,
JMT: JMT_map
});
// NOTE!!: you most probably want to create a Firestore user doc with the user Id as the doc Id... In this case use user.uid
})
.then((docRef) => {
console.log("Document written with ID: ", docRef.id);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorCode);
console.log(errorMessage);
});
}

Unable to write to firebase realtime database even though authentication is successful

I'm creating a sign up form using firebase auth and realtime database.
Here is the basic layout of the form (without CSS).
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-app.js";
import { getDatabase, set, ref, update , onValue } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-database.js";
import { getAuth, createUserWithEmailAndPassword, signInWithEmailAndPassword, onAuthStateChanged, signOut , GoogleAuthProvider, signInWithRedirect, getRedirectResult, TwitterAuthProvider } from "https://www.gstatic.com/firebasejs/9.4.0/firebase-auth.js";
// Your web app's Firebase configuration
const firebaseConfig = {
//CONFIDENTIAL
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const auth = getAuth();
signUp.addEventListener('click',(e) => {
var email = document.getElementById('signUpEmail').value;
var password = document.getElementById('signUpPass').value;
// var username = document.getElementById('username').value;
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
let dt = new Date();
set(ref(database, 'users/' + user.uid),{
// username: username,
email: email,
prem: false,
pday: dt.getDate(),
pmon: dt.getMonth(),
pyear: dt.getFullYear()
})
alert('Signup Successful!');
window.close();
// window.location.replace('index.html');
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
alert(errorMessage);
// ..
});
});
<h1 class='status'>signup</h1>
<input type="text" class="email" name="email" id="signUpEmail" placeholder="E-mail" />
<input type="password" class="password" name="password" id="signUpPass" placeholder="Password" />
<input type="submit" id='signUp' name="signUp" value="signUp" />
The Auth is happening successfully but the user details are not written to the realtime database.
I'm storing the following in the database:
User email
If they have premium subscription for my product (T/F)
Day when their premium ends
Month when their premium ends
Year when their premium ends
Where am I going wrong?
Writing data to the database (and reading data from it) is an asynchronous operation. Asynchronous here means that your main code continues to execute, while the operations runs in the background. But this also means that your window.close() in the main code executes before the database write completes, and in fact it seems to cancel that operation.
The solution is to wait for the database operation to complete before closing the window, similar to what you already do for createUserWithEmailAndPassword :
set(ref(database, 'users/' + user.uid),{
// username: username,
email: email,
prem: false,
pday: dt.getDate(),
pmon: dt.getMonth(),
pyear: dt.getFullYear()
}).then(() => { // 👈
alert('Signup Successful!');
window.close();
})

Set cookie with JWT - NodeJs and Javascript

I'm a bit lost in my own code right now, I need brightness.
I'm trying to set a cookie with JWT when I log in. Here is my code :
My route :
router.post('/signin', user.signIn);
My controller :
const jwtExpire = 3 * 23 * 60 * 60 * 1000
const createToken = (id) => {
return jwt.sign({ id }, process.env.TOKEN_SECRET, {
expiresIn: jwtExpire
})
}
module.exports.signIn = async (req, res) => {
const { email, password } = req.body
try {
const user = await UserModel.login(email, password)
const token = createToken(user._id)
res.cookie('jwt', token, { httpOnly: true, jwtExpire })
res.status(200).json({ user: user._id })
} catch (err) {
const errors = signInErrors(err)
res.status(200).json({ errors })
}
}
My form :
<form id="signin-block" style="display: block;" class="p-4 mx-auto">
<h2 class="text-center my-4 underline">Se connecter</h2>
<div class="input-group">
<input id="email" type="text" class="form-control" name="email" placeholder="E-mail">
</div>
<div class="input-group">
<input id="password" type="password" class="form-control" name="password"
placeholder="Mot de passe">
</div>
<button type="submit" class="btn btn-primary mt-4" id="submit">Me connecter</button>
</form>
My function to log in :
logInBlock.addEventListener('submit', function (e) {
e.preventDefault()
const email = e.target[0].value
const password = e.target[1].value
axios({
method: 'post',
url: 'http://localhost:5000/api/signin',
data: {
email: email,
password: password
}
}).then((res) => console.log(res))
})
With POSTMAN, the cookie is set. So something is missing is my own request, but I don't see what. Any idea ?
Are you doing this in different origins? Cookies will not be in request if origins are different, it is unsafe and can lead to attacks.
If yes, another way to do is to response your jwt from server, when ajax is responsed, store your jwt in cookie by client side, and use axios property to bring it in request header:
axios.defaults.headers.common['Authorization'] = yourJwt
See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

Firebase Authentication setup in Java Script

I am having a problem with my current firebase html and javascript setup that is leading to not getting users registered to my firebase database of users. I am not receiving any error alerts in the browser when I run the below code. I have also tried running the site by running 'firebase serve' and I am not getting any errors logged to the console.
The html source includes and javascript file are below. I have tested to make sure that I am able to access the username and password fields from the Document and that is working fine. Let me know if you need to see any additional information. Thank you!
Right after the Body tag in my html I include the following scripts:
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-auth.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="register.js"></script>
Then in my register.js file:
// Initialize Firebase
var config = {
apiKey: "mykey",
authDomain: "mydomain",
databaseURL: "myurl",
projectId: "myid",
storageBucket: "mybucket",
messagingSenderId: "mysenderid"
};
firebase.initializeApp(config);
$(document).ready(function(){
$("form").submit(function(){
var email = $('user').val();
var password = $('#password').val();
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(val) {
alert("Success!!");
console.log(val);
})
.catch(function(error) {
// Handle Errors here.
alert("ERROR");
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
}).success(function(json) {
console.log(json);
alert("TESTER");
})
// [END createwithemail]
});
});
A couple of remarks:
1/ For initialization you just need to do
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase.js"></script>
OR
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.3/firebase-auth.js"></script>
See https://firebase.google.com/docs/web/setup
2/ Don't call the submit method of your form. Just get the values of the email and password fields (e.g. var email = $('user').val();) and call the Firebase createUserWithEmailAndPassword(email, password) function as you do, without submitting the form.
Note that if you want to handle a succesful registration you should add a then(), as follows, since the function returns a promise (see doc here)
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function(val) {
//Success!!
console.log(val);
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
});
Add a success function callback and see the response
$("form").submit(function(){
var email = $('user').val();
var password = $('#password').val();
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
alert("ERROR");
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
}).success(function(json) {
console.log(json);
});
// [END createwithemail]
});

How to maintain Firebase Auth for multiple pages on the web?

I am using Firebase for a web application. The goal is to allow a familiar log-in/sign-up where the user signs up or logs in one one page, and upon successful authentication, is brought to the home page.
The flow would look something like this:
Log-in/Sign-up -> (allows access to) -> [Home, Profile, Search, Friends, etc.]
I am using Javascript (No AngularJs since I am unfamiliar with it entirely). The problem I am having is that once the user successfully logs in or signs up, their "user object" becomes null on using
window.location = 'home.html'
Here is the complete code. I am using the sample found Firebase for now for the authentication process, but the home.html is my doing:
<!DOCTYPE html>
<html>
<head>
<!--Bootstrap CSS CDN-->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!---jQuery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
/**
* Handles the sign in button press.
*/
function toggleSignIn() {
if (firebase.auth().currentUser) {
// [START signout]
firebase.auth().signOut();
// [END signout]
} else {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
// Sign in with email and pass.
// [START authwithemail]
firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode === 'auth/wrong-password') {
alert('Wrong password.');
} else {
alert(errorMessage);
}
console.log(error);
document.getElementById('quickstart-sign-in').disabled = false;
// [END_EXCLUDE]
});
// [END authwithemail]
window.location = '/1home.php'
}
document.getElementById('quickstart-sign-in').disabled = true;
}
/**
* Handles the sign up button press.
*/
function handleSignUp() {
var email = document.getElementById('email').value;
var password = document.getElementById('password').value;
if (email.length < 4) {
alert('Please enter an email address.');
return;
}
if (password.length < 4) {
alert('Please enter a password.');
return;
}
// Sign in with email and pass.
// [START createwithemail]
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/weak-password') {
alert('The password is too weak.');
} else {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
});
// [END createwithemail]
}
/**
* Sends an email verification to the user.
*/
function sendEmailVerification() {
// [START sendemailverification]
firebase.auth().currentUser.sendEmailVerification().then(function() {
// Email Verification sent!
// [START_EXCLUDE]
alert('Email Verification Sent!');
// [END_EXCLUDE]
});
// [END sendemailverification]
}
function sendPasswordReset() {
var email = document.getElementById('email').value;
// [START sendpasswordemail]
firebase.auth().sendPasswordResetEmail(email).then(function() {
// Password Reset Email Sent!
// [START_EXCLUDE]
alert('Password Reset Email Sent!');
// [END_EXCLUDE]
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// [START_EXCLUDE]
if (errorCode == 'auth/invalid-email') {
alert(errorMessage);
} else if (errorCode == 'auth/user-not-found') {
alert(errorMessage);
}
console.log(error);
// [END_EXCLUDE]
});
// [END sendpasswordemail];
}
/**
* Handles registering callbacks for the auth status.
*
* This method registers a listener with firebase.auth().onAuthStateChanged. This listener is called when
* the user is signed in or out, and that is where we update the UI.
*
* When signed in, we also authenticate to the Firebase Realtime Database.
*/
function initApp() {
// Listening for auth state changes.
// [START authstatelistener]
firebase.auth().onAuthStateChanged(function(user) {
// [START_EXCLUDE silent]
document.getElementById('quickstart-verify-email').disabled = true;
// [END_EXCLUDE]
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var refreshToken = user.refreshToken;
var providerData = user.providerData;
// [START_EXCLUDE silent]
document.getElementById('quickstart-sign-in-status').textContent = 'Signed in';
document.getElementById('quickstart-sign-in').textContent = 'Sign out';
document.getElementById('quickstart-account-details').textContent = JSON.stringify({
displayName: displayName,
email: email,
emailVerified: emailVerified,
photoURL: photoURL,
isAnonymous: isAnonymous,
uid: uid,
refreshToken: refreshToken,
providerData: providerData
}, null, ' ');
if (!emailVerified) {
document.getElementById('quickstart-verify-email').disabled = false;
}
// [END_EXCLUDE]
} else {
// User is signed out.
// [START_EXCLUDE silent]
document.getElementById('quickstart-sign-in-status').textContent = 'Signed out';
document.getElementById('quickstart-sign-in').textContent = 'Sign in';
document.getElementById('quickstart-account-details').textContent = 'null';
// [END_EXCLUDE]
}
// [START_EXCLUDE silent]
document.getElementById('quickstart-sign-in').disabled = false;
// [END_EXCLUDE]
});
// [END authstatelistener]
document.getElementById('quickstart-sign-in').addEventListener('click', toggleSignIn, false);
document.getElementById('quickstart-sign-up').addEventListener('click', handleSignUp, false);
document.getElementById('quickstart-verify-email').addEventListener('click', sendEmailVerification, false);
document.getElementById('quickstart-password-reset').addEventListener('click', sendPasswordReset, false);
}
window.onload = function() {
initApp();
};
</script>
</head>
<body>
<div class="jumbotron text-center">
</div>
<div class="container">
<div class="jumbotron">
<div class="row">
<div class="col-md-6">
<!--<img src="" style="width:500px; height:340px">-->
</div>
<div class="col-md-6">
<!-- Container for the demo -->
<div class="mdl-card mdl-shadow--2dp mdl-cell mdl-cell--12-col mdl-cell--12-col-tablet mdl-cell--12-col-desktop">
<div class="mdl-card__title mdl-color--light-blue-600 mdl-color-text--white">
<h2 class="mdl-card__title-text">Sign Up</h2>
</div>
<div class="mdl-card__supporting-text mdl-color-text--grey-600">
<p>Enter an email and password below and either sign in to an existing account or sign up</p>
<input class="mdl-textfield__input" style="display:inline;width:auto;" type="text" id="email" name="email" placeholder="Email"/>
<br /><br />
<input class="mdl-textfield__input" style="display:inline;width:auto;" type="password" id="password" name="password" placeholder="Password"/>
<br/><br/>
<button disabled class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-sign-in" name="signin">Sign In</button>
<button class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-sign-up" name="signup">Sign Up</button>
<button class="mdl-button mdl-js-button mdl-button--raised" disabled id="quickstart-verify-email" name="verify-email">Send Email Verification</button>
<button class="mdl-button mdl-js-button mdl-button--raised" id="quickstart-password-reset" name="verify-email">Send Password Reset Email</button>
<!-- Container where we'll display the user details -->
<div class="quickstart-user-details-container">
<!--Firebase--> sign-in status: <span id="quickstart-sign-in-status">Unknown</span>
<div><!--Firebase--> auth <code>currentUser</code> object value:</div>
<pre><code id="quickstart-account-details">null</code></pre>
</div>
</div><!---->
</div>
</div>
</div>
</div>
<!--Bootstrap Js CDN-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!--Firebase Initialization-->
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "XXXXXXXXXXXXXXXXX",
authDomain: "XXXXXXXXXXXXXX",
databaseURL: "XXXXXXXXXXXXX",
storageBucket: "XXXXXXXXXXXXXXXX",
};
firebase.initializeApp(config);
</script>
</body>
</html>
Additionally, the page that is auth screen redirects to is monitoring the auth state with onAuthStateChanged. This is where using console.log(user); returns null, although using console.log("Attempted sign in); is printed. I copied the initApp function from the Firebase Auth sample. Perhaps I am using it in the wrong place?
<!DOCTYPE html>
<html>
<head>
<meta name ="viewport" content ="width=device-width, initial-scale=1.0">
<!--Bootstrap CSS CDN-->
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!---jQuery CDN-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="styles.css">
<link rel="stylesheet" href="animations.css">
<!--Firebase-->
<script type="text/javascript">
function initApp() {
// Listening for auth state changes.
// [START authstatelistener]
firebase.auth().onAuthStateChanged(function(user) {
// [START_EXCLUDE silent]
// [END_EXCLUDE]
console.log("Attempted Sign in");
console.log(user);
if (user) {
// User is signed in.
console.log("Attempted Sign in successful");
var displayName = user.displayName;
var email = user.email;
var emailVerified = user.emailVerified;
var photoURL = user.photoURL;
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var refreshToken = user.refreshToken;
var providerData = user.providerData;
console.log(uid);
console.log(displayName);
console.log(email);
console.log(photoURL);
// [START_EXCLUDE silent]
if (!emailVerified) {
}
// [END_EXCLUDE]
} else {
// User is signed out.
// [START_EXCLUDE silent]
// [END_EXCLUDE]
}
// [START_EXCLUDE silent]
// [END_EXCLUDE]
});
// [END authstatelistener]
}
window.onload = function() {
initApp();
// Register the callback to be fired every time auth state changes
ref.onAuth(function(authData) {
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
} else {
console.log("User is logged out");
}
});
};
</script>
So, to re-iterate the issue and goal: I want to be able to authenticate a user on this page (the code above represents a login/signup screen), and then send them a set of pages that loads content based on their Firebase ID.
I think you're calling your redirect too early. Try placing it in the onAuthStateChanged callback. If you redirect before your local Firebase client has had time to register the authentication change, your session won't have time to get stored in localStorage, so there won't be any session when you arrive at your destination. The login process is effectively short-circuited.
Try something like
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
window.location = '/1home.php';
}
}

Categories