Web Firebase Google SignIn doesn't work - javascript

I am new to web development and am trying to create an app that right now allows you to sign in using Firebase Authentication and the app will display your name. I have been following the Codelab that Firebase offers online to create this basic functionality but I cannot figure out why I am not able to detect that someone has signed in. Here is my initFirebase function:
LoginClient.prototype.initFirebase = function() {
// Shortcuts to Firebase SDK features.
this.auth = firebase.auth();
this.database = firebase.database();
this.storage = firebase.storage();
// Initiates Firebase auth and listen to auth state changes.
this.auth.onAuthStateChanged(this.onAuthStateChanged.bind(this));
};
Within this I am using onAuthStateChanged to listen for the auth state change and execute the following function that I have written:
LoginClient.prototype.onAuthStateChanged = function(user) {
if(user){
//window.open("userdash.html");
console.log("onAuthStateChanged works")
/*this.userNameDisplay.innerText = "Hello " + user.displayName + "!";
window.alret("Hello " + user.displayName + "!");*/
//this.userNameDisplay.removeAttribute('hidden');
this.userNameDisplay.textContent= user.displayName;
this.userNameDisplay.removeAttribute('hidden');
this.signInButton.setAttribute('hidden', 'true');
this.googleSignInButton.setAttribute('hidden', 'true');
this.createAccountButton.setAttribute('hidden', 'true');
}else{
this.userNameDisplay.setAttribute('hidden', 'true');
this.signInButton.removeAttribute('hidden');
this.googleSignInButton.removeAttribute('hidden');
this.createAccountButton.removeAttribute('hidden');
}
};
The function will detect that there is a user and then display the name of the person who signed in. So what I want to happen is for me to press a button that triggers the following google sign in function:
LoginClient.prototype.googleSignIn = function(){
var provider = new firebase.auth.GoogleAuthProvider();
this.auth.signInWithPopup(provider);
console.log("Signed in google");
};
which will allow a user to signin off the popup window that is created. Once they have successfully signed in, the auth.onAuthStateChanged listener will be triggered and cause the above onAuthStateChanged function to be called. However what is currently happening is that the googleSignIn function is called and a popup window is created but before I can authenticate on the popup window, the page reloads. Once I finish signing in successfully on the popup window the onAuthStateChanged function fails to be called. Can anyone help me figure out why the page reloads when I try to sign in?

Related

How to get different user in firebase auth

I am working on an app, and part of the functionality of the app is an admin being able to sign in and reset other users' passwords. How do I get a user other than the one currently signed in?
resetForm.addEventListener('submit', (e) => {
e.preventDefault();
let newPass = resetForm['reset-password'].value;
let firebaseUser = auth.user(docId);
console.log(firebaseUser);
});
I understand that that code won't actually reset any password, I just wrote that to see if I could get a user other than the one already signed in. I ran it, but instead of seeing the User UID in the console I saw this:
Uncaught TypeError: auth.user is not a function
Edit:
I have created a cloud function. Here is the code of my index.js file:
var functions = require('firebase-functions');
var admin = require("firebase-admin");
var serviceAccount = require("/removed-for-privacy.json");
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://troop-30-elections-web-app.firebaseio.com"
});
exports.resetPassword = functions.https.onCall((docId,newPass) => {
console.log("step 2");
admin.auth().updateUser(docId, {
password: newPass,
}).then(() => {
const modal = document.querySelector('#modal-reset');
M.Modal.getInstance(modal).close();
resetForm.reset();
});
});
Here is the code that runs when the button is pressed:
resetForm.addEventListener('submit', (e) => {
console.log("Step 1");
e.preventDefault();
let newPass = resetForm['reset-password'].value;
const resetPasswordFunction = firebase.functions().httpsCallable('resetPassword');
resetPasswordFunction(docId,newPass);
console.log("Step 1.5");
});
When I open the console, there are no error messages. I see step 1 and step 1.5. Nothing else.
There is no way to identify an application administrator in Firebase Authentication. You will have to build your own infrastructure for this.
Typically this means:
In a trusted environment (like a server you control, or Cloud Function) you use the Admin SDK to change their password.
You then wrap that code into a custom API, that you expose to your application.
You call the API from your application, passing along the ID token of the signed in user.
In the API you verify the ID token, and make sure the caller is authorized for the operation.
You are completely on your own here though, as you can't use Firebase's built in password reset mechanism. That is only available to the signed-in user on the client, to prevent it being abused to spam users.

How to get current user or login user in Firebase cloud functions?

How to get current user email like there is a event called onCreate but i want to trigger onLogin or currentUser?
exports.currentUser = functions.auth.user().onCreate((user) => {
const email = user.email; // The email of the user.
const displayName = user.displayName; // The display name of the user.
});
There are no Cloud Functions triggers for when a user signs in to your app with Firebase Authentication. If you have something to do what the user signs in, that should be controlled by the app itself, since it has the callback for signin and signout. You could directly invoke an HTTP or callable type function in that case, and pass the function the UID to look up using the Firebase Admin SDK.

Keep user after redirect with firebase

Im currently working on a side project with firebase on web and it uses user auth. I have the user logging in and then creating a game room which redirects to a separate page for the game "room". After the page redirects though i cannot pull any of the users data and the only way that im doing it is by re initializing firebase and using
auth.onAuthStateChanged(function(user) {
if (user && user != null) {
uid = user.uid;
email = user.email;
currUser = user;
} else {
//user isnt logged in
window.location.href = 'index.html';
}
There seems to probably be an easier way to do this but i cant seem to get it working and this way also messes up sections of my other code.
Attaching an onAuthStateChanged callback is the idiomatic way to get the user.
You can also get the user with firebase.auth().currentUser. But if a token refresh is required, you may in that case mis-detect that there is no user. That why an onAuthStateChanged callback is recommended.
See the Firebase documentation on getting the current user.

How to manage google sign-in session (Google Sign-In JavaScript client)

im trying to implement google sign-in using their new API : https://developers.google.com/identity/sign-in/web/
Sign-in and Sign-out work fine.
My problem is that i dont know how to manage a session on other pages without a server side.
So i tried this code - https://developers.google.com/identity/sign-in/web/session-state
And it doesnt work well for me.
I dont want to have the google sign in button in every page. If i remove the "auth2.attachClickHandler.." part the whole code doesnt work.
All i want is to indicate in other pages (not in the page with the google button) if a user is still connected to or not.
Can you help me?
EDIT:
I tried the following code suggested in the answers but i get an error that says: " Uncaught TypeError: Cannot read property 'init' of undefined"
Code:
var auth2 = gapi.auth2.init({
client_id : 'ID.apps.googleusercontent.com'
});
auth2.then(function() {
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (isSignedIn) {
console.log("signed in");
// User is signed in.
// Pass currentUser to onSignIn callback.
} else {
console.log("NOT signed in");
// User is not signed in.
// call auth2.attachClickHandler
// or even better call gapi.signin2.render
}
});
You can load gapi.auth2 on all pages and call:
var auth2 = gapi.auth2.init(...);
auth2.then(function() {
var isSignedIn = auth2.isSignedIn.get();
var currentUser = auth2.currentUser.get();
if (isSignedIn) {
// User is signed in.
// Pass currentUser to onSignIn callback.
} else {
// User is not signed in.
// call auth2.attachClickHandler
// or even better call gapi.signin2.render
}
});
In this solution sign in button is displayed only when user is not signed in.

AngularFire: Resuming an anonymous session

From the Simple Web Login docs, it claims you can resume a session by doing the following:
var auth = new FirebaseSimpleLogin(chatRef, function(error, user) {
...
});
Is there an equivalent for AngularFire?
The $firebaseSimpleLogin constructor takes a firebase reference as its only parameter..
Specifically, what I'm trying to do is login once anonymously and resume that login on a full page refresh. Is that achievable?
Whether or not your auth session is preserved is determined by the parameters you pass into the login method. Whether you use FirebaseSimpleLogin or $firebaseSimpleLogin is irrelevant here.
var auth = $firebaseSimpleLogin(ref);
$rootScope.$on('$firebaseSimpleLogin:login', function(user) {
console.log('logged in', user.uid);
});
// automagically logs in the next time you call $firebaseSimpleLogin() after page refresh
auth.$login('anonymous', { rememberMe: true });
// does not automagically log in
auth.$login('anonymous');
UPDATE As of Angular 1.x and Firebase 2.x this syntax and behavior has changed.
From the remember attribute in Firebase docs:
If not specified - or set to default - sessions are persisted for as
long as you have configured in the Login & Auth tab of your App
Dashboard. To limit persistence to the lifetime of the current window,
set this to sessionOnly. A value of none will not persist
authentication data at all and will end authentication as soon as the
page is closed.
var auth = $firebaseAuth(ref);
$firebaseAuth.$onAuth(function(user) {
console.log('logged ' + (user? 'in' : 'out'), user && user.uid);
});
// stays logged in for length specified in the app dashboard
auth.$authAnonymously();
// stays logged in until the browser closes
auth.$authAnonymously({ remember: 'sessionOnly' });
// does not stay logged in on page refresh
auth.$authAnonymously({ remember: 'none' });

Categories