问题
I'm using Firebase database and little confused with next situation.
Let's imagine i have todo app. I use standard Firebase Auth
system for sync items
between user devices. But in other case user could work anonymously without synchronization.
Step 1:
User launch app first time, and in AppDelegate
i created Anonymous user:
FIRAuth.auth()?.addStateDidChangeListener { auth, user in
if let _user = user {
if _user.isAnonymous {
print("User logged in as anonymous. Saving uid to user defaults storage.")
UserDefaults.standard.setValue(_user.uid, forKey: "uid")
} else {
print("User logged in with email: \(_user.email)")
}
} else {
FIRAuth.auth()?.signInAnonymously() { (user, error) in
if let _error = error {
print("Anonymous signIn error: \(_error)")
}
}
}
}
Step 2:
This anonymous user created few todo items and decided signUp:
let credential = FIREmailPasswordAuthProvider.credential(withEmail: emailField.text!, password: passwordField.text!)
FIRAuth.auth()?.currentUser?.link(with: credential, completion: { user, error in
if error == nil {
FIRAuth.auth()!.signIn(withEmail: emailField.text!,
password: passwordField.text!)
}
})
So i have modified previous code and change owner of created todo items:
if let prevUserUID = UserDefaults.standard.string(forKey: "uid"), prevUserUID != _user.uid {
FIRDatabase.database().reference().child("todo-items").queryOrdered(byChild: "user").queryEqual(toValue: prevUserUID).observe(.value, with: { snapshot in
for item in snapshot.children {
var todoItem = TodoItem(snapshot: item as! FIRDataSnapshot)
todoItem.user = _user.uid
todoItem.ref?.setValue(todoItem.toAnyObject())
}
})
print("Data migrated.")
}
Ok everything works. But, now user logged out. An i created new anonymous user. Then he login again and i merge data. But i can't link account, because i already did it before. And i can't delete anonymous user from Auth
database(my question). And we get zombie! unused anonymous account. And if user will log in/log out 1000 times we get 1000 anonymous accounts.
回答1:
When you link the credential with the currentUser you are logged already, don't need for:
FIRAuth.auth()!.signIn
You keep the UID of the anonymous user.
If user already have an account, in this case you need to:
currentUser.delete()
And then logIn with the credentials provided
来源:https://stackoverflow.com/questions/41555145/remove-anonymous-user-from-auth-database