能否使用正则表达式在Cloud Firestore中识别用户?
Great question! You're right that document.matches() is designed to validate document paths, but validating a request-level field like request.auth.token.email just requires using the built-in matches() method for string values in Firebase Security Rules. Here's how to fix your functions and implement this correctly:
Step 1: Update the isCorrectEmail Function
Instead of trying to use the document path matching syntax, call matches() directly on the email string. Note that in Security Rules, regex patterns are passed as strings (no surrounding / delimiters), and special regex characters like . need to be escaped with a double backslash (\\.) since backslashes are escape characters in rule strings.
Here's the revised function:
function isCorrectEmail(email) { // Check for exact matches OR a regex match for @domain.com emails return email != null && ( email == 'my_email@gmail.com' || email == 'anotherEmail@gmail.com' || email.matches('^.+@domain\\.com$') ); }
- Added
email != nullto avoid errors if the user doesn't have an email linked to their auth account. - The regex
^.+@domain\\.com$ensures the entire email ends with@domain.com(the^and$anchors prevent partial matches likeuser@domain.com.evil.com).
Step 2: Integrate with Your isDeveloper Function
Your existing isDeveloper function works fine once isCorrectEmail is updated. Here's the full context of how this fits into a complete rules file:
rules_version = '2'; service cloud.firestore { match /databases/{database}/documents { // Verify user is authenticated and UID matches function isUserAuthenticated(userId) { return request.auth != null && request.auth.uid == userId; } // Validate email against exact matches or regex function isCorrectEmail(email) { return email != null && ( email == 'my_email@gmail.com' || email == 'anotherEmail@gmail.com' || email.matches('^.+@domain\\.com$') ); } // Check if user is an authorized developer function isDeveloper(userId) { return isUserAuthenticated(userId) && isCorrectEmail(request.auth.token.email); } // Example: Restrict write access to developers only match /{document=**} { allow write: if isDeveloper(request.auth.uid); } } }
Key Notes
- String
matches()vs Documentmatches(): The stringmatches()method works on any string value in your rules (likerequest.auth.token.email,resource.data.email, etc.), whiledocument.matches()is exclusively for validating document paths. - Test with the Rules Simulator: Always test your regex patterns using Firebase's built-in Rules Simulator to ensure they behave as expected for valid and invalid email addresses.
- Regex Syntax: Security Rules regex uses RE2 syntax, so make sure your pattern is compatible with that standard (most common regex patterns work without issues).
内容的提问来源于stack exchange,提问作者Brandon

