flutter_facebook_auth plugin not clearing the data when logging out - flutter

I'm making use of the flutter_facebook_auth 3.5.0 plugin to enable users to log into my app using their Facebook account.
Everything is working as expected. But when I log out and try to login again, it isn't prompting me to enter the credentials and directly logs me in.
I want it to prompt the user to enter their Facebook account credentials and then log into the app only if the authentication was successful.
Below is the SignIn code:
Future<void> signInWithFacebook(BuildContext context) async {
User? firebaseUser;
LoginResult response = await FacebookAuth.instance.login();
AuthCredential facebookCredential = FacebookAuthProvider.credential(response.accessToken!.token);
final UserCredential userCredential = await FirebaseAuth.instance.signInWithCredential(facebookCredential);
firebaseUser = userCredential.user;
switch (response.status) {
case LoginStatus.success:
final userData = await FacebookAuth.instance.getUserData();
facebookUserData = userData;
firestoreInstance.collection("users").doc(firebaseUser!.uid).set({
"userID": firebaseUser.uid,
"name": facebookUserData["name"],
"photo": facebookUserData["picture"]["data"]["url"],
"emailAddress": facebookUserData["email"],
"signUpMethod": "facebook",
"accountCreatedOn": Timestamp.now(),
"receiveOffers": true,
"isAdmin": false,
"isAuth": false,
"isSubscribed": false,
});
Navigator.of(context).pushReplacement(ScaledAnimationPageRoute(HomePage()));
break;
case LoginStatus.cancelled:
print("Facebook: User cancelled login");
break;
case LoginStatus.failed:
print("Facebook: Login error!");
break;
case LoginStatus.operationInProgress:
// TODO: Handle this case.
break;
}
}
Below is the method for logout:
await FacebookAuth.instance.logOut();
facebookUserData = {};
await authInstance.signOut().then((value) => Navigator.of(context).pushReplacement(ScaledAnimationPageRoute(SignIn())));
I think the AuthCredential needs to be cleared when the user is logging out. I'm not sure how to do it.
I'm new to Flutter. How can I fix this?

There is already an issue on the github project of the flutter_facebook_auth 3.5.0 here.
It looks like an lmitation of Facebook and not the plugin itself.

Use package named flutter_facebook_login instead...I am using this package and it is working well

Related

Invalid key hash error when opening flutter facebook login application

While logging in to facebook in the application I published on google play store, if the application is installed on the device, I get an invalid key hash error, but when I delete the application, I do not get any errors in the logins on the web, I can log in directly.
How can I do web redirect without entering the application
My code
`
FacebookLoginResult _faceResult = await _facebookLogin.logIn(permissions: [
FacebookPermission.publicProfile,
FacebookPermission.email,
]);
switch (_faceResult.status) {
case FacebookLoginStatus.success:
if (_faceResult.accessToken != null &&
_faceResult.accessToken.token.isNotEmpty) {
FirebaseUser.UserCredential _firebaseResult = await _firebaseAuth
.signInWithCredential(FacebookAuthProvider.credential(_faceResult.accessToken.token));
FirebaseUser.User _user = _firebaseResult.user;
return _userFromFirebase(_user);
} else {
/* print("access token valid :" +
_faceResult.accessToken.isValid().toString());*/
}
break;
case FacebookLoginStatus.cancel:
print("kullanıcı facebook girişi iptal etti");
break;
case FacebookLoginStatus.error:
print("Hata cıktı :" + _faceResult.error.toString());
break;
}
`
actually being able to login facebook somehow is enough for me

Connect Metamask with a native mobile app built with Flutter

I want to connect the app to Metamask to get the user account and signature from the user to confirm the transaction. But the problem is that when I enter Metamask from the app, I am not asked any questions to confirm the connection and nothing happens inside Metamask, it is like only the Metamask app is opened and when I back up and return to the app, the null account is returned.
_walletConnect() async {
final connector = WalletConnect(
bridge: 'https://bridge.walletconnect.org',
clientMeta: const PeerMeta(
name: 'WalletConnect',
description: 'WalletConnect Developer App',
url: 'https://walletconnect.org',
icons: [
'https://gblobscdn.gitbook.com/spaces%2F-LJJeCjcLrr53DcT1Ml7%2Favatar.png?alt=media'
],
),
);
// Subscribe to events
connector.on('connect', (session) => print(session));
connector.on('session_update', (payload) => print(payload));
connector.on('disconnect', (session) => print(session));
// Create a new session
if (!connector.connected) {
session = await connector.createSession(
chainId: 97,
onDisplayUri: (uri) async => {print(uri), await launch(uri)});
}
setState(() {
account = session.accounts[0];
print(account);
});
if (account != null) {
final client = Web3Client(rpc, Client());
EthereumWalletConnectProvider provider =
EthereumWalletConnectProvider(connector);
credentials = WalletConnectEthereumCredentials(provider: provider);
yourContract = ethUtils.getDeployedContract(myAddress, client);
}
It sometimes happened to me as well.
I had just closed the MetaMask app and clicked on the button (Which triggered this function) and it worked fine.
I made a library for this, web3_connect, uses the same code and it gets the address back just fine for me

Flutter Send user to another screen if response is 401 or 403

I have functions witch I use to get data from the api, and the user can be logged in, but the admin can change the password of the employee, so when the user comes back to the app the besic auth token that is saved in local storage isnt the same as the one that the admin changed to since the admin changed the password, so all i need is that if there is status code such as 401 or 403 to send the user back to the log in screen. And if the response code is 500 to show like an image to come back later.
Future<Response> fetchWorkingLocationData() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var authorization = prefs.getString('authorization');
var url = 'https://dev.api.wurk.skyver.co/api/v1/projects';
basicAuth = 'Basic ' +
base64Encode(
utf8.encode('${phoneNumberController.text}:${passwordController.text}'),
);
response2 = await http.get(
Uri.parse(url),
headers: <String, String>{
'authorization': authorization ?? basicAuth.toString()
},
);
return response2;
}
You can write custom logic based on the statusCode
So something like:
if (response2.statusCode == HttpStatus.unauthorized) {
Navigator.pushNamed(
context,
'login',
);
}
If you don't have context for the Navigator, check out https://medium.com/flutter-community/navigate-without-context-in-flutter-with-a-navigation-service-e6d76e880c1c

Flutter google sign in serverAuthCode

I'm using this flutter plugin google_sign_in 5.2.1
works good I get the response
{displayName: Mario Mc, email: myemail#gmail.com, id: 117816213074325689769, photoUrl: https://lh3.googleusercontent.com/a-/AOh14GgyaPy7ik693hjyIBmtW5IRXUdCXluaeI=s96-c, serverAuthCode: 4/0AX4XfWiqJ1DMfPaDbgf6gOFVMCfgMicyPqGk25bxjKfA4wq7bJCCu-TWRB8c3rAz_g}
My question is: what is serverAuthCode?
And what's id: 117816213074325689769 used for
And after I send that serverAuthCode to the server, how do I verify that code is legit by calling google servers(as you know any person can send a fake serverAuthCode, so we need to verify it before saving it or do something with it)
I want to use PHP in the server side
thanks
What you can do is use this to get the accessToken then send it to the server
// sign In With Google
_googleSignIn.signIn().then((userData) {
userData.authentication.then((googleKey) {
setState(() {
// Retrieve the email from Google auth
googleEmail = userData.email;
googleId = userData.id;
googlePhotoUrl = userData.photoUrl;
googleServerAuthCode = userData.serverAuthCode;
googleAccessToken = googleKey.accessToken;
googleIdToken = googleKey.idToken;
});
print("googleAccessToken");
print(googleAccessToken);
// call your login function if no errors
checkInternetAndLoginWithGoogle();
}).catchError((err) {
print('inner error');
});
}).catchError((err) {
print('error occurred');
print(err);
});
in the server side, you can verify that access token by calling
https://www.googleapis.com/oauth2/v3/tokeninfo?access_token=<access token>
you will get an answer if that token is valid or expired
Also, you can call this to get user info such as name, email, photo etc.
https://www.googleapis.com/oauth2/v3/userinfo?access_token=<access token>

Is there a way to redirect to a payment gateway via flutter with some data?

I am using JazzCash Platform for online payment in Pakistan, All I need to do is make a Map<String,String> and redirect user to Jazzcash's website with the Map.
I checked out Url_Launcher (https://pub.dev/packages/url_launcher) and WebView For Flutter (https://pub.dev/packages/webview_flutter) but both of them are not accepting body as their parameter.
Is there a way to do this in Flutter?
Here is the link for doing it Natively On Android : https://www.youtube.com/watch?v=MsBB80UBxeU
My Map:
var temp = {
"pp_Amount": "1599",
"pp_BillReference": "billRef",
"pp_CustomerEmail": user.email,
"pp_CustomerID": user.userId,
"pp_CustomerMobile": user.phoneNumber,
"pp_Description": "Description of transaction",
"pp_IsRegisteredCustomer": "Yes",
"pp_Language": "EN",
"pp_MerchantID": "######",
"pp_Password": "######",
"pp_ReturnURL": "http//localhost/case.php",
"pp_TxnCurrency": "PKR",
"pp_TxnDateTime": currentDate,
"pp_TxnExpiryDateTime": expDate,
"pp_TxnRefNo": refNo,
"pp_TxnType": "MPAY",
"pp_Version": "2.0",
"ppmpf_1": "1",
"ppmpf_2": "2",
"ppmpf_3": "3",
"ppmpf_4": "4",
"ppmpf_5": "5",
};
URL Launcher Code, I tried sending the data in header, did not worked there either:
Future<void> _launchInBrowser(
String url, Map<String, String> header1) async {
print('In Launch Func: $header1');
if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: false,
forceWebView: false,
headers: header1,
);
} else {
throw 'Could not launch $url';
}
}
It works perfectly fine when I do http.post request but I need it to be redirected in the browser..
This is something not meant for url_launcher or webview to do. On native android, a mobile SDK for the payment gateway is used.
What you need is a flutter plugin/package for this payment gateway. Head on to pub.dev to see if there is a plugin/package available. In the absence of non, you could consider building a plugin off the mobile SDK.