Deleting and logging out user causes invalid session token Swift Parse Server - ios

I've done this before and not had any problems. All I'm doing is deleting the current user and if that is successful logging them out and going back to the sign up view. I use the below code. This is the issue.
If a user signs up, I can delete and log them out successfully once. But if another user is created and I try to delete and log them out the user is deleted and when the logout attempts I got the error: Invalid session token.
Any help is much appreciated. Also please let me know if theres any other relevant code I can add.
PFUser.current()?.deleteInBackground(block: { (success, error) in
if error != nil {
print(error)
} else {
PFUser.logOutInBackground(block: { (error) in
if error != nil {
print(error)
} else {
self.performSegue(withIdentifier: "showLoginSignupView", sender: self)
}
})
}
})

I'm surprised this would work even the first time. If you've deleted a user, there is no user to log out. Try switching the order of those functions. Sign them out, then delete the user. You may need a cloud function for this so that the User can be deleted with the master key, as users should not have public destroy permissions.

Related

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")
}

Why does logging out user from firebase require error handling, but not getting current user?

I'm a bit new to error handling in swift. After going through multiple firebase tutorials I've become accustomed to mindlessly writing out my error handlers without understanding why they are required for certain cases and not required for others. I know that any time an error can be thrown, I must handle the error but I don't always know why an error might be thrown in the first place.
Why do we not need an error handler when getting the current user?
guard let currentUser = FIRAuth.auth()?.currentUser else {return}
But we do need one for signing out a user?
func logout() {
if FIRAuth.auth()?.currentUser != nil {
// there is a user signed in
do {
try? FIRAuth.auth()?.signOut()
} catch {
print("failed to sign out user")
}
}
Don't both have the potential to throw errors?
Signing out is really just a matter of forgetting whatever tokens were previously in place that identified the user. Nothing else really needs to happen that could "fail" and prevent the signout from finishing.

Removing a specific value off of firebase database

I am setting up a social media app and currently working on a way to create authentic usernames(no duplicates) for the user to enter, similar to that of Instagram.
The problem that I'm facing is that I can't find a way to delete the users previous username(in case anyone else wants to use it). The way that my database is setup for usernames is like:
Usernames
- username:"testUsername"
I have attempted to delete the code using this
let usernameRef = FIRDatabase.database().reference().child("Usernames").child("username").child(usersCurrentUsername)
usernameRef.removeValue(completionBlock: {(error, ref) in
if error != nil {
print("There was an error in removing the current username\(error?.localizedDescription)")
} else {
print(ref)
print("The child was removed")
}
})
I capture the users current username via snapshot in the viewdidload and store it in usersCurrentUsername.
Any help would be appreciated
let usernameRef = FIRDatabase.database().reference().child("Usernames").child("username");
usernameRef.removeValue();
Note that if the child of Usernames is only the username, the Usernames node will also be deleted.

Invalid session toked after deleting a user Parse Server Swift

Im running Parse Server on heroku and mLab and I use the following code to delete a user:
if PFUser.current() != nil {
PFUser.current()?.deleteInBackground(block: { (success, error) in
if error == nil {
self.performSegue(withIdentifier: "unwindToLoginFromSignUp", sender: self)
} else {
// Handle error
}
})
}
The issue is that after deleting a user if I create a new user I get the error "Invalid session token (Code: 209, Version: 1.14.2)". I understand what a session toked is but I'm not sure how I should be handling it when I delete a user.
Also the error does not cause a crash, it just shows up in the console. Any help is much appreciated!
I think you should store the currentUser object then log out the user first, and then delete the currentUser.
Once you delete the user without deleting the session, the app won't know that the current user doesn't exist any more, the session still remains, therefore you will get a session error after signing up another user.
But if you log out the user first, the current session will also be deleted, then you are free to create a new user.
I realized I forgot to log the user out after deleting their account and taking them back to the sigh up view.

Logout user when deleted from Parse data browser

I have a couple hundred users that I need to remove from my parse app. However, when I delete the user accounts the users are still able to use the app fully without a problem. Is there anyway to "force" the logout remotely? Or what else would you suggest? Thanks!
It sounds like the user is being cached on the device and I don't think parse has a remote way to clear cached data on there. I like to put a user refresh(now fetch since refresh is deprecated) function when app opens to get the latest data for that user.
You could put a fetch function when the app opens and if it returns a specific error, it would mean the user doesn't exist and then set the current user to nil. I'm not sure which error it returns and I'm at work so I can't try it right now. I would hope that if the user doesn't exist, it would return kPFErrorUserWithEmailNotFound = 205...
Here are the error codes: https://parse.com/docs/ios/api/Constants/PFErrorCode.html
You will have to give it a try but I am thinking something like this (sudo-code):
post.fetchIfNeededInBackgroundWithBlock {
(post: PFObject?, error: NSError?) -> Void in
if let someError = error {
if someError = kPFErrorUserWithEmailNotFound {
// User doesn't exist!
}
} else {
// User exists and is fetched successfully
}
}

Resources