firebase facebook auth get user data - firebase

I'm using firebase auth system for login with facebook on my ionic app.
I'm trying to get profile data and save it into database after user login with database. You can check the how can i to do that with the following code.
User can login successfully but can not set data into database.
How can i solve that?
loginWithFacebook() {
this.facebook.login(['email']).then((response) => {
let credintial = firebase.auth.FacebookAuthProvider.credential(response.authResponse.accessToken);
firebase.auth().signInWithCredential(credintial).then(info => {
this.userEmail = info['email'];
this.userName = info['displayName'];
this.userUid = info['uid'];
});
});
this.afDatabase.database.ref(`dump/${this.userUid}`).set({
username: this.userName,
email: this.userEmail,
uid: this.userUid,
wallet: 0
}).then(data => {
this.navCtrl.setRoot(TabsPage);
});
}

Should be aware that you are using an asynchronous function and you should insert the record into database after successful sign in.
loginWithFacebook() {
this.facebook.login(['email']).then((response) => {
let credintial = firebase.auth.FacebookAuthProvider.credential(response.authResponse.accessToken);
firebase.auth().signInWithCredential(credintial).then(info => {
this.userEmail = info['email'];
this.userName = info['displayName'];
this.userUid = info['uid'];
this.afDatabase.database.ref(`dump/${this.userUid}`).set({
username: this.userName,
email: this.userEmail,
uid: this.userUid,
wallet: 0
}).then(data => {
this.navCtrl.setRoot(TabsPage);
});
});
});
}

Related

How can I log in a user right after his/her email has been verified using firebase/auth and react-native without creating a whole landing page?

Notice: I have seen this question, but creating a whole landing page just to verify a user seems a bit much.
I added a login functionality to my react-native app using firebase/auth with email and password. This works well so far and I have no issues doing that.
I then continued to send a verification email to a new user and only allow him/her to use the app, once the email is verified. Again, no issues here.
The next step would be to login the user right after the email was verified. This is where I'm stuck, since the onAuthStateChanged eventhandler doesn't update after the user pressed the verification link in the email.
Is there any way to listen to the emailVerified state in real-time? I tried to use polling with setInterval() but this is not great since there is a notable delay between verification and login. I read about a continueLink you can pass to sendEmailVerification, but I couldn't figure out how to make that work in react-native.
I'm using Expo and therefore the Firebase SDK, not the Firebase react native package.
Here is the code I use for the signup:
export const signUp = async (username: string, email: string, password: string) => {
try {
const auth = getAuth();
if (email && password && username) {
// sign up
const userCredential = await createUserWithEmailAndPassword(auth, email, password);
// save username in firestore
await setUserName(userCredential, username);
// send Email Verification
await sendEmailVerification(userCredential.user);
return true;
}
} catch (error) {
onError(error);
}
};
And this is my onAuthStateChanged handler:
auth.onAuthStateChanged(authenticatedUser => {
try {
if (authenticatedUser?.emailVerified) {
setUser(authenticatedUser)
} else {
setUser(null)
}
} catch (error) {
console.log(error);
}
});
So in the end I did follow this question, but I changed it a bit to fit my needs. I'll post my steps for anyone who's doing the same.
Create a simple static website with firebase init and host it on firebase or somewhere else (check the hosting tab in your firebase console to get started)
Follow this guide to create the appropriate handlers on the website
Add the following to your verificationHandler to update the user (don't forget to import firestore) (I send the userId via the continueURL, but there are probably better ways)
// You can also use realtime database if you want
firebase.firestore().collection("users").doc(userId).set({
emailVerified: true
}, {merge: true}).then(() => {
message.textContent = "Your email has been verified.";
}).catch((error) => {
message.textContent = "The verification was invalid or is expired. Please try to send another verification email from within the app.";
});
Got to authentication -> templates in your firebase console and change the action url to your hosted website's url
Add a listener to the firestore doc to your react-native app
const onUserDataChanged = (uid, callback) => {
onSnapshot(doc(firestore, "users", uid), doc => callback(doc.data()));
}
Use the data from the callback to update the login state in the app
// As an example
auth.onAuthStateChanged(authenticatedUser => {
if (authenticatedUser && !authenticatedUser.emailVerified) {
unsubscribeFirestoreListener?.();
unsubscribeFirestoreListener = onUserDataChanged(authenticatedUser.uid, (data: any) => {
if (data?.emailVerified) {
setUser(authenticatedUser);
unsubscribeFirestoreListener?.();
}
});
}
}
use the codes below for your authentication context. for user id, you should use 'user.uid'
import React, { useState, createContext } from "react";
import * as firebase from "firebase";
import { loginRequest } from "./authentication.service";
export const AuthenticationContext = createContext();
export const AuthenticationContextProvider = ({ children }) => {
const [isLoading, setIsLoading] = useState(false);
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
firebase.auth().onAuthStateChanged((usr) => {
if (usr) {
setUser(usr);
setIsLoading(false);
} else {
setIsLoading(false);
}
});
const onLogin = (email, password) => {
setIsLoading(true);
firebase.auth().signInWithEmailAndPassword(email, password)
.then((u) => {
setUser(u);
setIsLoading(false);
})
.catch((e) => {
setIsLoading(false);
setError(e.toString());
});
};
const onRegister = (email, password, repeatedPassword) => {
setIsLoading(true);
if (password !== repeatedPassword) {
setError("Error: Passwords do not match");
return;
}
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((u) => {
setUser(u);
setIsLoading(false);
})
.catch((e) => {
setIsLoading(false);
setError(e.toString());
});
};
const onLogout = () => {
setUser(null);
firebase.auth().signOut();
};
return (
<AuthenticationContext.Provider
value={{
isAuthenticated: !!user,
user,
isLoading,
error,
onLogin,
onRegister,
onLogout,
}}
>
{children}
</AuthenticationContext.Provider>
);
};

Create a new User when authenticating with Google

How can I create a document user in firebase when I first authenticate or multiple times ???
Example: I choose to authenticate by google, Twitter .... by account abc#gmail.com ... and I want to save to collection "user" with document = User UId (google account).
With the certificate authentication method I don't know how to get the Google User User UID until it's added to the Authentication List.
signInWithGoogleAsync = async () => {
try {
const { type, accessToken } = await Google.logInAsync({
iosClientId: '1058889369323-kh44jtru0ar24qu24ebv1bu0ebrgvokd.apps.googleusercontent.com',
scopes: ['profile', 'email'],
});
if (type === 'success') {
this.setState({ spinner: true });
const credential = firebase.auth.GoogleAuthProvider.credential(null, accessToken);
firebase.auth().signInWithCredential(credential).catch(error => {console.log(error);});
///I know how to do this, authenticate 1 user and put it in the Authentication list when authenticating successfully the first time
} else {
return { cancelled: true };
}
} catch (e) {
return { error: true };
}
}

Handle facebook login with same account used with Google using firebase

I'm working on a react native project and I've came to a part where initially I implemented google sign in my project using react-native-google-signin and later on Facebook sign in using react-native-fbsdk packages with the help of firebase and both worked like a charm "individually".
The Problem
Let's say the user logged in using google account and it worked but later logged in using Facebook with the same account (I'm allowing only one email per user in firebase), I get an error
auth/account-exists-with-different-credentials
I want the user to be able to login using Facebook from the login screen or to be more specific to link his account from the login screen.
What have I tried?
I searched online and found some answers and got up with this solution or piece of code:
facebookSignin: async () => {
const result = await LoginManager.logInWithPermissions([
'public_profile',
'email',
]);
if (result.isCancelled) {
alert('User cancelled the login process');
this.setState({loginInProcess: false});
}
const data = await AccessToken.getCurrentAccessToken();
if (!data) {
alert('Something went wrong obtaining access token');
this.setState({loginInProcess: false});
}
const facebookCredential = auth.FacebookAuthProvider.credential(
data.accessToken,
);
await auth()
.signInWithCredential(facebookCredential)
// The problem starts here from the catch block
.catch((error) => {
if (
error.code === 'auth/account-exists-with-different-credential'
) {
var pendingCred = error.credential;
var email = error.email;
auth()
.fetchSignInMethodsForEmail(email)
.then(async (methods) => {
if (methods[0] === 'google.com') {
const {idToken} = await GoogleSignin.signIn();
const googleCredential = auth.GoogleAuthProvider.credential(
idToken,
);
auth()
.signInWithCredential(googleCredential)
.then((user) => {
user.linkWithCredential(pendingCred);
})
.catch((error) => console.log(error));
}
});
}
});
}
This code implements a function when triggered, if there is no user with the same email, it proceeds normally, however if there is an error (mentioned above), it will grant the user with a list of google accounts that are present in the user phone (google thing) and when he chooses his account (linked with google account) it doesn't work. The email isn't linked.
To be more specific, I would like somehow to not grant the user with all his google accounts but only with the email to be linked var email = error.email; (in the code snippet above) and for the Facebook provider to be linked successfully.
After a little of hard work, I've managed to make it work in react native and I'm gonna leave the answer here for peeps who are facing the same issue. Be ware that I used react-native-prompt-android to ask the user for confirming his password when trying to link with Facebook.
The user tries to sign with Facebook and gets this error:
auth/account-exists-with-different-credentials
This is how I handled it:
.catch((error) => {
// Catching the error
if (
error.code === 'auth/account-exists-with-different-credential'
) {
const _responseInfoCallback = (error, result) => {
if (error) {
alert('Error fetching data: ' + error.toString());
} else {
setEmail(result.email);
}
};
// Getting the email address instead of error.email from Facebook
const profileRequest = new GraphRequest(
'/me?fields=email',
null,
_responseInfoCallback,
);
new GraphRequestManager().addRequest(profileRequest).start();
if (email) {
auth()
.fetchSignInMethodsForEmail(email)
.then(async (methods) => {
// Checking the method
if (methods[0] === 'password') {
// Prompting the user to confirm/input his password for linking
const AsyncAlert = () => {
return new Promise((resolve, reject) => {
prompt(
'Password Confirmation',
'The email address is already linked with password account. Enter your password to process',
[
{
text: 'Cancel',
style: 'cancel',
},
{
text: 'Continue',
onPress: (password) =>
resolve(setPassword(password)),
},
],
{
type: 'secure-text',
cancelable: false,
placeholder: 'Password',
},
);
});
};
// Here the linking goes
await AsyncAlert().then(async () => {
await auth()
.signInWithEmailAndPassword(email, password)
.then(() => {
return auth().currentUser.linkWithCredential(
facebookCredential,
);
})
.catch(() => alert('Something went wrong'));
});
} else if (methods[0] === 'google.com') {
const {idToken} = await GoogleSignin.signIn(email);
const googleCredential = auth.GoogleAuthProvider.credential(
idToken,
);
await auth()
.signInWithCredential(googleCredential)
.then(() => {
return auth().currentUser.linkWithCredential(
facebookCredential,
);
});
}
});
} else {
alert('Something went wrong');
}
}
});

Nuxt SSR auth guard with Firebase auth

I'm trying to implement auth guards in Nuxt with Firebase Auth, but I keep running in to problems. At the moment I'm able to login, but the correct page isn't loaded after login, after login the user should be redirected to the '/profile-overview' page but that doesn't happen. When I navigate away from the 'profile' page to another page and then go back I do automatically go to the 'profile-overview' page. So the login works, there is just something wrong with the navigation / refresh of the page after login. Also when I refresh the page the user is logged out again, I would except the user to still be logged in then?
My code so far:
Page:
loginGoogle () {
this.$store.dispatch('signInWithGoogle').then(() => {
console.log('reload')
location.reload()
//window.location.reload(true)
}).catch((e) => {
this.title = 'Google login failed'
this.message =
"Something went wrong, please try again later. If this problem keeps happening please contact: jonas#co-house.be " + "Error: " + e.message;
this.dialog = true;
})
},
Middleware:
export default function ({ store, redirect, route }) {
console.log('user state' + store.state.user)
console.log('route ' + route.name)
store.state.user != null && route.name == 'profile' ? redirect('/profile-overview') : ''
store.state.user == null && isAdminRoute(route) ? redirect('/profile') : ''
}
function isAdminRoute(route) {
if (route.matched.some(record => record.path == '/profile-overview')) {
return true
}
}
Plugin:
import { auth } from '#/services/fireInit.js'
export default context => {
const { store } = context
return new Promise((resolve, reject) => {
auth.onAuthStateChanged(user => {
if (user) {
return resolve(store.commit('setUser', user))
}
return resolve()
})
})
}
Store (function to login only:
signInWithGoogle ({ commit }) {
return new Promise((resolve, reject) => {
auth.signInWithPopup(GoogleProvider).then((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;
return resolve(store.commit(state.user, result.user))
// ...
}).catch((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;
// ...
})
})
},
Does anyone have any idea what I could be doing wrong, or some documentation / tutorial I could read?
Thanks in advance.
You need to init your user on server in nuxtServerInit. See this repo for example implementation https://github.com/davidroyer/nuxt-ssr-firebase-auth.v2

How to persist a Firebase login?

I'm doing an app with Ionic Framework and Firebase. I made a custom login to get data inside Firebase, but every single time the app is restarted I need to login again. How can I persist the login? The user should login the first time, and not need to do it again.
Here is my service:
(function() {
'use strict';
angular
.module('mytodo.login')
.factory('LoginService', LoginService);
LoginService.$inject = ['$state', '$ionicLoading', '$firebaseAuth', '$firebaseObject','$rootScope', '$timeout', 'fb', '$q'];
function LoginService($state, $ionicLoading, $firebaseAuth, $firebaseObject, $rootScope, $timeout, fb, $q){
var service = {
CustomLogin: CustomLogin,
GetCurrentUser: GetCurrentUser,
RegisterUser: RegisterUser,
};
return service;
function CustomLogin(email, password) {
if(email ==null | password == null){
console.log('Preencha todos os campos!');
return;
}
$ionicLoading.show({
showBackdrop: false,
template: '<p>Carregando...</p><ion-spinner icon="android" style="stroke: #1d9c9e;fill:#1d9c9e;"></ion-spinner>'
});
$firebaseAuth().$signInWithEmailAndPassword(email, password).then(function(authData) {
$rootScope.currentUser = GetCurrentUser(authData.uid);
$timeout(function() {
$ionicLoading.hide();
$state.go('tab.todo', {});
}, 1000);
}).catch(function(error) {
showToast();
$ionicLoading.hide();
console.log(error);
});
}
function showToast(){
ionicToast.show('Usuário ou senha inválido', 'middle', false, 1500);
}
function GetCurrentUser(userId) {
var query = fb.child('/users/' + userId);
var currentUser = $firebaseObject(query)
return currentUser;
}
function SaveUser(authData) {
console.log(authData.uid);
var deffered = $q.defer();
var uid = authData.uid;
var user = {
displayName: authData.displayName,
name: authData.displayName,
photoURL: authData.photoURL,
email: authData.email,
emailVerified: authData.emailVerified,
providerId: authData.providerData[0].providerId
};
var ref = fb.child('/users/' + uid);
ref.once("value")
.then(function(snapshot) {
if (snapshot.exists()) {
console.log('User already exists');
} else {
ref.set(user);
}
deffered.resolve(snapshot);
});
return deffered.promise;
};
function RegisterUser(user) {
var deffered = $q.defer();
$ionicLoading.show();
$firebaseAuth().$createUserWithEmailAndPassword(user.email, user.password).then(function(authData) {
var newUser = {
name: user.name,
email: user.email,
providerId: authData.providerData[0].providerId
};
var userId = authData.uid;
var ref = fb.child('/users/' + userId);
ref.once("value")
.then(function(snapshot) {
if (snapshot.exists()) {
//console.log('User already exists');
} else {
ref.set(newUser).then(function(user){
$rootScope.currentUser = GetCurrentUser(userId);
})
}
deffered.resolve(snapshot);
CustomLogin(user.email, user.password);
});
}).catch(function(error) {
$ionicLoading.hide();
var errorCode = error.code;
console.log(errorCode);
if(errorCode === 'auth/weak-password')
ionicToast.show('Erro, a senha precisa ter no mínimo 6 digitos.', 'middle', false, 3000);
if(errorCode === 'auth/email-already-in-use')
ionicToast.show('Erro, o email: ' + user.email + ' já existe em nossa base de dados.', 'middle', false, 3000);
})
return deffered.promise;
};
}
})();
To re-iterate the point of don't persist the login yourself, firebase does this for you. I am referencing this from typescript FYI.
In the official docs() :
firebase.auth().setPersistence(firebase.auth.Auth.Persistence.LOCAL)
Where local is on disk.
Then later in your code all you need to do is subscribe to the onAuthStateChanged observable.
this.firebase.auth.onAuthStateChanged(user => {
if (user){
Do not persist the plain text password yourself!!!! Firebase persists a user with uid, session API keys etc.
Just follow the Firebase docs. Persisting plain text password will result in a bad security audit.
Newer version
Initialize the app like this to keep the user logged in even after the browser is closed and reopened on the same device.
import { initializeApp } from 'firebase/app';
import { getAuth, browserLocalPersistence, setPersistence } from 'firebase/auth'
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
(async () => {
await setPersistence(auth, browserLocalPersistence);
})();
To get the user object you can use React Firebase Hooks:
import { useAuthState } from 'react-firebase-hooks/auth';
const [user, loading, error] = useAuthState(auth);
You shouldn't persist username and password to storage, if you have to then at least store the password as a hash.
Firebase has the following for signing in again:
firebase.auth().onAuthStateChanged(user => {
});
I've figured out how to do this. Maybe it's not the most correct anwser for it, but it worked for me. I used localSotrage to store the username and password. I could store the tolken as well, but I want to create a "remember password" screen.
When I do my first login I do this in my service.
service.js when I store the user data;
localStorage.setItem("uPassword",password);
localStorage.setItem("uEmail",email);
And I add the following if statement in my controller. If i already did the login, I use the e-mail and password to login again. If I dont, I wait to user press the button and call de function in my service.
controller.js if statement:
if(localStorage.getItem("uEmail")!==undefined && localStorage.getItem("uPassword")!==undefined) {
LoginService.CustomLogin(localStorage.getItem("uEmail"),localStorage.getItem("uPassword"))
}

Resources