I have an app which is written in HTML, CSS, Javascript. I am able to login using Google Authentication. I use
window.location = '/home.html'
for redirecting from index.html to home.html. Home.html has 5 list item menu options. However, clicking one specific list item menu displays index.html for a brief amount of time (which it should not be doing).
Here is the authentication JavaScript code.
function google_login_in(){
var provider = new firebase.auth.GoogleAuthProvider();
provider.addScope('https://www.googleapis.com/auth/plus.login');
firebase.auth().signInWithPopup(provider).then(function(result) {
var token = result.credential.accessToken;
var user = result.user;
}).catch(function(error) {
var errorCode = error.code;
var errorMessage = error.message;
var email = error.email;
var credential = error.credential;
});
}
function print_user(user) {
user.providerData.forEach(function (profile) {
console.log("Sign-in provider: "+profile.providerId);
console.log(" Provider-specific UID: "+profile.uid);
console.log(" Name: "+profile.displayName);
console.log(" Email: "+profile.email);
console.log(" Photo URL: "+profile.photoURL);
});
}
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
print_user(user);
window.location = '/home.html'
} else {
google_login_in();
}
});
Any help is greatly appreciated.
<li><a class="Baskets" href="#Baskets" onClick="document.getElementById('BasketsContent')
.style.display='block';document.getElementById('CalendarContent')
.style.display='none';document.getElementById('BrowserContent')
.style.display='none';document.getElementById('AnalyticsContent')
.style.display='none';document.getElementById('SettingsContent')
.style.display='none';document.getElementById('UpgradeContent')
.style.display='none';document.getElementById('ShareContent')
.style.display='none';">
<img class="icon1" src="./images/basket.png">
<i class="baskets"></i>Baskets</a>
</li>
use window.location.href, this will help you to navigate to the file
for example
window.location.href = 'home.html'
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.
Using createUserWithEmailAndPassword function of firebase I am able to sign users up but how to add extra information such as display name and picture URL?
This is what I have done.
const signup = document.querySelector('#signup-form');
signup.addEventListener('submit', e=>{
e.preventDefault();
//get user info
const first_name = signup['firstname'].value;
const last_name = signup['lastname'].value;
const email = signup['email1'].value;
const password = signup['pswd1'].value;
//sigup the user
firebase.auth().createUserWithEmailAndPassword(email, password).then(()=>{
firebase.auth().onAuthStateChanged(function(user){
if(user){
user.updateProfile({
displayName: first_name
})
}
})
signup.reset();
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
// ...
});
});
Once you have created the user, you can access user object provided by firebase. Using its updateProfile function, you can pass an object containing the properties you want the user object to have, like the code below:
var user = firebase.auth().currentUser;
user.updateProfile({
displayName: "Jane Q. User",
photoURL: "https://example.com/jane-q-user/profile.jpg"
}).then(function() {
// Update successful.
}).catch(function(error) {
// An error happened.
});
This worked for me.
firebase.auth().createUserWithEmailAndPassword(email, password).then(cred=>{
cred.user.updateProfile({
displayName: first_name + " " + last_name
})
})
.catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
window.alert("Error: " + errorMessage);
// ...
});
Here is a preview of what is happening
The login with google popup is taking too long to load (>2s)
This is causing a bounce rate problem for our site.
Notice that the popup stays on the url about: blank for quite some time.
Here are some tech specs
This test is run on a 100mbps fiber connection with <9ms ping
Site is powered by angular
Browser is chrome
Firebase Imports:
<script src="https://www.gstatic.com/firebasejs/6.4.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/6.4.1/firebase-auth.js"></script>
Code used to trigger the popup:
declare var firebase: any;
this.googleProvider = new firebase.auth.GoogleAuthProvider();
this.googleProvider.addScope('email');
this.googleProvider.addScope('profile');
loginWithGoogle() {
const that = this;
firebase.auth().signInWithPopup(this.googleProvider).then(function (result) {
const GoogleToken = result.credential.accessToken;
}).catch(function (error) {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const credential = error.credential;
});
}
The remainder of the login process is going smoothly.
Can someone suggest any way we can speed this up ?
Perhaps by preloading the google and facebook login pages before clicking the login button ?
#FrankvanPuffelen
This is what we did to speed up,
added native google signin imports in index.html
<script src="https://apis.google.com/js/platform.js"></script>
<meta name="google-signin-cookiepolicy" content="single_host_origin">
<meta name="google-signin-scope" content="profile email">
then in login component,
declare var gapi: any;
ngOnInit() {
gapi.load('auth2', function () {
gapi.auth2.init({
client_id: "enter-client-id-here"
});
});
}
loginWithGoogle() {
gapi.auth2.getAuthInstance().signIn().then(googleUser => {
const credential = firebase.auth.GoogleAuthProvider.credential(
googleUser.getAuthResponse().id_token);
firebase.auth().signInWithCredential(credential).catch(function (error) {
const errorCode = error.code;
const errorMessage = error.message;
const email = error.email;
const errorCred = error.credential;
});
}).catch(err => {
console.log(err);
});
}
This is a workaround but still doesn't solve the original problem.
Firebase being a product by google itself is expected to have these types of problems figured.
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?
I've a authentication Google with redirect in my app, and I would like just redirect when authentication is completely finished.
But the promise is not working
function loginGoogle() {
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithRedirect(provider);
firebase.auth().getRedirectResult().then(function (result) {
// This gives you a Google Access Token. You can use it to access the Google API.
if (result.credential) {
var token = result.credential.accessToken;
console.log('token ' + token);
}
// The signed-in user info.
var user = result.user;
console.log('user ' + user);
// if success redirect to
$state.go('maps-fullwidth');
// ...
}).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
console.log(errorCode);
var errorMessage = error.message;
// The email of the user's account used.
console.log(errorMessage);
var email = error.email;
console.log(email);
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
console.log(credential);
// ...
});
}
Thanks.
Move the getRedirectResult() call out of your loginGoogle() function. getRedirectResult() should be called on page load. An example of this in action can be found here:
https://github.com/firebase/quickstart-js/blob/master/auth/google-redirect.html