Skip to main content

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 TypeControl GranularityApplicable ScenariosConfiguration Complexity
Basic Permission ControlCollection LevelSimple Permission RequirementsLow
Security Rule PermissionsDocument LevelComplex Business LogicHigh

🔧 Basic Access Control

Configuration Method

On the Collection Management page in the CloudBase console, set corresponding permissions for each collection:

Permission Options

Based on the user's identity, select the corresponding permissions.

Permission TypeApplicable Scenarios
Read all data and modify own dataPublic content, such as articles and products
Read and modify own dataPrivate data, such as user profiles
Read all data but cannot modify dataConfiguration data, such as system settings
No accessSensitive data, such as financial information

🛡️ 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:

Security Rules Configuration

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 TypeDescriptionDefault ValueExample Scenario
readRead documentfalseQuery, retrieve documents
writeWrite document (General)falseDefault rule when no specific write operation is specified
createCreate documentInherits writeAdd new data
updateUpdate documentInherits writeModify existing data
deleteDelete documentInherits writeDelete 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 NameTypeDescriptionExample
authObjectUser login informationauth.openid, auth.uid
docObjectDocument data or query conditionsdoc.userId, doc.status
requestObjectRequest informationrequest.data
nowNumberCurrent timestampnow > doc.expireTime

User Identity Information (auth)

FieldTypeDescriptionApplicable Scenarios
openidStringWeChat user OpenIDWeChat Mini Program login
uidStringUser unique IDWeb login
loginTypeStringLogin methodTo distinguish between different login channels

Operator Support

OperatorDescriptionExampleUse Cases
==Equal toauth.uid == doc.userIdTo verify data owner
!=Not equal todoc.status != 'deleted'To exclude specific status
>, >=, <, <=Comparison operationsdoc.age >= 18Numeric range judgment
inInauth.uid in doc.editorsTo check if a user is in a list
&&Logical ANDauth.uid == doc.userId && doc.publishedCombining multiple conditions
||Logical ORauth.uid == doc.userId \|\| doc.publicMultiple 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 ScenarioRecommended SolutionReason
Simple ApplicationBasic Permission ControlSimple configuration that meets basic requirements
Complex Business LogicSecurity Rule PermissionsFlexible expressions that support complex judgments
Enterprise-level ApplicationRole Permissions + Basic PermissionsSupports organizational structure with clear permission hierarchy
High Security RequirementsSecurity Rules + Role PermissionsMulti-layered protection with fine-grained control

Permission Configuration Recommendations

  1. Start simple: Begin with basic permissions and gradually upgrade as needed
  2. Layered Design: Basic permissions handle common logic, while security rules handle specific logic
  3. Test Verification: Thoroughly test various permission scenarios in the development environment
  4. 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.