How to connect facebook, firebase and flutter? - facebook

I'm following the instructions for incorporating facebook with android projects found here https://developers.facebook.com/apps/318154048893918/fb-login/quickstart/ and there is a step to download the Facebook SDK, but after that, it doesn't tell me where to put the file. The import statement it tells me to add won't work (says target of uri doesn't exist).
I'm trying to add the facebook user to our firebase database when they log in. I'm using flutter in android studio.
There doesn't seem to be anything of use in the console log, except that print statement doesn't print anything. Any ideas?
Here's my code to log in the user.
import com.facebook.FacebookSdk;
import com.facebook.appevents.AppEventsLogger;
Future<FirebaseUser> initiateFacebookLogin() async {
final FacebookLoginResult result =
await facebookLogin.logInWithReadPermissions(['email', 'public_profile']);
FirebaseUser user =
await _auth.signInWithFacebook(accessToken: result.accessToken.token);
//Token: ${accessToken.token}
ProviderDetails userInfo = new ProviderDetails(
user.providerId, user.uid, user.displayName, user.photoUrl, user.email);
List<ProviderDetails> providerData = new List<ProviderDetails>();
providerData.add(userInfo);
print(user.displayName);
addToDatabase(user.uid, user.displayName, user.displayName, user.email);
return user;
}

In flutter you need use flutter_facebook_login plugin take a look here to see how to get the plugin and setup your flutter app to make use of this plugin. You can also check this article that is step-by-step about how setup you project and contains code example too but the API used is out of date.
Here a snippet with updated API showing how to achieve login in firebase with facebook account.
/// This mehtod makes the real auth
Future<FirebaseUser> firebaseAuthWithFacebook({#required FacebookAccessToken token}) async {
AuthCredential credential= FacebookAuthProvider.getCredential(accessToken: token.token);
FirebaseUser firebaseUser = await _authInstance.signInWithCredential(credential);
return firebaseUser;
}
In your code you're using _auth.signInWithFacebook method that is deprecated and you should replaced by signInWithCredential updating you firebase_auth plugin version.
///This object comes from facebook_login_plugin package
final facebookLogin = new FacebookLogin();
final facebookLoginResult = await facebookLogin
.logInWithReadPermissions(['email', 'public_profile']);
switch (facebookLoginResult.status) {
case FacebookLoginStatus.error:
print("Error");
break;
case FacebookLoginStatus.cancelledByUser:
print("CancelledByUser");
break;
case FacebookLoginStatus.loggedIn:
print("LoggedIn");
/// calling the auth mehtod and getting the logged user
var firebaseUser = await firebaseAuthWithFacebook(
token: facebookLoginResult.accessToken);
}
}

Related

how to keep user logged in

this is how I login using Google and firebase. but I couldn't figure it out as to how to keep the use logged in.. when the app restarts it log the user out automatically
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
final FirebaseAuth _auth = FirebaseAuth.instance;
final GoogleSignIn googleSignIn = GoogleSignIn();
Future<String> signInWithGoogle() async {
final GoogleSignInAccount? googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication =
await googleSignInAccount!.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final authResult = await _auth.signInWithCredential(credential);
final User? user = authResult.user;
assert(!user!.isAnonymous);
final User? currentUser = _auth.currentUser;
assert(user!.uid == currentUser!.uid);
return 'signInWithGoogle succeeded: $user';
}
You can call await _auth.currentUser() at the start of your app to check the current user. Further you may want to store the token in shared preferences.
Firebase automatically persists the user credentials in the shared storage, and restores them when the app restarts. There's nothing you need to do for that.
What you will need to do though is listen for the authentication state as shown in the first code snippet in the documentation on getting the current user:
FirebaseAuth.instance
.authStateChanges()
.listen((User? user) {
if (user != null) {
print(user.uid);
}
});
This code needs to run when the app starts, so I typically have it in my top-level widget and then store the user in the state so that my build method can use it. By listening to auth state changes, the code is run automatically when the user sign-in state is restored at startup (which happens asynchronously, so may take a few moments) but also when the user would later be logged out (for example, if you disable the account in the Firebase Authentication console).
It may not be the best way to do it but this worked.
chooseLogin() {
if (_auth.currentUser == null) {
return const SignUo();
} else {
return const Splash();
}
}

Google_sign_in Org_internal unable to login with different account

I'm working on an application for my organization. I was trying to implement oAuth with the google_sign_in package based on our google accounts.
The process for members to log in with accounts that belongs to the organization works fine. That's not the case with external emails.
I was expecting an error to be thrown in google prompt but I'm unable to log in with different at all. Seams that google tries to log me in instantly each time, leading to this screen each time:
I've tried using GoogleSignIn().signOut() or .deactivate() methods both of those did nothing to either remove the cache or retrigger the signing process.
Code responsible for log in:
class FirebaseAuthExternalIdentityProvider implements ExternalIdentityProvider {
final FirebaseAuth _firebaseAuth;
FirebaseAuthExternalIdentityProvider({required FirebaseAuth firebaseAuth})
: _firebaseAuth = firebaseAuth;
#override
Future<Result<GoogleSignInTokenWrapper>> signInWithGoogle() async {
final GoogleSignInAccount? googleAccount = await GoogleSignIn().signIn();
if (googleAccount == null) {
return Result.failure(Failure.signInProcessAborted());
}
final GoogleSignInAuthentication? googleAuthStatus =
await googleAccount.authentication;
final OAuthCredential _firebaseCredential = GoogleAuthProvider.credential(
accessToken: googleAuthStatus?.accessToken,
idToken: googleAuthStatus?.idToken,
);
try {
return Result.success(GoogleSignInTokenWrapper(
accessToken: await (await _firebaseAuth
.signInWithCredential(_firebaseCredential))
.user!
.getIdToken(),
));
} on FirebaseAuthException catch (cause) {
return Result.failure(Failure.firebaseSignInException(cause: cause));
} on Exception catch (cause) {
return Result.failure(Failure.unexpected(cause: cause));
}
}
}
Does someone know how to handle this problem? Changing the OAuth consent screen to External is the last thing I want to consider doing.
Thanks for any help in this matter!

Flutter Web Google Sign In

I try to implement a signIn with Google in Flutter Web. I use GoogleSignn 4.1.1 and Firebase Auth 0.15.4. I do not get any error message. It just does not pop up.
I registered the web app in Firebase (Added Dependencies) and even added the <meta> Tag with the google-signin-client_id
The Firebase Auth with Google works when I run it on Android
I also ran the Example App from GoogleSignIn in Web. It also does not pop up.
This is my Login Code (Works on Android)
final FirebaseAuth _auth = FirebaseAuth.instance;
FirebaseUser user = await _auth.currentUser();
if (user != null) {
log.d('alreadyLoggedIn');
} else {
final GoogleSignIn _googleSignIn = GoogleSignIn(clientId: Constants.GOOGLE_SIGN_IN_CLIENT_ID);
final GoogleSignInAccount googleUser = await _googleSignIn.signIn();
final GoogleSignInAuthentication googleAuth =
await googleUser.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
await _auth.signInWithCredential(credential);
user = await _auth.currentUser();
assert(user.email != null);
assert(user.displayName != null);
assert(!user.isAnonymous);
assert(await user.getIdToken() != null);
}
return user;
}
I hope someone knows how this can be fixed.
Have you followed all of the instructions (including adding OAuth ID to index.html) from this page?
https://pub.dev/packages/google_sign_in_web
You get your CLIENT ID from https://console.developers.google.com/apis/credentials
You also have to run from terminal like this, for it to work on localhost in debug:
flutter run -d chrome --web-hostname localhost --web-port 5000
The default authorised port is 5000, you can add other URIs on the same page you got your CLIENT ID (e.g.8764367243864-987523.apps.googleusercontent.com), it's under "Authorised JavaScript origins"
https://console.developers.google.com/apis/credentials)

How to use a google service account with cloud_firestore for Flutter?

I'm creating an application that needs to store and export some information on google firestore. I have a google service account with the corresponding certificate and the exporter that was made with Node.js works as expected. On the other hand, I use flutter and the latest cloud_firestore plugin for the application that needs to store the information and I can not find any documentation about how to use google service account certificate with the Flutter plugin.
The cloud_firestore plugins do not seem to have any mechanism to handle authentication and the plugin firebase_auth does not seem to support google service accounts.
Was anyone able to use a Google service account with Firestore and Flutter?
Here is my answer if the comment is correct.
Here is an AuthService that i use.
This will handle the google signin.
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:google_sign_in/google_sign_in.dart';
class AuthService {
final GoogleSignIn _googleSignIn = GoogleSignIn();
final FirebaseAuth _auth = FirebaseAuth.instance;
Future<FirebaseUser> signIn(String email, String password) async {
FirebaseUser u = await _auth.signInWithEmailAndPassword(
email: email, password: password);
updateUserData(u);
return u;
}
Future<FirebaseUser> signInAnon() async {
FirebaseUser user = await _auth.signInAnonymously();
updateUserData(user);
return user;
}
void signOut() {
_auth.signOut();
}
Future<FirebaseUser> googleSignIn() async {
try {
GoogleSignInAccount googleSignInAccount = await _googleSignIn.signIn();
GoogleSignInAuthentication googleAuth =
await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.getCredential(
accessToken: googleAuth.accessToken,
idToken: googleAuth.idToken,
);
FirebaseUser user = await _auth.signInWithCredential(credential);
updateUserData(user);
return Future.value(user);
} catch (error) {
print(error);
return Future.error(error);
}
}
}
In your pupspec you can import
firebase_core: ^0.4.0
firebase_auth: ^0.11.0
cloud_firestore: ^0.11.0+1
google_sign_in: ^4.0.1+3
In your firebase project console you can add google service account in settings -> service accounts (settings/serviceaccounts/adminsdk).
You also need to declare google as a provider in authentication -> providers
At this point you need to import in your flutter project the new version of google-service.json file provided in the settings part of firebase console.

How can I perform firebase authentication with facebook in flutter [duplicate]

This question already has answers here:
Function SignInWithFacebook doesn't exist in Firebase Auth SDK for Flutter in macOS, but in Windows it exists
(4 answers)
Closed 3 years ago.
I'm trying to add firebase and facebook authentication in my app. Facebook auth is already done:
final facebookLogin = FacebookLogin();
final result = await facebookLogin.logInWithReadPermissions(['email']);
switch (result.status) {
case FacebookLoginStatus.loggedIn:
final token = result.accessToken.token;
final graphResponse = await http.get(
'https://graph.facebook.com/v2.12/me?fields=name,first_name,last_name,email&access_token=$token');
Map<String, dynamic> user = jsonDecode(graphResponse.body);
// _onGetFacebookUser(user);
I don't know how to perform firebase authentication with facebook result.
I've already watched this answer, but it doesn't help, there is only facebook login code example.
I've found this article, but there is no method signInWithFacebook
You have to use credential
final result = await facebookLogin.logInWithReadPermissions(['email']);
switch (result.status) {
case FacebookLoginStatus.loggedIn:
final token = result.accessToken.token;
AuthCredential fbCredential = FacebookAuthProvider.getCredential(accessToken: token);
FirebaseAuth.instance.signInWithCredential(credential).then((FirebaseUser user) {
// do something...
});
...
UPD:
It worked fine for flutter_facebook_login version 2.0.1
For now for version 3.0.0 there is method 'login':
final result = await facebookLogin.logIn(['email']);