abs-auth-rbac-core 0.1.15__tar.gz → 0.3.13__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. abs_auth_rbac_core-0.3.13/PKG-INFO +727 -0
  2. abs_auth_rbac_core-0.3.13/README.md +699 -0
  3. abs_auth_rbac_core-0.3.13/abs_auth_rbac_core/auth/__init__.py +15 -0
  4. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/auth/auth_functions.py +4 -1
  5. abs_auth_rbac_core-0.3.13/abs_auth_rbac_core/auth/middleware.py +245 -0
  6. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/gov_casbin_rule.py +9 -0
  7. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/user.py +1 -0
  8. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/rbac/service.py +239 -120
  9. abs_auth_rbac_core-0.3.13/abs_auth_rbac_core/repository/__init__.py +4 -0
  10. abs_auth_rbac_core-0.3.13/abs_auth_rbac_core/repository/permission_repository.py +12 -0
  11. abs_auth_rbac_core-0.3.13/abs_auth_rbac_core/repository/role_repository.py +18 -0
  12. abs_auth_rbac_core-0.3.13/abs_auth_rbac_core/service/__init__.py +4 -0
  13. abs_auth_rbac_core-0.3.13/abs_auth_rbac_core/service/permission_service.py +15 -0
  14. abs_auth_rbac_core-0.3.13/abs_auth_rbac_core/service/role_service.py +18 -0
  15. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/util/permission_constants.py +330 -17
  16. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/pyproject.toml +7 -4
  17. abs_auth_rbac_core-0.1.15/PKG-INFO +0 -234
  18. abs_auth_rbac_core-0.1.15/README.md +0 -211
  19. abs_auth_rbac_core-0.1.15/abs_auth_rbac_core/auth/__init__.py +0 -3
  20. abs_auth_rbac_core-0.1.15/abs_auth_rbac_core/auth/middleware.py +0 -51
  21. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/__init__.py +0 -0
  22. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/auth/jwt_functions.py +0 -0
  23. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/__init__.py +0 -0
  24. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/base_model.py +0 -0
  25. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/permissions.py +0 -0
  26. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/rbac_model.py +0 -0
  27. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/role_permission.py +0 -0
  28. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/roles.py +0 -0
  29. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/seeder/permission_seeder.py +0 -0
  30. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/user_permission.py +0 -0
  31. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/models/user_role.py +0 -0
  32. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/rbac/__init__.py +0 -0
  33. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/rbac/decorator.py +0 -0
  34. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/rbac/policy.conf +0 -0
  35. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/schema/__init__.py +0 -0
  36. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/schema/permission.py +0 -0
  37. {abs_auth_rbac_core-0.1.15 → abs_auth_rbac_core-0.3.13}/abs_auth_rbac_core/util/__init__.py +0 -0
@@ -0,0 +1,727 @@
1
+ Metadata-Version: 2.3
2
+ Name: abs-auth-rbac-core
3
+ Version: 0.3.13
4
+ Summary: RBAC and Auth core utilities including JWT token management.
5
+ License: MIT
6
+ Author: AutoBridgeSystems
7
+ Author-email: info@autobridgesystems.com
8
+ Requires-Python: >=3.11,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Requires-Dist: abs-exception-core (>=0.2.0,<0.3.0)
15
+ Requires-Dist: abs-nosql-repository-core (>=0.11.8,<0.12.0)
16
+ Requires-Dist: abs-repository-core (>=0.3.0,<0.4.0)
17
+ Requires-Dist: abs-utils (>=0.4.1,<0.5.0)
18
+ Requires-Dist: casbin (>=1.41.0,<2.0.0)
19
+ Requires-Dist: casbin-redis-watcher (>=1.3.0,<2.0.0)
20
+ Requires-Dist: casbin-sqlalchemy-adapter (>=1.4.0,<2.0.0)
21
+ Requires-Dist: fastapi[standard] (>=0.115.12,<0.116.0)
22
+ Requires-Dist: passlib (>=1.7.4,<2.0.0)
23
+ Requires-Dist: psycopg2-binary (>=2.9.10,<3.0.0)
24
+ Requires-Dist: pyjwt (>=2.10.1,<3.0.0)
25
+ Requires-Dist: sqlalchemy (>=2.0.40,<3.0.0)
26
+ Description-Content-Type: text/markdown
27
+
28
+ # ABS Auth RBAC Core
29
+
30
+ A comprehensive authentication and Role-Based Access Control (RBAC) package for FastAPI applications. This package provides robust JWT-based authentication and flexible role-based permission management using Casbin with Redis support for real-time policy updates.
31
+
32
+ ## 🚀 Features
33
+
34
+ - **🔐 JWT-based Authentication**: Secure token-based authentication with customizable expiration
35
+ - **🔒 Password Security**: Secure password storage using bcrypt with passlib
36
+ - **👥 Role-Based Access Control (RBAC)**: Flexible permission management using Casbin
37
+ - **⚡ Real-time Policy Updates**: Redis integration for live policy synchronization
38
+ - **🔄 User-Role Management**: Dynamic role assignment and revocation
39
+ - **🛡️ Permission Enforcement**: Decorator-based permission checking
40
+ - **🔌 Middleware Integration**: Seamless FastAPI middleware integration
41
+ - **📝 Comprehensive Error Handling**: Built-in exception handling for security scenarios
42
+ - **🏗️ Dependency Injection Ready**: Compatible with dependency-injector
43
+ - **📊 Permission Constants**: Predefined permission constants and enums
44
+
45
+ ## 📦 Installation
46
+
47
+ ```bash
48
+ pip install abs-auth-rbac-core
49
+ ```
50
+
51
+ ## 🏗️ Architecture Overview
52
+
53
+ ```
54
+ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
55
+ │ FastAPI App │ │ Auth Middleware│ │ RBAC Service │
56
+ │ │ │ │ │ │
57
+ │ ┌─────────────┐ │ │ ┌─────────────┐ │ │ ┌─────────────┐ │
58
+ │ │ Routes │ │◄──►│ │JWT Validation│ │◄──►│ │Permission │ │
59
+ │ │ │ │ │ │User Fetch │ │ │ │Checking │ │
60
+ │ └─────────────┘ │ │ └─────────────┘ │ │ └─────────────┘ │
61
+ └─────────────────┘ └─────────────────┘ └─────────────────┘
62
+ │ │ │
63
+ │ │ │
64
+ ▼ ▼ ▼
65
+ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
66
+ │ Database │ │ Redis │ │ Casbin │
67
+ │ (Users, │ │ (Policy │ │ (Policy │
68
+ │ Roles, │ │ Updates) │ │ Engine) │
69
+ │ Permissions) │ │ │ │ │
70
+ └─────────────────┘ └─────────────────┘ └─────────────────┘
71
+ ```
72
+
73
+ ## 🚀 Quick Start
74
+
75
+ ### 1. Basic Setup
76
+
77
+ ```python
78
+ from abs_auth_rbac_core.auth.jwt_functions import JWTFunctions
79
+ from abs_auth_rbac_core.rbac import RBACService
80
+ from abs_auth_rbac_core.schema.permission import RedisWatcherSchema
81
+ import os
82
+
83
+ # Initialize JWT functions
84
+ jwt_functions = JWTFunctions(
85
+ secret_key=os.getenv("JWT_SECRET_KEY"),
86
+ algorithm=os.getenv("JWT_ALGORITHM", "HS256"),
87
+ expire_minutes=int(os.getenv("JWT_EXPIRE_MINUTES", "60"))
88
+ )
89
+
90
+ # Initialize RBAC service with database session
91
+ rbac_service = RBACService(
92
+ session=your_db_session,
93
+ redis_config=RedisWatcherSchema(
94
+ host=os.getenv("REDIS_HOST"),
95
+ port=int(os.getenv("REDIS_PORT", "6379")),
96
+ channel=os.getenv("REDIS_CHANNEL", "casbin_policy_updates"),
97
+ password=os.getenv("REDIS_PASSWORD"),
98
+ ssl=os.getenv("REDIS_SSL", "false").lower() == "true"
99
+ )
100
+ )
101
+ ```
102
+
103
+ ### 2. Authentication Setup
104
+
105
+ #### Option 1: Using Package Middleware (Recommended)
106
+
107
+ ```python
108
+ from abs_auth_rbac_core.auth.middleware import auth_middleware
109
+ from fastapi import FastAPI, Depends
110
+
111
+ app = FastAPI()
112
+
113
+ # Create authentication middleware
114
+ auth_middleware = auth_middleware(
115
+ db_session=your_db_session,
116
+ jwt_secret_key=os.getenv("JWT_SECRET_KEY"),
117
+ jwt_algorithm=os.getenv("JWT_ALGORITHM", "HS256")
118
+ )
119
+
120
+ # Apply to specific routers
121
+ app.include_router(
122
+ protected_router,
123
+ dependencies=[Depends(auth_middleware)]
124
+ )
125
+
126
+ # Public routes (no middleware)
127
+ app.include_router(public_router)
128
+ ```
129
+
130
+ **How it works:**
131
+ 1. ✅ Validates JWT token from Authorization header
132
+ 2. ✅ Extracts user UUID from token payload
133
+ 3. ✅ Fetches user from database using UUID
134
+ 4. ✅ Sets user object in `request.state.user`
135
+ 5. ✅ Returns user object for route handlers
136
+
137
+ **Accessing the user in routes:**
138
+ ```python
139
+ @router.get("/profile")
140
+ async def get_profile(request: Request):
141
+ user = request.state.user
142
+ return {"user_id": user.uuid, "email": user.email}
143
+ ```
144
+
145
+ #### Option 2: Custom Authentication Function
146
+
147
+ ```python
148
+ from abs_auth_rbac_core.auth.jwt_functions import JWTFunctions
149
+ from fastapi import Security, HTTPAuthorizationCredentials
150
+ from fastapi.security import HTTPBearer
151
+ from abs_exception_core.exceptions import UnauthorizedError
152
+
153
+ security = HTTPBearer(auto_error=False)
154
+ jwt_functions = JWTFunctions(
155
+ secret_key=os.getenv("JWT_SECRET_KEY"),
156
+ algorithm=os.getenv("JWT_ALGORITHM", "HS256"),
157
+ expire_minutes=int(os.getenv("JWT_EXPIRE_MINUTES", "60"))
158
+ )
159
+
160
+ async def get_current_user(
161
+ credentials: HTTPAuthorizationCredentials = Security(security),
162
+ ) -> Dict:
163
+ try:
164
+ if not credentials:
165
+ raise UnauthorizedError(detail="No authorization token provided")
166
+
167
+ token = credentials.credentials
168
+ if token.lower().startswith("bearer "):
169
+ token = token[7:]
170
+
171
+ decoded_token = jwt_functions.decode_jwt(token)
172
+ if not decoded_token:
173
+ raise UnauthorizedError(detail="Invalid or expired token")
174
+
175
+ return decoded_token
176
+ except Exception as e:
177
+ raise UnauthorizedError(detail=str(e))
178
+
179
+ @app.get("/protected")
180
+ async def protected_route(current_user: dict = Depends(get_current_user)):
181
+ return {"message": f"Hello {current_user.get('name')}"}
182
+ ```
183
+
184
+ ### 3. RBAC Operations
185
+
186
+ ```python
187
+ # Create a role with permissions
188
+ role = rbac_service.create_role(
189
+ name="admin",
190
+ description="Administrator role with full access",
191
+ permission_ids=["permission_uuid1", "permission_uuid2"]
192
+ )
193
+
194
+ # Assign roles to user
195
+ rbac_service.bulk_assign_roles_to_user(
196
+ user_uuid="user_uuid",
197
+ role_uuids=["role_uuid1", "role_uuid2"]
198
+ )
199
+
200
+ # Check user permissions
201
+ has_permission = rbac_service.check_permission(
202
+ user_uuid="user_uuid",
203
+ resource="USER_MANAGEMENT",
204
+ action="VIEW",
205
+ module="USER_MANAGEMENT"
206
+ )
207
+
208
+ # Get user permissions and roles
209
+ user_permissions = rbac_service.get_user_permissions(user_uuid="user_uuid")
210
+ user_roles = rbac_service.get_user_roles(user_uuid="user_uuid")
211
+ ```
212
+
213
+ ## 🏛️ Core Components
214
+
215
+ ### Authentication (`auth/`)
216
+ - **`jwt_functions.py`**: JWT token management and password hashing
217
+ - **`middleware.py`**: Authentication middleware for FastAPI
218
+ - **`auth_functions.py`**: Core authentication functions
219
+
220
+ ### RBAC (`rbac/`)
221
+ - **`service.py`**: Main RBAC service with role and permission management
222
+ - **`decorator.py`**: Decorators for permission checking
223
+ - **`policy.conf`**: Casbin policy configuration
224
+
225
+ ### Models (`models/`)
226
+ - **`user.py`**: User model
227
+ - **`roles.py`**: Role model
228
+ - **`permissions.py`**: Permission model
229
+ - **`user_role.py`**: User-Role association model
230
+ - **`role_permission.py`**: Role-Permission association model
231
+ - **`user_permission.py`**: User-Permission association model
232
+ - **`rbac_model.py`**: Base RBAC model
233
+ - **`base_model.py`**: Base model with common fields
234
+ - **`gov_casbin_rule.py`**: Casbin rule model
235
+
236
+ ### Schema (`schema/`)
237
+ - **`permission.py`**: Permission-related schemas
238
+
239
+ ### Utilities (`util/`)
240
+ - **`permission_constants.py`**: Predefined permission constants and enums
241
+
242
+ ## 🔧 Complete Implementation Example
243
+
244
+ ### 1. Dependency Injection Setup
245
+
246
+ ```python
247
+ from dependency_injector import containers, providers
248
+ from abs_auth_rbac_core.auth.middleware import auth_middleware
249
+ from abs_auth_rbac_core.rbac import RBACService
250
+ from abs_auth_rbac_core.schema.permission import RedisWatcherSchema
251
+ from abs_auth_rbac_core.util.permission_constants import (
252
+ PermissionAction,
253
+ PermissionModule,
254
+ PermissionResource
255
+ )
256
+
257
+ class Container(containers.DeclarativeContainer):
258
+ # Configure wiring for dependency injection
259
+ wiring_config = containers.WiringConfiguration(
260
+ modules=[
261
+ "src.api.auth_route",
262
+ "src.api.endpoints.rbac.permission_route",
263
+ "src.api.endpoints.rbac.role_route",
264
+ "src.api.endpoints.rbac.users_route",
265
+ ]
266
+ )
267
+
268
+ # Database session provider
269
+ db_session = providers.Factory(your_db_session_factory)
270
+
271
+ # RBAC service provider
272
+ rbac_service = providers.Singleton(
273
+ RBACService,
274
+ session=db_session,
275
+ redis_config=RedisWatcherSchema(
276
+ host=os.getenv("REDIS_HOST"),
277
+ port=int(os.getenv("REDIS_PORT", "6379")),
278
+ channel=os.getenv("REDIS_CHANNEL", "casbin_policy_updates"),
279
+ password=os.getenv("REDIS_PASSWORD"),
280
+ ssl=os.getenv("REDIS_SSL", "false").lower() == "true"
281
+ )
282
+ )
283
+
284
+ # Auth middleware provider
285
+ get_auth_middleware = providers.Factory(
286
+ auth_middleware,
287
+ db_session=db_session,
288
+ jwt_secret_key=os.getenv("JWT_SECRET_KEY"),
289
+ jwt_algorithm=os.getenv("JWT_ALGORITHM", "HS256")
290
+ )
291
+
292
+ # Initialize container
293
+ container = Container()
294
+ app.container = container
295
+ ```
296
+
297
+ ### 2. Application Setup
298
+
299
+ ```python
300
+ from fastapi import FastAPI, Depends
301
+ from fastapi.middleware.cors import CORSMiddleware
302
+ from dependency_injector.wiring import Provide, inject
303
+ from src.core.container import Container
304
+
305
+ class CreateApp:
306
+ def __init__(self):
307
+ self.container = Container()
308
+ self.db = self.container.db()
309
+ self.auth_middleware = self.container.get_auth_middleware()
310
+
311
+ self.app = FastAPI(
312
+ title="Your Service",
313
+ description="Service Description",
314
+ version="0.2.0"
315
+ )
316
+
317
+ # Apply CORS middleware
318
+ self.app.add_middleware(
319
+ CORSMiddleware,
320
+ allow_origins=[str(origin) for origin in configs.BACKEND_CORS_ORIGINS],
321
+ allow_credentials=True,
322
+ allow_methods=["*"],
323
+ allow_headers=["*"],
324
+ )
325
+
326
+ # Public routes (no authentication required)
327
+ self.app.include_router(auth_router, tags=["Auth"])
328
+ self.app.include_router(public_router_v1)
329
+
330
+ # Protected routes (authentication required)
331
+ self.app.include_router(
332
+ router_v1,
333
+ dependencies=[Depends(self.auth_middleware)]
334
+ )
335
+
336
+ # Register exception handlers
337
+ register_exception_handlers(self.app)
338
+
339
+ # Initialize application
340
+ application = CreateApp()
341
+ app = application.app
342
+ ```
343
+
344
+ ### 3. Route Implementation with Permissions
345
+
346
+ ```python
347
+ from fastapi import APIRouter, Depends, Request
348
+ from dependency_injector.wiring import Provide, inject
349
+ from abs_auth_rbac_core.rbac import rbac_require_permission
350
+ from abs_auth_rbac_core.util.permission_constants import (
351
+ PermissionAction,
352
+ PermissionModule,
353
+ PermissionResource
354
+ )
355
+
356
+ # Protected router (requires authentication)
357
+ router = APIRouter(prefix="/users")
358
+
359
+ # Public route example
360
+ @router.post("/all", response_model=FindUserResult)
361
+ @inject
362
+ async def get_user_list(
363
+ request: Request,
364
+ find_query: FindUser = Body(...),
365
+ rbac_service: RBACService = Depends(Provide[Container.rbac_service]),
366
+ service: UserService = Depends(Provide[Container.user_service]),
367
+ ):
368
+ """Get the list of users with filtering, sorting and pagination"""
369
+ find_query.searchable_fields = find_query.searchable_fields or ["name"]
370
+ users = service.get_list(schema=find_query)
371
+ return users
372
+
373
+ # Protected route with permission check
374
+ @router.get("/{user_id}", response_model=UserProfile)
375
+ @inject
376
+ @rbac_require_permission(
377
+ f"{PermissionModule.USER_MANAGEMENT.value}:{PermissionResource.USER_MANAGEMENT.value}:{PermissionAction.VIEW.value}"
378
+ )
379
+ async def get_user(
380
+ user_id: int,
381
+ request: Request,
382
+ service: UserService = Depends(Provide[Container.user_service]),
383
+ rbac_service: RBACService = Depends(Provide[Container.rbac_service]),
384
+ ):
385
+ """Get user profile with permissions and roles"""
386
+ return service.get_user_profile("id", user_id, rbac_service)
387
+ ```
388
+
389
+ ## 🔐 Permission System
390
+
391
+ ### Permission Format
392
+ Permissions follow the format: `module:resource:action`
393
+
394
+ - **Module**: The system module (e.g., `USER_MANAGEMENT`, `EMAIL_PROCESS`)
395
+ - **Resource**: The specific resource within the module (e.g., `USER_MANAGEMENT`, `ROLE_MANAGEMENT`)
396
+ - **Action**: The action being performed (e.g., `VIEW`, `CREATE`, `EDIT`, `DELETE`)
397
+
398
+ ### Using Permission Constants
399
+
400
+ ```python
401
+ from abs_auth_rbac_core.util.permission_constants import (
402
+ PermissionAction,
403
+ PermissionModule,
404
+ PermissionResource,
405
+ PermissionConstants
406
+ )
407
+
408
+ # Using enums
409
+ permission_string = f"{PermissionModule.USER_MANAGEMENT.value}:{PermissionResource.USER_MANAGEMENT.value}:{PermissionAction.VIEW.value}"
410
+
411
+ # Using predefined constants
412
+ user_view_permission = PermissionConstants.RBAC_USER_MANAGEMENT_VIEW
413
+ permission_string = f"{user_view_permission.module}:{user_view_permission.resource}:{user_view_permission.action}"
414
+ ```
415
+
416
+ ### Multiple Permissions
417
+
418
+ ```python
419
+ @rbac_require_permission([
420
+ f"{PermissionModule.USER_MANAGEMENT.value}:{PermissionResource.USER_MANAGEMENT.value}:{PermissionAction.VIEW.value}",
421
+ f"{PermissionModule.USER_MANAGEMENT.value}:{PermissionResource.ROLE_MANAGEMENT.value}:{PermissionAction.VIEW.value}"
422
+ ])
423
+ async def get_user_with_roles():
424
+ # User needs both permissions to access this endpoint
425
+ pass
426
+ ```
427
+
428
+ ## ⚙️ Configuration
429
+
430
+ ### Environment Variables
431
+
432
+ ```bash
433
+ # JWT Configuration
434
+ JWT_SECRET_KEY=your-secret-key-here
435
+ JWT_ALGORITHM=HS256
436
+ JWT_ACCESS_TOKEN_EXPIRE_MINUTES=60
437
+ JWT_REFRESH_TOKEN_EXPIRE_MINUTES=1440
438
+
439
+ # Redis Configuration (for real-time policy updates)
440
+ REDIS_HOST=localhost
441
+ REDIS_PORT=6379
442
+ REDIS_PASSWORD=your-redis-password
443
+ REDIS_CHANNEL=casbin_policy_updates
444
+ REDIS_SSL=false
445
+
446
+ # Database Configuration
447
+ DATABASE_URI=postgresql://user:password@localhost/dbname
448
+ ```
449
+
450
+ ### Casbin Policy Configuration
451
+
452
+ The package uses a default policy configuration that supports:
453
+ - Role-based access control
454
+ - Resource-based permissions
455
+ - Module-based organization
456
+ - Super admin bypass
457
+
458
+ Policy format: `[role] [resource] [action] [module]`
459
+
460
+ ## 🛠️ Advanced Usage
461
+
462
+ ### User Profile with Permissions
463
+
464
+ ```python
465
+ def get_user_profile(self, attr: str, value: any, rbac_service: RBACService) -> UserProfile:
466
+ """Get user profile with permissions and roles"""
467
+ user = self.user_repository.read_by_attr(attr, value, eager=True)
468
+
469
+ # Get user permissions and roles
470
+ permissions = rbac_service.get_user_permissions(user_uuid=user.uuid)
471
+ user_permissions = rbac_service.get_user_only_permissions(user_uuid=user.uuid)
472
+ roles = rbac_service.get_user_roles(user_uuid=user.uuid)
473
+
474
+ # Convert roles to response models
475
+ role_models = [UserRoleResponse.model_validate(role) for role in roles]
476
+
477
+ return UserProfile(
478
+ id=user.id,
479
+ uuid=user.uuid,
480
+ email=user.email,
481
+ name=user.name,
482
+ is_active=user.is_active,
483
+ last_login_at=user.last_login_at,
484
+ permissions=permissions,
485
+ user_permissions=user_permissions,
486
+ roles=role_models,
487
+ )
488
+ ```
489
+
490
+ ### Role and Permission Management
491
+
492
+ ```python
493
+ @router.get("/roles")
494
+ @inject
495
+ @rbac_require_permission(
496
+ f"{PermissionModule.USER_MANAGEMENT.value}:{PermissionResource.ROLE_MANAGEMENT.value}:{PermissionAction.VIEW.value}"
497
+ )
498
+ async def get_roles(
499
+ request: Request,
500
+ rbac_service: RBACService = Depends(Provide[Container.rbac_service]),
501
+ ):
502
+ """Get all roles"""
503
+ return rbac_service.list_roles()
504
+
505
+ @router.post("/roles")
506
+ @inject
507
+ @rbac_require_permission(
508
+ f"{PermissionModule.USER_MANAGEMENT.value}:{PermissionResource.ROLE_MANAGEMENT.value}:{PermissionAction.CREATE.value}"
509
+ )
510
+ async def create_role(
511
+ role: CreateRoleSchema,
512
+ request: Request,
513
+ rbac_service: RBACService = Depends(Provide[Container.rbac_service]),
514
+ ):
515
+ """Create a new role with permissions"""
516
+ return rbac_service.create_role(
517
+ name=role.name,
518
+ description=role.description,
519
+ permission_ids=role.permission_ids
520
+ )
521
+ ```
522
+
523
+ ## 🔍 Authentication Flow
524
+
525
+ ```
526
+ 1. Client Request
527
+ ┌─────────────────┐
528
+ │ Authorization: │
529
+ │ Bearer <token> │
530
+ └─────────────────┘
531
+
532
+
533
+ 2. Auth Middleware
534
+ ┌──────────────────────┐
535
+ │ Validate JWT │
536
+ │ Extract User ID │
537
+ │ Fetch User │
538
+ │ Set in Request state │
539
+ └──────────────────────┘
540
+
541
+
542
+ 3. RBAC Decorator
543
+ ┌─────────────────┐
544
+ │ Get User UUID │
545
+ │ Check Permissions│
546
+ │ Allow/Deny │
547
+ └─────────────────┘
548
+
549
+
550
+ 4. Route Handler
551
+ ┌─────────────────┐
552
+ │ Execute Logic │
553
+ │ Return Response │
554
+ └─────────────────┘
555
+ ```
556
+
557
+ ## 🚨 Error Handling
558
+
559
+ The package includes comprehensive error handling:
560
+
561
+ ```python
562
+ from abs_exception_core.exceptions import (
563
+ UnauthorizedError,
564
+ PermissionDeniedError,
565
+ ValidationError,
566
+ DuplicatedError,
567
+ NotFoundError
568
+ )
569
+
570
+ # Handle authentication errors
571
+ try:
572
+ user = await auth_middleware(request)
573
+ except UnauthorizedError as e:
574
+ return {"error": "Authentication failed", "detail": str(e)}
575
+
576
+ # Handle permission errors
577
+ try:
578
+ # Protected operation
579
+ pass
580
+ except PermissionDeniedError as e:
581
+ return {"error": "Permission denied", "detail": str(e)}
582
+ ```
583
+
584
+ ## 📊 Monitoring and Logging
585
+
586
+ ```python
587
+ import logging
588
+ from abs_utils.logger import setup_logger
589
+
590
+ logger = setup_logger(__name__)
591
+
592
+ # Log authentication events
593
+ logger.info(f"User {user_uuid} authenticated successfully")
594
+
595
+ # Log permission checks
596
+ logger.info(f"Permission check: {user_uuid} -> {resource}:{action}:{module}")
597
+
598
+ # Log role assignments
599
+ logger.info(f"Roles assigned to user {user_uuid}: {role_uuids}")
600
+ ```
601
+
602
+ ## 🏥 Health Checks
603
+
604
+ ```python
605
+ @app.get("/health")
606
+ async def health_check():
607
+ return {
608
+ "status": "healthy",
609
+ "rbac_watcher": rbac_service.is_watcher_active(),
610
+ "policy_count": rbac_service.get_policy_count()
611
+ }
612
+ ```
613
+
614
+ ## 🔧 Troubleshooting
615
+
616
+ ### Common Issues
617
+
618
+ | Issue | Solution |
619
+ |-------|----------|
620
+ | **Authentication Fails** | Check JWT secret key, token expiration, user existence |
621
+ | **Permission Denied** | Verify user roles, role-permission assignments, permission format |
622
+ | **Redis Connection Issues** | Check Redis server status, connection parameters, pub/sub support |
623
+ | **Policy Not Updating** | Verify Redis watcher configuration, policy format, Redis logs |
624
+
625
+ ### Debug Mode
626
+
627
+ ```python
628
+ # Enable debug logging
629
+ import logging
630
+ logging.basicConfig(level=logging.DEBUG)
631
+
632
+ # Check RBAC service status
633
+ print(f"Watcher active: {rbac_service.is_watcher_active()}")
634
+ print(f"Policy count: {rbac_service.get_policy_count()}")
635
+ ```
636
+
637
+ ## 📋 Dependencies
638
+
639
+ ### Core Dependencies
640
+ - **pyjwt** (>=2.10.1,<3.0.0): JWT token handling
641
+ - **fastapi[standard]** (>=0.115.12,<0.116.0): Web framework
642
+ - **passlib** (>=1.7.4,<2.0.0): Password hashing
643
+ - **sqlalchemy** (>=2.0.40,<3.0.0): Database ORM
644
+ - **casbin** (>=1.41.0,<2.0.0): RBAC policy engine
645
+ - **casbin-sqlalchemy-adapter** (>=1.4.0,<2.0.0): Database adapter
646
+ - **casbin-redis-watcher** (>=1.3.0,<2.0.0): Real-time policy updates
647
+
648
+ ### Internal Dependencies
649
+ - **abs-exception-core** (>=0.1.4,<0.2.0): Exception handling
650
+ - **psycopg2-binary** (>=2.9.10,<3.0.0): PostgreSQL adapter
651
+
652
+ ## 🚀 Best Practices
653
+
654
+ ### Security
655
+ - ✅ Use environment variables for sensitive data
656
+ - ✅ Implement proper password policies
657
+ - ✅ Regularly rotate JWT secret keys
658
+ - ✅ Use HTTPS in production
659
+ - ✅ Implement rate limiting for authentication endpoints
660
+
661
+ ### Permission Design
662
+ - ✅ Use descriptive permission names
663
+ - ✅ Group related permissions by module
664
+ - ✅ Implement least privilege principle
665
+ - ✅ Document permission requirements
666
+
667
+ ### Performance
668
+ - ✅ Use Redis for real-time policy updates
669
+ - ✅ Implement caching for frequently accessed permissions
670
+ - ✅ Optimize database queries with eager loading
671
+ - ✅ Monitor policy enforcement performance
672
+
673
+ ### Maintenance
674
+ - ✅ Regularly audit user permissions
675
+ - ✅ Implement permission cleanup for inactive users
676
+ - ✅ Monitor and log security events
677
+ - ✅ Keep dependencies updated
678
+
679
+ ## 📚 API Reference
680
+
681
+ ### RBACService Methods
682
+
683
+ | Method | Description |
684
+ |--------|-------------|
685
+ | `create_role(name, description, permission_ids)` | Create a new role |
686
+ | `assign_role_to_user(user_uuid, role_uuid)` | Assign role to user |
687
+ | `bulk_assign_roles_to_user(user_uuid, role_uuids)` | Assign multiple roles |
688
+ | `check_permission(user_uuid, resource, action, module)` | Check user permission |
689
+ | `get_user_permissions(user_uuid)` | Get all user permissions |
690
+ | `get_user_roles(user_uuid)` | Get user roles |
691
+ | `list_roles()` | List all roles |
692
+ | `is_watcher_active()` | Check Redis watcher status |
693
+
694
+ ### JWT Functions
695
+
696
+ | Method | Description |
697
+ |--------|-------------|
698
+ | `create_access_token(data)` | Create JWT access token |
699
+ | `decode_jwt(token)` | Decode and validate JWT |
700
+ | `hash_password(password)` | Hash password with bcrypt |
701
+ | `verify_password(password, hashed)` | Verify password hash |
702
+
703
+ ## 📄 License
704
+
705
+ This project is licensed under the MIT License - see the LICENSE file for details.
706
+
707
+ ## 🤝 Contributing
708
+
709
+ 1. Fork the repository
710
+ 2. Create a feature branch
711
+ 3. Make your changes
712
+ 4. Add tests
713
+ 5. Submit a pull request
714
+
715
+ ## 📞 Support
716
+
717
+ For support and questions:
718
+ - Email: info@autobridgesystems.com
719
+ - Documentation: [Link to documentation]
720
+ - Issues: [GitHub Issues]
721
+
722
+ ---
723
+
724
+ **Version**: 0.2.0
725
+ **Last Updated**: 2024
726
+ **Python Version**: >=3.12,<4.0
727
+