Spaces:
Running
Running
| # Access Roles CRUD Module | |
| Complete CRUD implementation for access roles management in the SCM microservice. | |
| ## Overview | |
| The Access Roles module provides comprehensive role-based access control (RBAC) functionality with full CRUD operations, projection support, and base role management. | |
| ## Features | |
| - β **Complete CRUD Operations**: Create, Read, Update, Delete access roles | |
| - β **Projection List Support**: Optimized queries with field selection | |
| - β **Base Role Protection**: Prevents deletion of system base roles | |
| - β **MongoDB Integration**: Async MongoDB operations with proper error handling | |
| - β **JWT Authentication**: Secured endpoints with user authentication | |
| - β **Comprehensive Validation**: Pydantic models with proper validation | |
| - β **Logging & Error Handling**: Detailed logging and proper error responses | |
| ## API Endpoints | |
| ### Base URL: `/access-roles` | |
| | Method | Endpoint | Description | | |
| |--------|----------|-------------| | |
| | `POST` | `/create` | Create new access role | | |
| | `POST` | `/get` | Get access role by ID | | |
| | `POST` | `/list` | List access roles with filtering | | |
| | `POST` | `/update?role_id={id}` | Update access role | | |
| | `POST` | `/delete` | Delete access role | | |
| | `GET` | `/base-roles` | Get all base system roles | | |
| ## Data Model | |
| ### AccessRole | |
| ```python | |
| { | |
| "role_id": "role_store_manager", | |
| "role_name": "Store Manager", | |
| "description": "Store level management access", | |
| "permissions": { | |
| "inventory": ["view", "create", "update"], | |
| "orders": ["view", "create", "update"], | |
| "suppliers": ["view"], | |
| "catalogues": ["view"], | |
| "reports": ["view"], | |
| "settings": ["view"], | |
| "goods_receipts": ["view", "create", "update"], | |
| "merchant_setting": ["view"], | |
| "merchant": ["view"], | |
| "stock": ["view", "create", "update"], | |
| "access_control": ["view"], | |
| "employees": ["view", "create", "update"] | |
| }, | |
| "is_base_role": false, | |
| "is_active": true, | |
| "created_by": "admin_user", | |
| "created_at": "2025-12-13T10:00:00Z", | |
| "updated_by": "admin_user", | |
| "updated_at": "2025-12-13T11:00:00Z" | |
| } | |
| ``` | |
| ### Permission Modules | |
| - `inventory`: Inventory management | |
| - `orders`: Order management | |
| - `suppliers`: Supplier management | |
| - `catalogues`: Catalogue management | |
| - `reports`: Reporting and analytics | |
| - `settings`: System settings | |
| - `goods_receipts`: Goods receipt notes | |
| - `merchant_setting`: Merchant settings | |
| - `merchant`: Merchant management | |
| - `stock`: Stock management | |
| - `access_control`: Access control management | |
| - `employees`: Employee management | |
| - `system`: System administration | |
| - `system_users`: System user management | |
| ### Permission Actions | |
| - `view`: Read access | |
| - `create`: Create new records | |
| - `update`: Modify existing records | |
| - `delete`: Delete records | |
| - `export`: Export data | |
| - `schedule`: Schedule operations | |
| - `manage`: Full management access | |
| - `audit`: Audit access | |
| - `backup`: Backup operations | |
| ## Base Roles | |
| The system includes three predefined base roles: | |
| ### 1. Super Administrator (`role_super_admin`) | |
| - **Description**: Full system access with all permissions | |
| - **Permissions**: All modules with all actions | |
| - **Protected**: Cannot be deleted | |
| ### 2. Company Administrator (`role_company_admin`) | |
| - **Description**: Company-wide administrative access | |
| - **Permissions**: Most modules with create/update access (no delete/system) | |
| - **Protected**: Cannot be deleted | |
| ### 3. cnf Manager (`role_cnf_manager`) | |
| - **Description**: cnf operations management | |
| - **Permissions**: Limited operational access | |
| - **Protected**: Cannot be deleted | |
| ## Usage Examples | |
| ### 1. Create Access Role | |
| ```bash | |
| curl -X POST "http://localhost:8000/access-roles/create" \ | |
| -H "Content-Type: application/json" \ | |
| -H "Authorization: Bearer YOUR_JWT_TOKEN" \ | |
| -d '{ | |
| "role_id": "role_store_manager", | |
| "role_name": "Store Manager", | |
| "description": "Store level management access", | |
| "permissions": { | |
| "inventory": ["view", "create", "update"], | |
| "orders": ["view", "create", "update"] | |
| }, | |
| "is_active": true | |
| }' | |
| ``` | |
| ### 2. List Roles with Projection | |
| ```bash | |
| curl -X POST "http://localhost:8000/access-roles/list" \ | |
| -H "Content-Type: application/json" \ | |
| -H "Authorization: Bearer YOUR_JWT_TOKEN" \ | |
| -d '{ | |
| "filters": {"is_active": true}, | |
| "skip": 0, | |
| "limit": 10, | |
| "projection_list": ["role_id", "role_name", "is_active"] | |
| }' | |
| ``` | |
| ### 3. Update Role | |
| ```bash | |
| curl -X POST "http://localhost:8000/access-roles/update?role_id=role_store_manager" \ | |
| -H "Content-Type: application/json" \ | |
| -H "Authorization: Bearer YOUR_JWT_TOKEN" \ | |
| -d '{ | |
| "role_name": "Updated Store Manager", | |
| "permissions": { | |
| "inventory": ["view", "create", "update", "delete"] | |
| } | |
| }' | |
| ``` | |
| ## Setup Instructions | |
| ### 1. Initialize Base Roles | |
| ```bash | |
| cd cuatrolabs-scm-ms | |
| python initialize_access_roles.py | |
| ``` | |
| ### 2. Test CRUD Operations | |
| ```bash | |
| cd cuatrolabs-scm-ms | |
| python test_access_roles_crud.py | |
| ``` | |
| ### 3. Test API Endpoints | |
| ```bash | |
| cd cuatrolabs-scm-ms | |
| # Update AUTH_TOKEN in the script first | |
| ./test_access_roles_api.sh | |
| ``` | |
| ## File Structure | |
| ``` | |
| cuatrolabs-scm-ms/app/access_roles/ | |
| βββ __init__.py | |
| βββ controllers/ | |
| β βββ __init__.py | |
| β βββ router.py # FastAPI router with all endpoints | |
| βββ models/ | |
| β βββ __init__.py | |
| β βββ model.py # Pydantic models | |
| βββ schemas/ | |
| β βββ __init__.py | |
| β βββ schema.py # Request/response schemas | |
| βββ services/ | |
| βββ __init__.py | |
| βββ service.py # Business logic and database operations | |
| ``` | |
| ## Key Features Implementation | |
| ### 1. Projection List Support | |
| Following the API standards, all list/get endpoints support projection lists for optimized queries: | |
| ```python | |
| # Service layer implementation | |
| projection_dict = None | |
| if projection_list: | |
| projection_dict = {field: 1 for field in projection_list} | |
| projection_dict["_id"] = 0 | |
| cursor = collection.find(query, projection_dict) | |
| docs = await cursor.to_list(length=limit) | |
| # Return raw dict if projection, model otherwise | |
| return docs if projection_list else [Model(**d) for d in docs] | |
| ``` | |
| ### 2. Base Role Protection | |
| Base roles are protected from deletion: | |
| ```python | |
| async def delete_access_role(self, role_id: str) -> bool: | |
| # Check if it's a base role | |
| role = await self.collection.find_one({"role_id": role_id}) | |
| if role and role.get("is_base_role", False): | |
| raise ValueError("Cannot delete base system roles") | |
| ``` | |
| ### 3. Comprehensive Error Handling | |
| All operations include proper error handling with detailed logging: | |
| ```python | |
| try: | |
| # Operation logic | |
| pass | |
| except DuplicateKeyError: | |
| logger.error(f"Role {role_id} already exists") | |
| raise HTTPException(status_code=409, detail="Role already exists") | |
| except Exception as e: | |
| logger.error(f"Error: {str(e)}") | |
| raise HTTPException(status_code=500, detail="Internal server error") | |
| ``` | |
| ## Database Collection | |
| **Collection Name**: `scm_access_roles` | |
| The collection stores access role documents with the following indexes: | |
| - `role_id`: Unique index for role identification | |
| - `is_active`: Index for filtering active roles | |
| - `is_base_role`: Index for base role queries | |
| ## Integration | |
| The access roles module is fully integrated into the SCM microservice: | |
| 1. **Router Registration**: Added to `app/main.py` | |
| 2. **Collection Constant**: Defined in `app/constants/collections.py` | |
| 3. **Authentication**: Uses existing JWT authentication from `app/dependencies/auth.py` | |
| 4. **Database**: Uses existing MongoDB connection from `app/nosql.py` | |
| ## Testing | |
| ### Unit Tests | |
| - Service layer CRUD operations | |
| - Model validation | |
| - Error handling scenarios | |
| ### Integration Tests | |
| - API endpoint testing | |
| - Authentication flow | |
| - Database operations | |
| ### Performance Tests | |
| - Projection list optimization | |
| - Large dataset handling | |
| - Concurrent operations | |
| ## Security Considerations | |
| 1. **JWT Authentication**: All endpoints require valid JWT tokens | |
| 2. **Base Role Protection**: System roles cannot be deleted | |
| 3. **Input Validation**: Comprehensive Pydantic validation | |
| 4. **Permission Validation**: Role permissions are validated against allowed modules/actions | |
| 5. **Audit Trail**: All operations include created_by/updated_by tracking | |
| ## Performance Optimizations | |
| 1. **MongoDB Projection**: Reduces data transfer and processing | |
| 2. **Indexed Queries**: Efficient database queries with proper indexes | |
| 3. **Async Operations**: Non-blocking database operations | |
| 4. **Connection Pooling**: Efficient database connection management | |
| ## Monitoring & Logging | |
| - Comprehensive logging for all operations | |
| - Error tracking with detailed context | |
| - Performance metrics for database operations | |
| - Audit trail for role modifications | |
| This implementation provides a robust, scalable, and secure access roles management system following all established API standards and best practices. |