Forget previously logged in facebook user? - ios

When I promt the user to log in with their facebook account I do it like this:
FBSession.openActiveSessionWithReadPermissions(["email"], allowLoginUI: true) { (session, state, error) -> Void in
if error == nil && state == .Open {
FBRequest.requestForMe().startWithCompletionHandler({ (connection, data_, error) in
println("Facebook data: ")
if error == nil {
let facebookInfo = data_ as NSDictionary
}
})
}
else {
self.SuperVC!.presentAlertView("Error", message: "Could not connect with facebook.", decline: "Ok", others: [])
}
Now, when its the first time logging in the user can enter their email and password... but the next time its not possible to do so, it remembers the previous user even if I clear token info like this:
FBSession.activeSession().closeAndClearTokenInformation()
I clear the token before promting to login, for testing purposes.
It only forgets if I reset the entire app, by deleting it or in the simulator 'Reset contents and settings'
Lets say that another user wants to log in on the same device, it is not possible.
How do I make it forget the previous user?

For me, none of the solutions above worked.
I was able to logout, but no way to change the user on the next login screen.
I found a way to change the user after logout from FB by initializing the FBSDKLoginManager as follow :
faceBookLoginManager = [[FBSDKLoginManager alloc] init];
faceBookLoginManager.loginBehavior = FBSDKLoginBehaviorWeb;
When using the above code, after the logOut was done using [faceBookLoginManager logOut]; FB login popup asks again for user name/password so another user can be used.

Facebook SDK takes your facebook login access from Safari. App forgets who the previous user was, if you just sign out of facebook in Safari.

I solved my issue by using another method for promting the user credentials.
I used
FBSession.activeSession().openWithBehavior(FBSessionLoginBehavior.ForcingWebView, completionHandler:{
// Stuff...
}
With the .ForcingWebView it always starts over and promting the users ceredntials.

[FBSession.activeSession closeAndClearTokenInformation];
[FBSession setActiveSession:nil];

Related

Firebase Anonymous Login - Why FirebaseID changes when logged to Facebook, but it remains the same when not logged to Facebook?

I have the following logic for allowing guest users to login to my app:
(1) Login as Anonymous.
(2) Check if Facebook is logged.
(3) If it is logged to Facebook, link to Anonymous.
(4) If link fails, Login to firebase passing facebook token to Firebase
If I am not logged in Facebook the Anonymous ID given by firebase after step (1) is always the same. However, the first time I login to Facebook, I link the account to firebase as in step (3). And from that onwards, I get a different Anonymous ID every time I go through the login process.
Question 1. Will the Anonymous ID in step (1) ALWAYS be the same until I login to Facebook for the first time?
Question 2. What is the best login flow to allow users to save data in the backend as guests, and link to facebook later when the user decides to do so?
Here is my swift code that implements my pseudo code:
func login() -> Promise<AuthCredential?> {
// Login as Anonymous. Check if FB is logged. If it is, link to Anonymous. If fails, pass FB token to Firebase
print("........................")
print("Starting Login")
return Promise { seal in
Auth.auth().signInAnonymously() { (authResult, error) in
print("-Done Login Anonymously", authResult?.credential, Auth.auth().currentUser?.uid)
if let error = error {
print("-DID NOT SIGNED UP WITH FIREBASE:", error)
seal.reject(error)
} else {
if AccessToken.isCurrentAccessTokenActive { // If Facebook token is active exchange for Firebase
let credential = FacebookAuthProvider.credential(withAccessToken: AccessToken.current!.tokenString)
print("-Loggged with FACEBOOK!!!!", credential)
Auth.auth().currentUser!.link(with: credential) { (result, error) in
print("-Linked Account!!!!??????????", result as Any, error as Any)
if error != nil {
Auth.auth().signIn(with: credential) { (authResult, error) in
print("-Signed UP in Firebase USIG FB. No Linking")
if let error = error {
print("-DID NOT SIGNED UP WITH FIREBASE:", error)
seal.reject(error)
} else {
print("-DID SIGNED UP WITH FIREBASE using FB:", Auth.auth().currentUser?.uid)
seal.fulfill(authResult?.credential)
}
}
}
}
}
// print("-Done Login", Auth.auth().currentUser?.uid)
// seal.fulfill(authResult?.credential)
}
}
}
}
The API documentation for signInAnonymously (javascript) reads:
If there is already an anonymous user signed in, that user will be
returned; otherwise, a new anonymous user identity will be created and
returned.
You probably only want to call signInAnonymously if there is no user signed into the app. It's best to wait to see if a user is already signed in using an auth state listener, as the sign-in process is not immediate.
Once you link the anonymous account with a full account, you should probably not call signInAnonymously again, since you probably want the user to stay signed in with their full account and no create another new anon account.

Check if user already has an account just by email

How do I check if a user exists in my Firebase Database only by email within Swift?
The first screen the user should see allows him to type in his email. After that he gets to the sign up page or the login page depending on wether or not the user exists.
You're looking for fetchSignInMethodsForEmail, which returns the sign-in methods with which the given email is registered. With that information you can build a sign-in screen.
Try with this:
Auth.auth().fetchProviders(forEmail: email) { (providers, error) in
if error != nil {
print(error?.localizedDescription)
} else {
print(providers)
}
}
If the email address has not yet been used, the empty list (providers) will be printed.

Swift - Firebase Authentication State Persistence

I'm currently thinking about implementing Firebase Auth to my Swift project, hence I've been reading some articles. - Namely among others this one.
I need some help understanding the given article. It's about "Authentication State Persistence". Does this mean, that if the value is set to local, the user will stay logged in even after closing the app? In other words, will he be able to sign up once and stay logged in until he decides to log out - even when he's offline?
Let's say a user decides not to create an account and logs in with "Anonymous Authentication" (I assume this is the type of login in this kind of case) - will he stay logged in forever as well or is there a danger of data loss, in case of going offline or closing the app?
First: the link you provided refers to a javascript firebase documentation
Second: the only thing available in IOS is you can create an anonymous user with
Auth.auth().signInAnonymously() { (authResult, error) in
// ...
let user = authResult.user
let isAnonymous = user.isAnonymous // true
let uid = user.uid
}
and you can convert it to a permanent user check This
Finally: whether the user is usual / anonymous , after you sign in you need to check this to show login/home screen every app open
if FIRAuth.auth()?.currentUser != nil {
print("user exists")
}
else {
print("No user")
}
and the user still exists unless you sign out regardless of whether you closed the app or not
If you are using the latest Firebase version, FIRAuth is now Auth:
if Auth.auth()?.currentUser != nil {
print("user exists")
}
else {
print("No user")
}

Parse Login iOS – Does not log in user after signing up

I am currently using Parse to create and log in users for my iOS app. After a user signs up with a new account, Parse does not log them in––it just clears the text fields. Some users get confused thinking the signup was unsuccessful, and try to put their information in again, prompting the "username taken" alert. How can I modify the Parse login so that it automatically logs in the user once they create a successful account? (I currently have a ParseLoginHelper class––would I make this modification in the PFSignUpViewControllerDelegate extension?)
If anyone has example code they would like to share in their answer, please note that I'm using Swift for my project.
When you are signing up (register) a new users you don't need to call the logIn function again in order to log them in to the app.
After the signing up process they are already logged in. In order to check if they are logged in you can check if the current user is not nil
if PFUser.currentUser() != nil {
}
At the end your sign up code should look like the following:
let user = PFUser()
user.username = "USERNAME"
user.password = "PASSWORD"
user.email = "EMAIL"
// add more fields
user.signUpInBackgroundWithBlock {
(succeeded: Bool, error: NSError?) -> Void in
if succeeded {
// here the current user should not be nil.
// if it is then please check for sessionToken
if PFUser.currentUser() != nil {
// user is logged in
}
}
}

Unable to Logout of Facebook within Unity IOS [duplicate]

I've managed to successfully log in FB using FB.Login function. Now I want to log out:
FB.Logout();
Debug.Log("FB IS LOGGED IN " + FB.IsLoggedIn);
I am expecting the above code to print the value of FB.IsLoggedIn as false and to ask me for a login and password on the next FB.Login.
In fact the value of FB.IsLoggedIn is true and I am not being logged out: next call to FB.Login does not ask for password and I am not being logged out when I open facebook site in my browser.
I've also tried to use the undocumented request to https://www.facebook.com/logout.php?next=[YourAppURL]&access_token=[ValidAccessToken] but it didn't make any effect for me.
How can I log the user out of facebook in my standalone unity application?
In fact what I need is to log in with different login and password.
Maybe I can invalidate the access token somehow which will cause the FB to ask me for login and password again?
Any help is much appreciated.
SDK version: 5.0.1
Build version: 140401.725cc2ecbc9002a
Unity Version 4.3.3f1 (c8ca9b6b9936)
I believe the FB.Logout operation is asynchronous, and the value of FB.IsLoggedIn would be true immediately after calling FB.Logout(). If you look at the documentation, it says:
You almost certainly should not use this function, which is provided
primarily for completeness. Having a logout control inside a game that
executes a Facebook-wide logout will violate users' expectations.
Instead, allow users to control their logged-in status on Facebook
itself.
Actually FB.Logout() has no delegate to let you know that account is successfully logout, so you have to create your own listner.
Secondly it will not sign you out from the actual device Facebook app or browser.
If you want to sign in with different account, so you can do by signing out explicitly from the app or browser.
Here is the code for how to detect that if you are logged out. It may useful to show Login and Logout button for Facebook that when to Login or Logout.
Here is the code from that you can determine the user has logged out within the Game.
public void OnFacebookLogout()
{
if (FB.IsLoggedIn)
{
FB.Logout ();
StartCoroutine ("CheckForSuccussfulLogout");
}
}
IEnumerator CheckForSuccussfulLogout()
{
if (FB.IsLoggedIn)
{
yield return new WaitForSeconds (0.1f);
StartCoroutine ("CheckForSuccussfulLogout");
} else
{
// Here you have successfully logged out.
// Do whatever you want as I do, I just enabled Login Button and Disabled
// logout button through this method.
EnableFacebookLoginButton ();
}
}
I'm not sure if it is correct but why not just do some while loop?
IEnumerator FBLogout (){
FB.Logout ();
while (FB.IsLoggedIn){
print ("Logging Out");
yield return null;
}
print ("Logout Successful");
}

Resources