Parse user not updating for just one specific user - swift

I was wondering if anyone has seen a case where Parse User table doesn't update for a specific user. I have a pretty simple code:
PFUser.current()?["TorF"] = true
PFUser.current()?.saveInBackground(block: { (success, error) in
if error != nil {
print(error)
} else {
}
})
I have checks in other places of the app regarding whether there is a current PFUser, and my database shows that the user is logged in and PFUser.current() is correctly assigned to this user. The simple operation above works for all other users except for one specific user. Has anyone encountered something like this?

I found out that this was happening because the user had changed his password and therefore invalidated his access token. The place to check for whether the user's access token is valid is via Graph request.

Related

Can you validate whether a user has been recently authenticated on Firebase (Swift)?

Is there a way to check if a user has recently authenticated on Firebase to avoid this message when trying to delete a user: "This operation is sensitive and requires recent authentication. Log in again before retrying this request."
I have been playing around trying to compare lastSignInDate (below) to current time but there seems to be a large margin of error on this which can cause problems:
firebase.auth().currentUser.metadata.lastSignInTime
Are there any functions that can return a simple boolean as to whether a user has recently authenticated so the user.delete() function will work properly?
Thanks so much!
The best way to do this is by checking if the response has an error, like so:
let user = Auth.auth().currentUser
user.delete { error in
if let error = error {
if (error.code == "auth/requires-recent-login") {
// The user's credentials are too old. Prompt Login screen.
}
} else {
// ...
}
}
According to Firebase Documentation, There's no other approach to this other than comparing the current date with firebase.auth().currentUser.metadata.lastSignInDate (Only if you have the Admin SDK on your app, but you most probably do not need that for enabling a user to delete themselves).

Test for account partially logged into cloudkit? "Update Apple ID Settings"

I've got an iOS app that is reliant on cloudkit for much of the functionality. However, I seem to be able to get in a state where the user is partially logged in. Basic cloudkit login checks pass, I can get my recordID, but I can't read or write to records like I can when I'm fully logged in.
Full details below - any ideas on how to identify this state without testing a read or write?
Upon launch of the phone, I get an 'Update Apple ID Settings' alert that states
"Some account services will not be available until you sign in again"
So, the issue is clearly related to that (which seems to be frequent with the simulator...). If I got to my settings and re-enter my password, all is well with the world. I can deal with this by error handling on an attempt to read or write, but I'd rather check in advance and warn the user appropriately.
How I check today:
At launch, I check to see if the user is logged in to cloudkit:
if FileManager.default.ubiquityIdentityToken != nil {
print("User logged in") // IT PASSES IN THIS STATE
}
else {
print("User is not logged in")
}
So far, so good. The test passes, the user is logged in. However, when I go to read or write, it is clear that I'm NOT logged in. For example, I'll get a CKErrorPermissionFailure when trying to write.
Additional note - in the current, 'partially'? logged in state, the below returns the correct recordID for my user:
let container = CKContainer.default()
container.fetchUserRecordID() { recordID, error in
Any ideas on how to programatically identify this partial state for cloudkit? Thanks!
I haven't found an answer that will address this, but wanted to document two things that could be of use
While the status check returns active, if I then try to fetch a record that requires you to be logged into iCloud, it fails and I can use that failure to determine logout status.
The other issue I've run into is a handful of users that have iCloud turned on but do NOT have iCloud Drive enabled for some reason. You can check for that with the approach below:
CKContainer.default().accountStatus { (accountstatus, error) in
switch accountstatus {
case .noAccount:
log.error("user logged out of iCloud OR iCloud Drive off")
case .restricted:
print("restricted")
case .available:
print("user logged into iCloud and iCloud drive")
case .couldNotDetermine:
log.warning("could not determine account status")
default:
log.error("New account status returned")
}
}

Duplicated anonymous users when session expired in Parse platforms

if let cachedUser = PFUser.current() {
// proceed to save some objects
} else {
PFAnonymousUtils.logIn{ (user, error) in
// proceed to save some objects
if ((error as NSError).code == 209) {
// session expired, logout and call PFAnonymousUtils.logIn again later
PFUser.logOut()
}
}
}
For a simple Swift mobile app, we save data on parse backend anonymously. If there is session expiration error (1 year default on Parser server), we will have to do something about it or we wont be able to save anything anymore. We therefore logout and re-login again.
Once we logout and re-login again, this creates a second new User on the backend.
This creates a problem - we no longer have an accurate picture of the number of users on the backend.
What was wrong in the flow above? Is there a way to prevent duplicated anonymous user when handling expired session?
It is possible to increase the default session duration in your server configuration.
You can also add the code below to your server configuration...
expireInactiveSessions: false
This thread may provide further useful insights into this issue.

firebase error when deleting user account "This operation is sensitive and requires recent authentication. Log in again before retrying this request."

When I want to delete a firebase user account in my application, the operation passes normally if the user has recently logged but after a period of time if I try to delete the user I get this error
"This operation is sensitive and requires recent authentication. Log in again before retrying this request."
Normally the firebase refresh the user session automatically but I didn't find why he want the user to log again and even the value of Auth.auth().currentUser is not nil. Thank you for your help !
this is my code to delete the user account :
#objc func deleteAccountAction(){
self.showProgressView()
let user = Auth.auth().currentUser
let id=Auth.auth().currentUser?.uid
self.refProducts.child(id!).removeValue { error, _ in
if(error != nil){
print("firebase remove error")
print(error?.localizedDescription.description ?? nil)
self.dismissHUD(isAnimated: true)
}
else{
self.refUsers.child(id!).removeValue { error, _ in
if(error != nil){
print("firebase remove error")
print("error while deleting user from firebase: "+error!.localizedDescription)
self.dismissHUD(isAnimated: true)
}
else {
user?.delete { error in
if error != nil {
print("error while deleting user:" + error!.localizedDescription)
self.dismissHUD(isAnimated: true)
} else {
UserDefaults.standard.removeObject(forKey: "USER_UID")
UserDefaults.standard.synchronize
self.dismissHUD(isAnimated: true)
let nextVC = self.storyboard?.instantiateViewController(withIdentifier: "StartingViewController") as! StartingViewController
nextVC.isAccoundDeleted=true
GlobalVar.user=nil
self.navigationController?.pushViewController(nextVC, animated: true)
}
}
}
}
}
}
}
For certain sensitive operations (such as changing the user's password, or deleting the user account), Firebase requires that the user has recently signed in. If the user hasn't signed in recently when you try to perform such an operation, Firebase throws the exception you get.
When you get this exception, you should ask the user to re-enter their credentials, and retry the operation.
From the documentation on handling errors:
[Deleting a user account] is a security sensitive operation that requires a recent login from the user. This error indicates the user has not signed in recently enough. To resolve, reauthenticate the user by invoking reauthenticateWithCredential:completion: on FIRUser.
In addition to Frank van's answer, time span for that is 5 minutes. After 5 minutes of login you cannot do such operations.
you can refer FIRAuthErrorCode (check out error code 17014 : FIRAuthErrorCodeRequiresRecentLogin = 17014)
Here is a workaround:
Make a call to a cloud function that performs the user account deletion and sign out the client. You must ensure proper guards for this cloud function so that it is not maliciously used.
Show courtesy to your users. Offer them with a proper dialog showing that this is irreversible and all relevant user data will be deleted permanently. Only call the function if the user accepts the consequences.
PSA edit:
Although this approach will work, it will have an improper risk imposed on your user profile and data. The requirement to have the user sign in again for the delete account procedure serves a higher objective which is an additional layer of protection for the user account. By bypassing it as the solution suggests you are imposing a risk that another actor using the device will be able to delete the account without any additional checks. it is a procedure that is irreversible so if it was done by mistake then there is no way to go back.
What you can do (its probably the most easy way) is to save login and password of the user in the local storage when they log in first time (for example using AsyncStorage) and once they want to delete the account log them in again without needing them to reenter credentials shortly before you delete the account. They wont even noticed you logged them in again before deleting the account.
Im not a security expert but the password and email would be stored localy without access to the outside world so I do not see any concerns about security issues there.
Once you delete the app, the local storage is gone anyways, at least with AsyncStorage.
Once you logout a user and use another account, the new account credentials would overwrite the old ones from the local storage.

Google Sign-In with Passportjs not getting authenticated

I'm using Sails with Passport for authentication. I'm using passport-google-oauth(OAuth2Strategy) and passport-facebook for enabling Google Sign-in.
I'm not too well-versed with Passport, so pardon me if this is a rookie question. I've set up login via Facebook and it works just fine. With Google, I do receive an authorization code after allowing access to the app, but the I'm eventually not authenticated. I'm guessing the same code should work for both Facebook and Google since the strategies are both based on oauth2.
I'm not even sure what code to share, since I'm using the auto-generated code from sails-generate-auth, but do let me know if there's anything else I can share.
Any ideas on why this might be happening? The app is locally hosted but that's unlikely to be the problem since I am getting to the authorization stage anyway.
I faced the same problem and it was located here in in api/services/passport.js:
// If the profile object contains a list of emails, grab the first one and
// add it to the user.
if (profile.hasOwnProperty('emails')) {
user.email = profile.emails[0].value;
}
// If the profile object contains a username, add it to the user.
if (profile.hasOwnProperty('username')) {
user.username = profile.username;
}
// If neither an email or a username was available in the profile, we don't
// have a way of identifying the user in the future. Throw an error and let
// whoever's next in the line take care of it.
if (!user.username && !user.email) {
return next(new Error('Neither a username nor email was available'));
}
The Google service was not returning a profile.username property.
Because of it, the user is not saved in the database and cannot be authenticated. Then the passport callback receives an empty user, so the function that handles errors is fired and the user is redirected to the login page.
This change allows to use the displayName property as the username:
// If the profile object contains a list of emails, grab the first one and
// add it to the user.
if (profile.hasOwnProperty('emails')) {
user.email = profile.emails[0].value;
}
// If the profile object contains a username, add it to the user.
if (profile.hasOwnProperty('username')) {
user.username = profile.username;
}
/** Content not generated BEGIN */
// If the username property was empty and the profile object
// contains a property "displayName", add it to the user.
if (!user.username && profile.hasOwnProperty('displayName')) {
console.log(profile); // <= Use it to check the content given by Google about the user
user.username = profile.displayName;
}
/** Content not generated END */
// If neither an email or a username was available in the profile, we don't
// have a way of identifying the user in the future. Throw an error and let
// whoever's next in the line take care of it.
if (!user.username && !user.email) {
return next(new Error('Neither a username nor email was available'));
}
You could also use the profile.id property because profile.displayName is not necessarily unique (ie: two Google accounts can have an identical displayName). But it is also true accross different services: a Twitter account could also have the same username than a Facebook account. If both register on your application, you will have a bug. This is a problem from the code generated by sails-generate-auth and you should adapt it with the behavior that you want.
I will propose a PR if this solution works for you too.
Alright, so this ultimately turned out to be a known issue with the API.
TL;DR: Enable the Google+ API and the Contacts API as mentioned here. (The Contacts API isn't required, as #AlexisN-o pointed out in the comments. My setup worked as desired with Contacts API disabled. This obviously depends on what scope you're using.)
I believe it's not a nice way of failing since this was an API error that was prevented from bubbling up. Anyway, I dug into passport.authenticate to figure out what was going wrong. This eventually calls the authenticate method defined in the package corresponding to the strategy (oauth2 in this case). In here (passport-google-oauth/lib/passport-google-oauth/oauth2.js) I found that the accessToken was indeed being fetched from Google, so things should be working. This indicated that there was a problem with the requests being made to the token urls. So I ventured a little further into passport-oauth2/lib/strategy.js and finally managed to log this error:
{ [InternalOAuthError: failed to fetch user profile]
name: 'InternalOAuthError',
message: 'failed to fetch user profile',
oauthError:
{ statusCode: 403,
data: '{
"error": {
"errors": [{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured. The API (Google+ API) is not enabled for your project. Please use the Google Developers Console to update your configuration.",
"extendedHelp": "https://console.developers.google.com"
}],
"code": 403,
"message": "Access Not Configured. The API (Google+ API) is not enabled for your project. Please use the Google Developers Console to update your configuration."
}
}'
} }
This was the end of the hunt for me and the first result for the error search led to the correct answer. Weird fix though.