问题
I currently have user authentication in my app using firebase and swift 3. Is there a way to only let users with a certain email address to sign up to use my app?
回答1:
Essentially what you want to do is include a boolean test to determine whether the email text contains the domain you want.
Here is a function that determines whether or not the input text contains a set domain.
func isValidEmail(testEmail:String, domain:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[\(domain)]+\\.[com]{3,\(domain.characters.count)}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
let result = emailTest.evaluate(with: testEmail)
return result
}
Here's an example of me using it
let customDomain = "mycompanyname"
let test = "frank@mycompanyname.com"
if isValidEmail(testEmail: test, domain: customDomain) == true {
//Test succeedes... Here you would register the users as normal
print("register \(test)")
}else{
//Test fails... Here you might tell the user that their email doesn't check out
print("register failed")
}
Additionally, I would take a look at Apples App Distribution Guide for if you want to distribute your app locally to say an employee base.
Hope this helps.
回答2:
You can do the following client and backend checks to enforce this:
- On the client side, you can block sign-in when an invalid email domain is provided. If you are using some federated sign in with Google or Facebook, etc, you can on return check the
currentUser.email
andcurrentUser.delete
the user if the email doesn't match your domain. Google also provides an 'hd' parameter to specify the user domain if you are using GSuite. - You can use Firebase Functions onCreate event to delete a user quickly every time one is created with an invalid email domain.
- If you are using database rules, you can block access if the email doesn't match:
".read": "auth != null && auth.uid == $uid" && auth.token.email.matches(/.*@mydomain.com$/)
- If you are using your own backend, when getting the ID token of a user, validate it, then get the email and make sure it matches your domain, if not, you can delete the user. The Firebase Admin SDKs provide the ability to verify an ID token and delete a user by UID.
来源:https://stackoverflow.com/questions/45494915/can-you-only-allow-users-with-a-specific-email-address-to-sign-up-and-use-your-a