Data Permission Management
CloudBase provides a multi-level data permission management mechanism, ensuring data security while meeting the permission control requirements of different business scenarios.
🎯 Permission Management Framework
CloudBase data permission management includes three levels:
Permission Type | Control Granularity | Applicable Scenarios | Configuration Complexity |
---|---|---|---|
Basic Permission Control | Model Level | Simple Permission Requirements | Low |
Role Permissions | User Level | Organizational Structure Permissions | Medium |
Security Rule Permissions | Document Level | Complex Business Logic | High |
Permission Priority
Relationships between different permission types:
- Role Permissions and Basic Permissions are combined as a union to form the final permissions.
- Security Rule Permissions have the highest priority and override other permission settings.
- Choose the appropriate permission management method based on business complexity.
🔧 Basic Access Control
Features
Basic Permission Control is the simplest permission management method, suitable for most common business scenarios:
- Model-level Control: Apply uniform permissions to the entire data model.
- Predefined Permission Templates: Provide common permission configuration templates.
- Simple and Easy to Use: No need to write complex rule expressions.
Configuration Method
On the Data Model page in the CloudBase console, set corresponding permissions for each model:
Permission Options
Based on the user's identity, select the corresponding permissions.
- All users include anonymous users, external users, and internal users.
- The actual permissions for an anonymous user are the maximum set of permissions from both "all users" and "anonymous users"; the same principle applies to external users and internal users.
- Best Practice 1: Manage permissions exclusively through "all users"; set permissions for anonymous users, external users, and internal users to no access.
- Best Practice 2: Delete the "all users" rules and manage permissions through granular roles.
Permission Type | Applicable Scenarios |
---|---|
Read all data and modify own data | Public content, such as articles and products |
Read and modify own data | Private data, such as user profiles |
Read all data but cannot modify data | Configuration data, such as system settings |
No access | Sensitive data, such as financial information |
👥 Custom Role Permission Control
Feature Overview
Role-based permissions are a permission management approach based on organizational structure, suitable for hierarchical permission control in enterprise-level applications. It complements Basic Permission Control, with the final permissions being the union of both.
Core Features:
- Support for Organizational Structure: Permission control based on departments and reporting relationships.
- Role Inheritance: Supports hierarchical inheritance of permissions.
- Flexible Combination: Combined with Basic Permissions as a union to provide more flexible permission configuration.
Configuration Steps
Step 1: Access Role Management
Access the Custom Roles Page to manage organizational structure and role definitions:
Step 2: Configure Row-level Permissions
Select the target role and click "Row Permission Settings" for detailed configuration:
Permission Level Description
Permission Level | Data Scope | Applicable Scenarios | Example |
---|---|---|---|
View own | Data where the Owner field is set to self | Personal data management | Employees can only view their own attendance records |
View Self and Subordinates | Data of self and subordinates | Team management | Supervisors can view work reports of team members |
View Own Department and Sub-departments | Data of own department and sub-departments | Department management | Department managers view all projects within the department |
View All | All data | System management | Administrators can view company-wide data |
Permission Combination Rules
Relationship Between Read and Write Permissions
⚠️ Important: Row modification permission automatically includes read permission, meaning that having modification permission implies having read permission.
Permissions Union Calculation
Basic Permissions + Role Permissions = Final Permissions
Example Scenario:
Basic Permissions: Readable and writable only by the creator and administrators
Role Permissions: View All + No Modification Permission
─────────────────────────────────
Final Permissions: Can view all data, but can only modify the data they created
Practical Application Cases
Case 1: Blog Permissions
Business Requirements:
- Can view everyone's blogs
- Can update their own blogs
Basic Permission Configuration
All users/Read all data, Modify own data
Case 2: Project Management System
Business Requirements:
- Project members can only view projects they participate in.
- Project managers can manage the projects under their responsibility.
- Department managers can view all projects within the department.
Basic Permission Configuration
All users/Read and modify own data
Role Permissions Configuration
Role | Role Data Permissions | Row Modification Permissions | Final Effect |
---|---|---|---|
Salesperson | View own | Self | Can only view and modify their own customers |
Sales Supervisor | View Self and Subordinates | Self and subordinates | Can manage all customers of the team |
Sales Director | View All | View All | Can manage all customers |
Permission Design Best Practices
1. Permissions Design Principles
- Principle of Least Privilege: Grant only the minimum permissions required to complete the work
- Separation of Duties: Different roles assume distinct data responsibilities
- Permission Inheritance: Effectively leverage the hierarchical relationships of the organizational structure
2. Common Configuration Patterns
Read-only Extension Pattern:
Basic Permissions: Readable and writable only by the creator
Role Permissions: Expand viewable scope without granting modification permission
Effect: Expand data visibility while maintaining modification control
Administrator Mode:
Basic Permissions: Readable and writable only by the creator
Role Permissions: View All + Modify All
Effect: Administrators can manage all data
Department Isolation Pattern:
Basic Permissions: Readable and writable only by the creator
Role Permissions: View Own Department + Modify Own Department
Effect: Data isolation between departments and sharing within each department.
3. Notes
- Permission Testing: Thoroughly test permissions for various roles before production deployment
- Permission Auditing: Regularly inspect and adjust permission configurations
- Documentation: Thoroughly document the business logic of permission design
- Change Management: Permission changes must go through an approval process
🛡️ Security Rule Permissions
Feature Overview
Security rule permissions provide more flexible, scalable, and granular access control capabilities, supporting dynamic permission determination based on document content.
Core Features:
- Document-level control: Access permissions can be determined based on the specific content of the document.
- Expression-driven: Define permission logic using expressions similar to those in programming languages.
- Dynamic permissions: Supports dynamic permission determination based on user identity, time, and data content.
- Client-side only restriction: Restricts client-side user access without affecting server-side (Cloud Function) operations.
Configuration Entry
Switch to the Collection Management page and configure more granular security rules via Security Rule Permissions:
Rule Configuration Format
Security rules are configured in JSON format, with the basic structure as follows:
{
"read": "expression",
"write": "expression",
"create": "expression",
"update": "expression",
"delete": "expression"
}
Operation Types Description
Operation Type | Description | Default Value | Example Scenario |
---|---|---|---|
read | Read document | false | Query, retrieve documents |
write | Write document (General) | false | Default rule when no specific write operation is specified |
create | Create document | Inherits write | Add new data |
update | Update document | Inherits write | Modify existing data |
delete | Delete document | Inherits write | Delete data |
💡 Rule Inheritance: If no specific write operation rules (create/update/delete) are specified, the
write
rule will be automatically applied.
Expression Syntax
Global Variables
Variable Name | Type | Description | Example |
---|---|---|---|
auth | Object | User login information | auth.openid , auth.uid |
doc | Object | Document data or query conditions | doc.userId , doc.status |
request | Object | Request information | request.data |
now | Number | Current timestamp | now > doc.expireTime |
User Identity Information (auth)
Field | Type | Description | Applicable Scenarios |
---|---|---|---|
openid | String | WeChat user OpenID | WeChat Mini Program login |
uid | String | User unique ID | Web login |
loginType | String | Login method | To distinguish between different login channels |
Operator Support
Operator | Description | Example | Use Cases |
---|---|---|---|
== | Equal to | auth.uid == doc.userId | To verify data owner |
!= | Not equal to | doc.status != 'deleted' | To exclude specific status |
>, >=, <, <= | Comparison operations | doc.age >= 18 | Numeric range judgment |
in | In | auth.uid in doc.editors | To check if a user is in a list |
&& | Logical AND | auth.uid == doc.userId && doc.published | Combining multiple conditions |
|| | Logical OR | auth.uid == doc.userId \|\| doc.public | Multiple access methods |
Practical Application Example
1. Basic Permission Mapping
Readable by all users, writable only by the creator:
{
"read": true,
"write": "doc._openid == auth.openid"
}
Readable and writable only by the creator:
{
"read": "doc._openid == auth.openid",
"write": "doc._openid == auth.openid"
}
2. Complex Business Logic
Article Publishing System:
{
"read": "doc.published == true || doc.author == auth.uid",
"create": true,
"update": "doc.author == auth.uid",
"delete": "doc.author == auth.uid && doc.published == false"
}
Collaborative Document System:
{
"read": "auth.uid in doc.readers || auth.uid in doc.editors || doc.owner == auth.uid",
"write": "auth.uid in doc.editors || doc.owner == auth.uid"
}
3. Time Control
Limited-Time Event Data:
{
"read": "now >= doc.startTime && now <= doc.endTime",
"write": "doc.owner == auth.uid && now <= doc.endTime"
}
get Function: Cross-Document Permission Verification
Feature Description
The
get()` function allows accessing data from other documents during permission verification, enabling complex cross-document permission control.
Syntax: `get('database.collection.documentID')
Usage Example
Role-Based Access Control:
{
"read": "get('database.user_roles.' + auth.uid).role in ['admin', 'editor']",
"write": "get('database.user_roles.' + auth.uid).role == 'admin'"
}
Associated Data Permissions:
{
"read": "auth.uid == get('database.projects.' + doc.projectId).owner"
}
Usage Limitations
- A single expression can contain up to 3
get
functions. - Up to 10 different documents can be accessed.
- Maximum nesting depth: 2 levels
- Additional database read operations will be generated (which will be billed).
Query Limitations and Optimization
Query Condition Requirements
Security rules require that query conditions must be a subset of the rules:
// Security Rules
{
"read": "doc.age > 10"
}
// ✅ Complies with rules (query conditions are a subset of the rules)
db.collection('users').where({
age: _.gt(15)
}).get()
// ❌ Does not comply with rules (query conditions exceed the scope of the rules)
db.collection('users').where({
age: _.gt(5)
}).get()
Document ID Query Refactoring
The traditional doc().get()
query needs to be rewritten as a where()
query:
// ❌ Traditional method (does not comply with security rules)
db.collection('posts').doc('postId').get()
// ✅ After refactoring (complies with security rules)
db.collection('posts').where({
_id: 'postId',
_openid: '{openid}' // Using template variables
}).get()
Best Practices
1. Rules Design Principles
- Principle of Least Privilege: Grant only necessary permissions
- Principle of Clarity: Rule expressions should be clear and easy to understand
- Performance Considerations: Avoid excessive
get()
function calls
2. Common Patterns
Data Owner Pattern:
{
"read": "doc._openid == auth.openid",
"write": "doc._openid == auth.openid"
}
Public Read, Restricted Write:
{
"read": true,
"write": "doc.author == auth.uid"
}
State-Based Permission:
{
"read": "doc.status == 'published' || doc.author == auth.uid",
"update": "doc.author == auth.uid && doc.status != 'locked'"
}
3. Debugging Tips
- Start with simple rules and gradually increase complexity
- Thoroughly test various scenarios in the development environment
- Check the permission error messages in the console
- Properly use logging to record permission verification processes
🎯 Permission Selection Guide
Select based on business complexity
Business Scenario | Recommended Solution | Reason |
---|---|---|
Simple Application | Basic Permission Control | Simple configuration that meets basic requirements |
Complex Business Logic | Security Rule Permissions | Flexible expressions that support complex judgments |
Enterprise-level Application | Role Permissions + Basic Permissions | Supports organizational structure with clear permission hierarchy |
High Security Requirements | Security Rules + Role Permissions | Multi-layered protection with fine-grained control |
Permission Configuration Recommendations
- Start simple: Begin with basic permissions and gradually upgrade as needed
- Layered Design: Basic permissions handle common logic, while security rules handle specific logic
- Test Verification: Thoroughly test various permission scenarios in the development environment
- Documentation: Thoroughly document the permission design rationale and configuration instructions
Through reasonable permission configuration, you can build a secure yet flexible data access control system that meets various complex business requirements.