AWS Cognito "confirmSignUp" is going in error code - ios

I am using Cognito login and signup. If I am confirming OTP Code it is giving me an error.
An error occurred while registering a user AuthError: Username/client id combination not found.
Recovery suggestion: Make sure that the user is present in the backend
Caused by:
userNotFound
func confirmSignUp(for username: String, with confirmationCode: String) {
_ = Amplify.Auth.confirmSignUp(for: username, confirmationCode: confirmationCode) { result in
switch result {
case .success(_):
print("Confirm signUp succeeded")
DispatchQueue.main.async {
self.checkOTP(otp:self.storeOTP)
}
case .failure(let error):
print("An error occurred while registering a user \(error)")
DispatchQueue.main.async {
self.alert(title: "", message: "OTP not match")
}
}
}
}

Related

Error "Amplify.AuthError error 2" thrown during the sign in flow on iOS with amplify-swift 1.15.1

During the sign in flow in iOS, for few users the Authentication module of the amplify-swift library throws the error The operation couldn't be completed. (Amplify.AuthError error 2). I have searched in the amplify-swift repository for possible solutions but couldn't find any. The version of Amplify pod used in code is 1.15.1.
func nativeLogin(
email: String?, password: String?, completion: #escaping (Result<Authstate, Error>) -> Void
) {
let isAlreadySignedIn = AWSMobileClient.default().isSignedIn
if isAlreadySignedIn {
// Do signout and then sign in
let options = AuthSignOutRequest.Options(globalSignOut: true)
Amplify.Auth.signOut(options: options) {
result in
DispatchQueue.main.async {
if case .success = result {
// completion(.success(.logout))
guard let email = email,
let password = password
else {
self.response(
completion, .failure(AuthError.passwordValidationError("Missing Email/Password")))
return
}
// log event
self.signIn(email: email, password: password, completion: completion)
} else if case .failure(let error) = result {
// log event
completion(.failure(error))
}
}
}
} else {
self.signIn(email: email, password: password, completion: completion)
}
}
The reason that the signOut method is invoked before actually signing in is to ensure that last logged in user is signed out first.
Can anyone explain where am I going wrong? Or has this error been already fixed in the latest version (2.2.1) of the amplify-swift library?

StoreKit Purchase Error code 400 and SK Error Domain 0 returning when user is going to start a trail by selecting a subscription service

StoreKit Purchase Error code 400 and SK Error Domain 0 returning when user is going to start a trial by selecting a subscription service.
Following are the error log on console:
Purchase Complition With Error: Error Domain=Subscription Service Code=400 "Purchase Error: The operation couldn’t be completed. (SKErrorDomain error 0.)" UserInfo={NSLocalizedDescription=Purchase Error: The operation couldn’t be completed. (SKErrorDomain error 0.)}
Following are the codes I have used for the purchase operation
func checkActiveSubscription() {
self.view.showActivity()
SubscriptionService.shared.activeSubscription(
types: [.month1, .months3, .months12]) { [weak self] result in
switch result {
case .success(let receiptVerificationDetails):
print("###################### Purchase Complition With Success:\n\(receiptVerificationDetails)")
if let receipt = receiptVerificationDetails.first {
self?.purchaseComplition(Result.success(receipt))
} else {
self?.view.hideActivity()
}
case .failure(let error):
self?.view.hideActivity()
print("Purchase Complition With Error: \(error)")
}
}
}
extension HeraAPIManager {
#discardableResult
static func updateSubscription(
receipt: String,
complition: ((EmptyModel.Response? , Error?) -> ())?) -> DataRequest? {
return HeraAPIManager.handleCall(
expecting: EmptyModel.Response.self,
endpoint: .subscriptions,
parameters:
["receipt-data": receipt,
"environment": HeraSubscriptionsEnvironment.currentEnvironment.rawValue],
complition: complition)
}
}
func purchaseComplition(_ result: Result<ReceiptVerificationDetails, Error>) {
switch result {
case .success(let receiptVerificationDetails):
print("###################### Purchase Complition With Success:\n\(receiptVerificationDetails)")
if let latestReceipt = receiptVerificationDetails.receiptInfo["latest_receipt"] as? String {
HeraAPIManager.updateSubscription(
receipt: latestReceipt) { [weak self] response, error in
if let error = error {
self?.view.hideActivity()
self?.view.showError(error.localizedDescription)
} else {
UserSession.shared.getUserInfo { _, _ in
self?.view.hideActivity()
let controller = R.storyboard.setupProfile.setupProfileWelcomeScreen()!
self?.navigationController?.setViewControllers([controller], animated: true)
// AppDelegate.setupRootController()
}
}
}
} else {
self.view.hideActivity()
}
case .failure(let error):
self.view.hideActivity()
print("Purchase Complition With Error: \(error)")
debugPrint(error.localizedDescription)
}
}
I am not familiar at all with InApp Purchase. This is an existing project that came to me and suddenly my manager wants to fix this and push an update Asap. Don't know what to do. Please anybody help me to sort out this.

Sign in with Apple - ASAuthorizationAppleIDProvider already signed in but notfound

recently I'm learning SiwA on
https://fluffy.es/sign-in-with-apple-tutorial-ios/
I tried to learn step-by step, however, I met some wired problem when I used "ASAuthorizationAppleIDProvider". I have saved the userID in local, but it returns notfound when using ASAuthorizationAppleIDProvider. I also delete the Apple ID used before in
Settings > Apple ID > Password & Security > Apps Using your Apple ID
But it stills return notfound when I re-login. Here is my code.
extension LoginViewController: ASAuthorizationControllerDelegate{
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
print("something bad", error)
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
if let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential{
UserDefaults.standard.set(appleIDCredential.user, forKey: appleAccount.userID)
}
}
}
if let userID = UserDefaults.standard.string(forKey: appleAccount.userID) {
ASAuthorizationAppleIDProvider().getCredentialState(forUserID: userID, completion: {
credentialState, error in
print(userID)
switch(credentialState){
case .authorized:
print("user remain logged in, proceed to another view")
self.performSegue(withIdentifier: "LoginToUserSegue", sender: nil)
case .revoked:
print("user logged in before but revoked")
case .notFound:
print("user haven't log in before")
default:
print("unknown state")
}
})
}
It indeed print userID so userID is not nil. But seems it's not match with the Apple ID so it shows notfound? Here is the error
[core] Credential State request returned with error: Error Domain=AKAuthenticationError Code=-7073 "(null)"
The problem is caused by simulator, if we change to device, there is no such problem. See reference:
failed to get credential.state and getCredentialStateForUserID

iOS link two firebase accounts error

I'm trying to link two firebase accounts
a phone account ( signed in ) to Anonymous account ( prevUser )
this is my code
func verifyCode() {
let credential = PhoneAuthProvider.provider().credential(
withVerificationID: self.verificationID,
verificationCode: phoneCode.text!)
let prevUser = Auth.auth().currentUser!
Auth.auth().signIn(with: credential) { (user, error) in
if let error = error {
print("1 something went wrong : ", error.localizedDescription)
return
}
print("the user ID is : " , user!.uid)
prevUser.link(with: credential, completion: { (user, error) in
if let error = error {
print("something went wrong : ", error.localizedDescription)
return
}
})
}
}
I keep getting the same error always
something went wrong : The SMS code has expired. Please re-send the verification
code to try again.
thanks in advance
There are 2 issues here:
You are signing in with the phone auth credential first and then linking to the same credential which contains the same underlying SMS code which is a one time code. This will always fail with the error you are getting since the Firebase Auth backend can only use the code once (it immediately expires the first time it is used).
Even if the code is usable more than once, you can't have more than one user with the same phone credential. You first sign in one user with that credential and then try to link it to another user. This will always fail with an error that the credential already exists on another account.
Step 1: You can verify the phone number by providing phone number string and in completion you will be returned a verificationID and error if any.
func verifyPhoneNumber(withPhoneNo phoneNo:String, completion: #escaping (_ error: Error?, _ verificationID: String?)->Void) {
PhoneAuthProvider.provider().verifyPhoneNumber(phoneNo) { (verificationID, error) in
if let error = error {
print(error.localizedDescription)
completion(error, verificationID)
} else {
print(verificationID ?? "no id provided")
completion(nil, verificationID)
}
}
}
Step 2: Linking Phone Number to the current User by providing the current user, 6digit verification code, verificationID obtained from the previous function.
In completion you will be returned with an error if any.
func linkPhoneNumber(withUser user: User, verificationCode: String, verificationID id: String, completion: #escaping (_ error: Error?)-> Void) {
let credential = PhoneAuthProvider.provider().credential(withVerificationID: id, verificationCode: verificationCode)
user.link(with: credential) { (user, error) in
if let error = error {
print(error.localizedDescription)
completion(error)
} else {
print(user!.uid)
completion(nil)
}
}
}

Firebase authentication tokens, check if valid

Is it possible to check if an authentication token is invalid?
FIRAuthErrorCode.errorCodeInvalidUserToken
this is shown as a possible error but I can't figure out how to access this error besides when logging in or resetting the password like below.
FIRAuth.auth()?.sendPasswordReset(withEmail: email, completion: { (error) in
if let err = error as? NSError {
if let errorCode = FIRAuthErrorCode(rawValue: err.code){
if errorCode == FIRAuthErrorCode.errorCodeInvalidUserToken{
self.alertFunc(title: "Error", message: "invalid token")
}
}
} else{
self.alertFunc(title: "Success", message: "Password reset email has been sent")
}
If a user has a few devices logged into the same account, and reset the password on one, then the others will not be able to post to firebase due to their invalid token. I need the apps on the other devices to be able to recognize the invalid token and then prompt the user for the username and password.
Any help or links would be appreciated, thanks!
FIRAuth.auth()?.currentUser?.getTokenWithCompletion({ (string, err) in
if err != nil{
if let err = err as NSError?{
if let error = FIRAuthErrorCode(rawValue: err.code){
switch error{
case .errorCodeInvalidCredential: self.delegate.invalidToken()
case .errorCodeInvalidUserToken: self.delegate.invalidToken()
case .errorCodeUserTokenExpired: self.delegate.invalidToken()
case .errorCodeInvalidCustomToken: self.delegate.invalidToken()
case .errorCodeCustomTokenMismatch: self.delegate.invalidToken()
default: print("call default error")
}
}
}
}
})

Resources