SwiftUI Firebase: Sending a message to the mail - ios

In the function I want to add sending a message to the confirmation email, if you confirm, then you get to Homescreen(), else SignUp().
What do I need to add to my code?
func register(){
if self.email != ""{
if self.pass == self.repass{
Auth.auth().createUser(withEmail: self.email, password: self.pass) { (res, err) in
if err != nil{
self.error = err!.localizedDescription
self.alert.toggle()
return
}
print("success")
UserDefaults.standard.set(true, forKey: "status")
NotificationCenter.default.post(name: NSNotification.Name("status"), object: nil)
}
}
else{
self.error = "Password mismatch"
self.alert.toggle()
}
}
else{
self.error = "Please fill all the contents properly"
self.alert.toggle()
}
}
SignUp() - View where registration takes place
Homescreen() - View where the message about successful registration appears

You can first try to sign the user in with email using following code:
Auth.auth().signIn(withEmail: email, link: self.link) { authResult, error in
// ...
}
If there is an error, present the error alert to the user.
If sign in was successful, you can use the following code to get the current user:
if let user = Auth.auth().currentUser {
}
And inside of the curly brackets just check if current user has already verified the E-Mail with user.isEmailVerified
If that is the case, then simply present your Homescreen
If current user has not verified his E-Mail yet, you can present an alert, where the user can choose if he wants to have the verification E-Mail sent out again. If that is the case, you can simply resend the E-Mail with
user.sendEmailVerification {error in
}
and the user will get his verification E-Mail or there can occur an error while sending the Email so you should handle that error aswell!
Good luck!
You can also check the Firebase docs for Email Verification

Related

How to detect if an email address change was reverted?

I was working on the user profile page of my app and I am allowing the user to change their email address. If the user email address is changed successfully, the data in the firebase database of the particular user will be updated. Also, After successfully changing the email address, firebase will send an email to the user's previous email address (the user email address before it was changed to the new one) asking if it was the actual owner of the account who changed the email address and there will be a link to reset their email. If the user chooses to reset the email (for whatever reason), the user's new email will be changed to the previous email. But the problem is that the data in the database will not be updated, how can I detect this change (email reset) and update the database?
authenticateUserAlert.addAction(UIAlertAction(title: "Done", style: .default, handler: { [weak authenticateUserAlert] (_) in
// Print the user email
let emailTextField = authenticateUserAlert?.textFields![0]
print("Email: \(emailTextField!.text!)")
// Print the user password
let passwordTextField = authenticateUserAlert?.textFields![1]
print("Password: \(passwordTextField!.text!)")
// Re-authenticate the user
let user = Auth.auth().currentUser
let credential = EmailAuthProvider.credential(withEmail: emailTextField!.text!, password: passwordTextField!.text!)
user?.reauthenticate(with: credential, completion: { (result, error) in
if error != nil {
// Alert: What ever the error
print(error!.localizedDescription)
Alerts.errorAlert(on: vc, error: error!.localizedDescription, dismissAlert: false)
} else {
print(result!)
let editProfilePage = EditUserProfile()
editProfilePage.updateUserInfo()
}
})
}))
Here is what I tried according to an answer
Auth.auth().currentUser?.reload(completion: { (Error) in
//Completion handler
if let email = Auth.auth().currentUser?.email {
UserDataRetrieval.userEmail = email
self.emailLabel.text = email
print(Auth.auth().currentUser?.email)
}
})
It depends on the type of authentication you are using but honestly you should just use the email that is part of the authenticated account and then you don't need to worry about updating it in the database.
You can always just get the users email by using Auth.auth().currentUser.email
Update
Found a workaround to the issue of the credential data, try using
Auth.auth().currentUser?.reload(completion: { (Error) in
if (Error != nil) {
//Do something with error
} else {
//Do something with success or do nothing
}
})
Just call update credentials at the start of the app if you want to always have to most up to date credentials
You can always build your own custom handler for the email change revocation landing page. In that landing page you can update your database.
Check the official docs on how to do that.

Firebase Auth and Swift: Check if email already in database

I'm working on an iOS app which will use Firebase for user management (sign up, sign in, etc.)
I'm new to Firebase, but it's mostly going ok. I've connected it, I have created users and logged in, etc.
But, I'm trying to change my UI so that the "Sign up" button is initially hidden and will only appear when:
all fields are not empty
email address is valid (using regex)
email address in not already in the database
user name is not already in the database
password and confirmPassword fields are equal
I can't figure out #3 and #4.
I've been reading documentation, watching videos, chasing links all over StackO and beyond, but I can't figure it out.
Can anyone point me in the right direction?
If you are using email & password authentication, the solution is very simple.
Firebase Authentication will not allow duplicate emails so when the createUser function is executed, if the email already exists Firebase will return a emailAlreadyInUse error in the error parameter. You can then cast this to an NSError to see which one it is and handle appropriately.
So the function is like this
Auth.auth().createUser(withEmail: createEmail, password: password ) { user, error in
if let x = error {
let err = x as NSError
switch err.code {
case AuthErrorCode.wrongPassword.rawValue:
print("wrong password")
case AuthErrorCode.invalidEmail.rawValue:
print("invalid email")
case AuthErrorCode.accountExistsWithDifferentCredential.rawValue:
print("accountExistsWithDifferentCredential")
case AuthErrorCode.emailAlreadyInUse.rawValue: //<- Your Error
print("email is alreay in use")
default:
print("unknown error: \(err.localizedDescription)")
}
//return
} else {
//continue to app
}
I threw some random errors into that case statement but check the link for a complete list of all AuthErrorCodes.
You can also do this
Auth.auth().fetchSignInMethods(forEmail: user, completion: { (signInMethods, error) in
print(signInMethods)
})
I think you can check it by using this method
let ref1 = Database.database().reference().child("Users").queryOrdered(byChild: "UserName").queryEqual(toValue: "UserName enter by user")
ref1.observeSingleEvent(of: .value) { (sanpshot) in
print(sanpshot.exists()) // it will return true or false
}
and same for email.

Firebase Email Verification Redirect Url

I incorporated Firebase's email verification for my iOS mobile app and am trying to resolve the following issues:
The length of the redirect url appears extremely long. It looks like it repeats itself.
https://app.page.link?link=https://app.firebaseapp.com//auth/action?apiKey%3XXX%26mode%3DverifyEmail%26oobCode%3XXX%26continueUrl%3Dhttps://www.app.com/?verifyemail%253Demail#gmail.com%26lang%3Den&ibi=com.app.app&ifl=https://app.firebaseapp.com//auth/action?apiKey%3XXX%26mode%3DverifyEmail%26oobCode%3XXX%26continueUrl%3Dhttps://www.app.com/?verifyemail%253Demail#gmail.com%26lang%3Den
When I set handleCodeInApp equal to true, and am redirected back to the app when I click on the redirect url, the user's email is not verified. Whereas when I set it to false and go through Firebase's provided web widget, it does get verified. Wasn't able to find documentation that outlined handling the former in swift...
Any thoughts are appreciated.
func sendActivationEmail(_ user: User) {
let actionCodeSettings = ActionCodeSettings.init()
let redirectUrl = String(format: "https://www.app.com/?verifyemail=%#", user.email!)
actionCodeSettings.handleCodeInApp = true
actionCodeSettings.url = URL(string: redirectUrl)
actionCodeSettings.setIOSBundleID("com.app.app")
Auth.auth().currentUser?.sendEmailVerification(with: actionCodeSettings) { error in
guard error == nil else {
AlertController.showAlert(self, title: "Send Error", message: error!.localizedDescription)
return
}
}
}
Make sure you're verifying the oobCode that is part of the callback URL.
Auth.auth().applyActionCode(oobCode!, completion: { (err) in
if err == nil {
// reload the current user
}
})
Once you have done that, try reloading the the user's profile from the server after verifying the email.
Auth.auth().currentUser?.reload(completion: {
(error) in
if(Auth.auth().currentUser?.isEmailVerified)! {
print("email verified")
} else {
print("email NOT verified")
}
})

Firebase iOS Authentication with an unconfirmed gmail account after Google Sign in

Scenario:
A user creates a gmail.com email account and doesn't confirm it.
A user uses Google sign in button to log in. Firebase replaces his/her email accout to Google sign in account as the email hasn't been confirmed.
A user tries to log in with a gmail email account.
Question
What error should I catch to tell the user that an email has already been user with another method of authentication?
Code
func signIn(with email: String, and password: String) {
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
Auth.auth().signIn(with: credential) { (user, error) in
if let error = error {
print(error.localizedDescription)
self.delegate.hideActivityIndicatorView()
if let errorCode = AuthErrorCode(rawValue: error._code) {
switch errorCode {
case .accountExistsWithDifferentCredential, .credentialAlreadyInUse:
self.delegate.presentAlert(title: "An account with this email already exists", message: nil)
case .userNotFound, .wrongPassword, .invalidEmail:
self.delegate.presentAlert(title: "Unable to Sign In", message: "Either email or password is incorrect.")
default:
self.delegate.presentAlert(title: "Something went wrong, please try again later.", message: nil)
return
}
}
}
print("Successful Email Sign In.")
self.delegate.hideActivityIndicatorView()
}
}

Firebase unlink email/password auth from user on iOS

I'm trying to unlink email/password authentication from a user in Swift on iOS. I've read the documentation and managed to link and unlink Facebook authentication without a problem. However, after linking email/password credentials successfully, the providerData object is nil. The providerID is "Firebase" but when I pass that to the unlink code the following error is thrown:
Error Domain=FIRAuthErrorDomain Code=17016 "User was not linked to an account with the given provider." UserInfo={NSLocalizedDescription=User was not linked to an account with the given provider., error_name=ERROR_NO_SUCH_PROVIDER}
The unlink code I'm using is:
let providerId = (FIRAuth.auth()?.currentUser?.providerID)!
print("Trying to unlink:",providerId) // providerId = "Firebase"
FIRAuth.auth()?.currentUser?.unlinkFromProvider(providerId) { user, error in
if let error = error {
print("Unlink error:", error)
} else {
// Provider unlinked from account successfully
print("Unlinked...user.uid:", user!.uid, "Anonymous?:", user!.anonymous)
}
}
Reading the docs and having got it working for Facebook, I expected the providerData array to be populated with something after email authentication. So is my linking code wrong (it doesn't throw an error and appears to work fine)?
My linking code:
let credential = FIREmailPasswordAuthProvider.credentialWithEmail(email, password: password)
FIRAuth.auth()?.currentUser!.linkWithCredential(credential) { (user, error) in
if user != nil && error == nil {
// Success
self.success?(user: user!)
dispatch_async(dispatch_get_main_queue(), {
self.dismissViewControllerAnimated(true, completion: nil)
if type == "new" {
print("New user logged in...")
}
if type == "existing" {
print("Existing user logged in...")
}
})
} else {
print("Login error:",error)
self.showOKAlertWithTitle("Login Error", message: error!.localizedDescription)
}
}
Any pointers of how I can modify my approach would be great.
To get the profile information retrieved from the sign-in providers linked to a user, use the providerData property.
if let user = FIRAuth.auth()?.currentUser {
for profile in user.providerData {
// Id of the provider (ex: facebook.com)
let providerID = profile.providerID
}
} else {
// No user is signed in.
}
Calling FIRAuth.auth()?.currentUser?.providerID will result to "firebase".

Resources