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';
}
}
Related
I'm logging in users via firebase-auth and need to pass their user uid to the redirected page. How can the user-uid be passed?
I've tried using the docs on firebase auth but cant quite solve it
loginForm.addEventListener('submit', (e) => {
e.preventDefault();
const email = loginForm['email'].value;
const password = loginForm['password'].value;
console.log(email, password);
firebase.initializeApp(config);
firebase.auth().signInWithEmailAndPassword(email, password)
.then(cred => {
if(email ==='admin#mombasa.com' && password ==='adminMomb') {
window.location = './admin-map.php';
}
else if(email ==='admin#nairobi.com' && password ==='adminNai') {
window.location = './admin-map.php';
}
else if(email ==='admin#eldoret.com' && password ==='adminEld') {
window.location = './admin-map.php';
}
else firebase.auth().onAuthStateChanged(function(user) {
window.user = user;
console.log('logged in ', user);
window.location = './dailyreports.php';
console.log('logged in ', user);
});
}).catch(
function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
console.log(errorMessage, errorCode);
}
)
;
});
On navigation to the next page, I expected to see the user-uid output in the console but it returns blank
Instead of passing the UID, it's better to pick up the state in the next page with a so-called authentication state listener.
As shown in the documentation on getting the currently signed in user:
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
} else {
// No user is signed in.
}
});
There will be no delay in picking up the user account this way on the new page, as the Firebase SDK will be able to restore the state from the information it stored in local storage.
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]
});
I'm trying to add Firebase ui auth on my app using Google's official documentation on Github.
The email sign in is working fine, but I'm getting issue with the phone sign in option.
On clicking the Sign in with phone and entering the 6 digit code I get on my number, I'm not able to sign up or sign in.
The round loading circle spins endlessly and doesn't redirect me to the signInSuccessUrl defined in my main.js.
The error I get in the console is this:
firebaseui.js:82 Uncaught TypeError: Cannot read property 'call' of undefined
at Ca (firebaseui.js:82)
at Fl (firebaseui.js:323)
at firebaseui.js:324
at firebaseui.js:281
at El.<anonymous> (firebaseui.js:238)
at oe (firebaseui.js:140)
at ne (firebaseui.js:139)
at ni (firebaseui.js:219)
at li.h (firebaseui.js:219)
at le (firebaseui.js:136)
Ca # firebaseui.js:82
Fl # firebaseui.js:323
(anonymous) # firebaseui.js:324
(anonymous) # firebaseui.js:281
(anonymous) # firebaseui.js:238
oe # firebaseui.js:140
ne # firebaseui.js:139
ni # firebaseui.js:219
li.h # firebaseui.js:219
le # firebaseui.js:136
he # firebaseui.js:137
b # firebaseui.js:134
My index.html
<!DOCTYPE html>
<html>
<head>
<title>Site Web flow</title>
<link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/2.6.0/firebaseui.css" />
</head>
<body>
<h1>Site Web flow</h1>
<div id="firebaseui-auth-container"></div>
<hr>
<div>
<div id="loader">Loading...</div>
<div id="sign-in-status"></div>
<div id="sign-in"></div>
<div id="account-details"></div>
<button id="signOutButton">Signout</button>
</div>
<script src="https://cdn.firebase.com/libs/firebaseui/2.6.0/firebaseui.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.9.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.9.1/firebase-firestore.js"></script>
<script src="main.js"></script>
</body>
</html>
My main.js file:
let config = {
apiKey: '##',
authDomain: '##',
projectId: '##'
};
firebase.initializeApp(config);
const db = firebase.firestore();
// const auth = firebase.auth();
let uiConfig = {
signInOptions: [
{
provider: firebase.auth.EmailAuthProvider.PROVIDER_ID,
requireDisplayName: true
},
{
provider: firebase.auth.PhoneAuthProvider.PROVIDER_ID,
defaultCountry: 'IN'
}
],
signInSuccessUrl: './success.html',
tosUrl: '#',
callbacks: {
signInSuccess: (currentUser, credential, redirectUrl) => {
return true;
},
signInFailure: (error) => {
return handleUIError(error);
},
uiShown: () => {
document.getElementById('loader').style.display = 'none';
}
}
};
// Initialize the FirebaseUI Widget using Firebase.
let ui = new firebaseui.auth.AuthUI(firebase.auth());
// The start method will wait until the DOM is loaded.
ui.start('#firebaseui-auth-container', uiConfig);
ui.disableAutoSignIn();
initApp = function() {
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
let displayName = user.displayName;
let email = user.email;
let emailVerified = user.emailVerified;
let photoURL = user.photoURL;
let uid = user.uid;
let phoneNumber = user.phoneNumber;
let providerData = user.providerData;
user.getIdToken().then(function(accessToken) {
document.getElementById('sign-in-status').textContent = 'Signed in';
document.getElementById('sign-in').textContent = 'Sign out';
document.getElementById('account-details').textContent = JSON.stringify({
displayName: displayName,
email: email,
emailVerified: emailVerified,
phoneNumber: phoneNumber,
photoURL: photoURL,
uid: uid,
accessToken: accessToken,
providerData: providerData
}, null, ' ');
});
} else {
// User is signed out.
document.getElementById('sign-in-status').textContent = 'Signed out';
document.getElementById('sign-in').textContent = 'Sign in';
document.getElementById('account-details').textContent = 'null';
}
}, function(error) {
console.log(error);
});
};
window.addEventListener('load', function() {
initApp()
});
document.getElementById('signOutButton').addEventListener('click', (e) => {
e.preventDefault();
firebase.auth().signOut().then(() => {
console.log('Signed out');
})
})
I do have enabled the sign in with email and phone in my Firebase console. Can anyone help?
update to latest firebaseui 2.6.1
npm install firebaseui#2.6.1
OR
npm install firebaseui#latest
OR
npm install firebaseui#latest --save
There was a bug in Phone number sign-in flow in FirebaseUI 2.6.0. https://github.com/firebase/firebaseui-web/issues/314. We have a fix and released 2.6.1. Anyone experiencing the same issue, please update firebaseUI to latest version 2.6.1.
I'm using Firebase at a school project and I'm having the same problem a while... I have looked at various sites but I can't find anyone with the same problem...
The User authentication is working correctly, but the problem is with saving the user data in the database.
I have two available ways to authenticate:
Email and password;
Facebook.
With email and password, the data is written successfully in the database, and I'm using the following JavaScript code:
function signUp(){
//Get DOM data
const email = String(document.getElementById('TXTEmail').value);
const pass = String(document.getElementById('TXTPassword').value);
const name = String(document.getElementById('TXTNome').value);
const gender = document.registo.sexo.value;
const auth = firebase.auth();
var promise = auth.createUserWithEmailAndPassword(email,pass);
promise.catch(e => console.log(e.message));
firebase.database().ref('users/' + firebase.auth().currentUser.uid).set({
name : name,
email : email,
gender : gender,
uid: firebase.auth().currentUser.uid
});
}
However, when using the function of facebook I can't save the data, I can only authenticate the user, and the code I'm using is as follows:
function signUpFacebook(){
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithRedirect(provider);
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
// This gives you a Facebook Access Token. You can use it to access the Facebook API.
var token = result.credential.accessToken;
}
// The signed-in user info.
var user = result.user;
const name = user.displayName;
const email = user.email;
const photo = user.photoURL;
if(user != 0) {
firebase.database().ref('users/' + user.uid).set({
name: nome,
email: email,
photo: photo,
uid: user.uid
});
}
//Tests only
if(user != 0){
console.log("name: "+user.displayName);
console.log("email: "+user.email);
console.log("photoUrl: "+user.photoURL);
console.log("uid: "+user.uid);
}
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
});
}
And I get this output on my console:
Console output.
name: Rafael Veloso
email: rafael****#gmail.com
photoUrl: scontent.xx.fbcdn.net/v/t1.0-1/s100x100/…
uid: **HY43Tl******KoO6OhZjG****
Also, my database.rules.json is:
{
"rules": {
".read": true,
".write": true
}
}
Does anyone know what is the problem that I'm having?
Thank you.
with the help of the Firebase support I managed to solve my problem :)
First, created a script within the .html document like that:
<script>
document.getElementById('btnFacebook').addEventListener('click', signUpFacebook, false);
function signUpFacebook(){
var provider = new firebase.auth.FacebookAuthProvider();
firebase.auth().signInWithRedirect(provider);
}
function createNewPost(name, email, photo, uid) {
firebase.database().ref('users/' + uid).set({
name: name,
email: email,
photo: photo,
uid: uid
});
}
firebase.auth().getRedirectResult().then(function(result) {
if (result.credential) {
var token = result.credential.accessToken;
}
// The signed-in user info.
if(user != null) {
console.log("name: "+user.displayName);
console.log("email: "+user.email);
console.log("photoUrl: "+user.photoURL);
console.log("uid: "+user.uid);
}
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
});
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
var name = user.displayName;
var email = user.email;
var photo = user.photoURL;
var uid = user.uid;
createNewPost(name, email, photo, uid);
console.log("name: "+user.displayName);
console.log("email: "+user.email);
console.log("photoUrl: "+user.photoURL);
console.log("uid: "+user.uid);
}
});
With just that, I still wasn't able to add the user data to the Realtime Database, so I changed my "imports", I was with this:
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.0/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script>
and only when I changed to the following I was able to save the user data in the Database:
<!-- <script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/3.5.0/firebase-messaging.js"></script>-->
<script src="https://www.gstatic.com/firebasejs/3.2.1/firebase.js"></script>
But I find that strange, can anyone help and explain me why that worked out?
How do you implement forget password method in my method. I am creating a HTML project which is due soon. My code:
function toggleSignIn() {
if (!firebase.auth().currentUser) {
// [START createprovider]
var provider = new firebase.auth.GoogleAuthProvider();
// [END createprovider]
// [START addscopes]
provider.addScope('https://www.googleapis.com/auth/plus.login');
// [END addscopes]
// [START signin]
firebase.auth().signInWithPopup(provider).then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
// [START_EXCLUDE]
document.getElementById('quickstart-oauthtoken').textContent = token;
// [END_EXCLUDE]
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// [START_EXCLUDE]
if (errorCode === 'auth/account-exists-with-different-credential') {
alert("You have already signed up with a different auth provider for that email.");
// If you are using multiple auth providers on your app you should handle linking
// the user's accounts here.
}
else if (errorCode === 'auth/auth-domain-config-required') {
alert("An auth domain configuration is required");
}
else if (errorCode === 'auth/cancelled-popup-request') {
alert("Popup Google sign in was canceled");
}
else if (errorCode === 'auth/operation-not-allowed') {
alert("Operation is not allowed");
}
else if (errorCode === 'auth/operation-not-supported-in-this-environment') {
alert("Operation is not supported in this environment");
}
else if (errorCode === 'auth/popup-blocked') {
alert("Sign in popup got blocked");
}
else if (errorCode === 'auth/popup-closed-by-user') {
alert("Google sign in popup got cancelled");
}
else if (errorCode === 'auth/unauthorized-domain') {
alert("Unauthorized domain");
}
else {
console.error(error);
}
// [END_EXCLUDE]
});
// [END signin]
} else {
// [START signout]
firebase.auth().signOut();
// [END signout]
}
// [START_EXCLUDE]
document.getElementById('quickstart-sign-ing').disabled = false;
// [END_EXCLUDE]
}
Here is a link to give you guidance:
https://firebase.google.com/docs/auth/web/manage-users#set_a_users_password
Please can you help me
To implement a forgot password button, you have to call:
firebase.auth().sendPasswordResetEmail('user#example.com')
Check the documentation for more details:
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#sendPasswordResetEmail
The easiest way to implement recover forgot password functionality is to call
import { AngularFireAuth } from "#angular/fire/auth";
constructor(
public afAuth: AngularFireAuth
) { }
// Reset Forggot password
ForgotPassword(passwordResetEmail) {
return this.afAuth.auth.sendPasswordResetEmail(passwordResetEmail)
.then(() => {
window.alert('Password reset email sent, check your inbox.');
}).catch((error) => {
window.alert(error)
})
}
To implement firebase reset you first need to send email to the user and for that we use sendPasswordResetEmail method. after that if user gonna click on the email, it will be redirected to a default page provided by firebase from there user can reset their password.
But if you want to have custom page for the password reset you can do that too, to do that you need to change the action url in the email template of your firebase project then you need to setup that custom action url, for this you can read this offical doc page: https://firebase.google.com/docs/auth/custom-email-handler?hl=en&authuser=0