Firebase web auth via Google SSO - How to know whether a user registered or logged in - firebase

I want to detect whether the user has just registered via SSO or simply logged in.
The documentation wasn't helpful.
I'm using React + ES6. Here's my current auth method:
authWithGoogle = () => {
this.props.setIsLoggingInState(true);
firebaseApp
.auth()
.getRedirectResult()
.catch(() => console.error('something went wrong with Google SSO'));
firebaseApp
.auth()
.signInWithRedirect(googleProvider)
.catch(() => console.error('something went wrong with Google SSO'));
};
To be honest, the code above doesn't seem right... (but it works)

You can do the following:
firebaseApp.auth().getRedirectResult().then(function(userCredential) {
// True if the user is new, false if existing.
console.log(userCredential.additionalUserInfo.isNewUser);
}).catch(function(error) {
// Error occurred.
});

Related

How do you send a Firebase verification email (so that a user can verify their email) to a user in React Native?

I am making a React Native app where you can create accounts via Firebase authentication. I am try to set up a way to verify your email. I thought the code below would work, but it doesn't work. Anyone know the solution to this:
Code:
async function handleSignUp() {
await createUserWithEmailAndPassword(auth, email, password)
.then((userCredentials) => {
let user = auth.currentUser;
const actionCodeSettings = {
url: `${configData.BASE_URL}/sign-in/?email=${user.email}`,
};
auth.currentUser.sendEmailVerification(actionCodeSettings).then(() => {
alert("Verification link has been sent to your email");
});
})
.catch((error) => alert(error.message));
}
You're using the v9 or later SDK, which uses a modular syntax like you see here: await createUserWithEmailAndPassword(auth, email, password).
Similar to createUserWithEmailAndPassword, sendEmailVerification is a top-level function too in this API, so the syntax is:
sendEmailVerification(auth.currentUser, actionCodeSettings).then(() => {
alert("Verification link has been sent to your email");
});
This API is quite well covered in the Firebase documentation on sending an email verification link, so I recommend keeping that handy while coding.

React Native, Firebase: Error (auth/admin-restricted-operation) fix?

const handleSignUp = () => {
createUserWithEmailAndPassword(auth, email, password)
.then((re) => {
console.log(re);
})
.catch((error) => {
console.log(error);
}
);
};
This is the signup function that I've implemented for email and password authentication using Firebase authentication. The error that I'm getting is,
Firebase: Error (auth/admin-restricted-operation).
This happens every time I run this function and the firebase authentication tab does not show the new user. Been stuck on this error for quite a while now and am unable to fix it. Any help would be highly appreciated.

firebase auth share session/token between microservices

I working with firebase auth and I'm a bit confused on how to manage the authentication between different apps, in particular nextjs (main site, that use express too) api and react app (is a kind of dashboard). After reading a bit of documentation what I did (but I'm not sure is the right way) is to get the idToken on the main site with the client side library:
firebase
.auth()
.signInWithEmailAndPassword(email, password)
.then(() => {
const currentUser = firebase.auth().currentUser.getIdToken();
currentUser.then(idToken => {
return axios.post("/auth/login", { idToken });
});
});
and make a request to nextjs/express to create the cookie sessions:
firebase
.auth()
.createSessionCookie(idToken, { expiresIn })
.then(
sessionCookie => {
res.cookie("session", sessionCookie, {
maxAge: expiresIn,
httpOnly: true
});
return res.end(JSON.stringify({ status: "success" }));
},
error => res.status(401).send(error)
);
then when I need to send a request to the api I'll pass the idtoken saved in the cookie and I verify the token in a middleware
const userInfo = await firebase.auth().verifySessionCookie(authToken);
I'm not implemented the react app yet but I think in that I'll just use the clientside library to do everything....My main doubt is the authentication between the nextjs/express and the api, I'm not sure if usin the sessioncookie is the right choise...do I need to send just the tokenId instead of the session cookie? do you have any suggestions?

Firebase Google login not staying persistence

I am developing an application, with an feature of Google Login through Firebase. I am trying to login via Google with the help of an library, known as react-native-google-signin. It is well known library in the field of ReactNative for Google Login.
My problem is not with this library, but the problem is that while I am using react-native-google-signin library with firebase to login via google. Firebase User is not staying persistence, I mean to say that when I am opening app after close FirebaseUser is getting null. Below the code I am using to login via firebase,
GoogleSignin.signIn().then(data => {
const credentials = firebase.auth.GoogleAuthProvider.credential(data.idToken, data.accessToken);
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
.then() => {
return firebase.auth().signInWithCredential(credentials);
}).catch(error => {
console.log('Error', error);
})
}).then(user => {
console.log('user', firebase.auth().currentUser);
}).catch(error => {
console.log('Error', error);
})
I also checked Firebase Docs, tried by using setPersistence() method but still I am getting null user after open app again.
You can try this
when you first time open your app you get user null, but after login one time then reopen your app and you will get previously logged in user in your console
async _setupGoogleSignin() {
try {
await GoogleSignin.hasPlayServices({ autoResolve: true });
await GoogleSignin.configure({
webClientId: 'YOUR WEBCLIENTID',
offlineAccess: false
});
const user = await GoogleSignin.currentUserAsync();
console.log("user",user); // HERE YOU GET LOGGED IN USER IN YOUR CONSOLE FIRST TIME IT WILL BE NULL BUT AFTER YOU GET PREVIOUSLY LOGGED IN USER
this.setState({user});
}
catch(err) {
console.log("Play services error", err.code, err.message);
}}
then
_signIn() {
GoogleSignin.signIn()
.then((user) => {
console.log(user);
this.setState({user: user});
const credential = firebase.auth.GoogleAuthProvider.credential(user.idToken, user.accessToken);
// console.log(credential);
return firebase.auth().signInAndRetrieveDataWithCredential(credential);
})
.catch((err) => {
console.log('WRONG SIGNIN', err);
})
.done();}
it is worked for me...
hope it will help you...

Secure HTTP trigger for Cloud Functions for Firebase

Is there a way to check if a user is firebase-authorized before triggering a cloud function? (Or within the function)
Yes. You will need to send the Firebase ID token along with the request (for example in the Authorization header of an AJAX request), then verify it using the Firebase Admin SDK. There is an in-depth example in the Cloud Functions for Firebase samples repository. It looks something like this (made shorter for SO post):
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')();
const validateFirebaseIdToken = (req, res, next) => {
cors(req, res, () => {
const idToken = req.headers.authorization.split('Bearer ')[1];
admin.auth().verifyIdToken(idToken).then(decodedIdToken => {
console.log('ID Token correctly decoded', decodedIdToken);
req.user = decodedIdToken;
next();
}).catch(error => {
console.error('Error while verifying Firebase ID token:', error);
res.status(403).send('Unauthorized');
});
});
};
exports.myFn = functions.https.onRequest((req, res) => {
validateFirebaseIdToken(req, res, () => {
// now you know they're authorized and `req.user` has info about them
});
});
Since the question asks for auth-based access (1) within, or (2) before a function, here's an method for the "before" case: >
Since every Firebase Project is also a Google Cloud Project -- and GCP allows for "private" functions, you can set project-wide or per-function permissions outside the function(s), so that only authenticated users can cause the function to fire.
Unauthorized users will be rejected before function invocation, even if they try to hit the endpoint.
Here's documentation on setting permissions and authenticating users. As of writing, I believe using this method requires users to have a Google account to authenticate.

Resources