Backend API Reference¶
This page is auto-generated from the backend source code using mkdocstrings.
Live Interactive API Docs¶
- FastAPI Swagger UI (Live) — Browse and try all API endpoints interactively (local development)
- FastAPI ReDoc (Live) — Alternative OpenAPI documentation (local development)
If your backend is deployed, replace
localhost:8000
with your server’s address.
FastAPI Endpoints & Schemas¶
api.v1.auth
¶
REGISTER_SUMMARY = 'Register a new user'
module-attribute
¶
REGISTER_DESCRIPTION = '\n**User Registration**\n\nCreates a new user account and returns authentication tokens for immediate login.\n\n**Process:**\n1. Validates email format and password strength\n2. Checks if email is already registered\n3. Creates user account with hashed password\n4. Returns JWT tokens for authentication\n\n**Requirements:**\n- Email must be valid and unique\n- Password must be at least 8 characters\n- Name is optional but recommended\n- API key required for registration\n\n**Rate Limiting:** 5 attempts per email per hour\n\n**Security Features:**\n- Password hashing with bcrypt\n- Email verification (optional)\n- Rate limiting to prevent abuse\n- API key requirement for service protection\n\n**Response:** Returns access token, refresh token, and user profile data\n\n**Examples:**\n```json\n{\n "email": "user@example.com",\n "password": "SecurePassword123!",\n "name": "Jane Doe"\n}\n```\n\n**Error Codes:**\n- `400`: Invalid input data\n- `409`: Email already registered\n- `429`: Too many registration attempts\n- `422`: Validation errors\n'
module-attribute
¶
LOGIN_SUMMARY = 'User login'
module-attribute
¶
LOGIN_DESCRIPTION = '\n**User Authentication**\n\nAuthenticates user credentials and returns JWT tokens for API access.\n\n**Process:**\n1. Validates email and password credentials\n2. Checks account status (active, not locked)\n3. Issues access and refresh tokens\n4. Returns user profile information\n\n**Authentication Methods:**\n- **Email + Password**: Standard login method\n- **Rate Limited**: 10 attempts per IP per minute\n\n**Token Details:**\n- **Access Token**: Valid for 24 hours, use for API requests\n- **Refresh Token**: Valid for 7 days, use to get new access tokens\n- **Token Type**: Bearer (include in Authorization header)\n\n**Security Features:**\n- Password verification with timing attack protection\n- Account lockout after failed attempts\n- Secure token generation with cryptographic signatures\n- IP-based rate limiting\n\n**Usage Examples:**\n\n\n*Request:*\n```json\n{\n "email": "user@example.com",\n "password": "yourpassword"\n}\n```\n\n*Response:*\n```json\n{\n "access_token": "eyJhbGciOiJIUzI1NiIs...",\n "refresh_token": "eyJhbGciOiJIUzI1NiIs...",\n "token_type": "bearer",\n "expires_in": 86400,\n "user": {\n "id": 123,\n "email": "user@example.com",\n "name": "Jane Doe"\n }\n}\n```\n\n**Error Codes:**\n- `400`: Missing or invalid credentials\n- `401`: Invalid email or password\n- `429`: Too many login attempts\n- `423`: Account temporarily locked\n'
module-attribute
¶
LOGOUT_SUMMARY = 'Logout user'
module-attribute
¶
LOGOUT_DESCRIPTION = '\nLogs out the current user and blacklists the access token.\n\n**Steps:**\n1. User sends a logout request with a valid access token.\n2. System blacklists the token and ends the session.\n\n**Notes:**\n- Blacklisted tokens cannot be reused.\n- Rate limiting is applied to prevent abuse.\n'
module-attribute
¶
REFRESH_SUMMARY = 'Refresh JWT access token'
module-attribute
¶
REFRESH_DESCRIPTION = '\nRefreshes the JWT access token using a valid refresh token.\n\n**Steps:**\n1. User provides a valid refresh token.\n2. System validates the token and issues a new access token.\n\n**Notes:**\n- Expired or blacklisted tokens will be rejected.\n- Rate limiting is applied to prevent abuse.\n'
module-attribute
¶
PWRESET_REQUEST_SUMMARY = 'Request password reset'
module-attribute
¶
PWRESET_REQUEST_DESCRIPTION = '\nInitiates a password reset flow.\n\n**Steps:**\n1. User submits email via this endpoint.\n2. System sends a password reset link to the email if it exists.\n3. User clicks the link and is directed to the reset form.\n4. User completes the process via `/reset-password`.\n\n**Notes:**\n- For security, this endpoint always returns a success message, even if the email is not registered.\n- Rate limiting is applied to prevent abuse.\n'
module-attribute
¶
PWRESET_SUMMARY = 'Reset password'
module-attribute
¶
PWRESET_DESCRIPTION = '\nCompletes the password reset flow using a valid reset token.\n\n**Steps:**\n1. User receives a reset link from `/request-password-reset`.\n2. User submits the token and new password to this endpoint.\n3. System validates the token and updates the password.\n\n**Notes:**\n- The token must be valid and not expired.\n- Rate limiting is applied to prevent abuse.\n'
module-attribute
¶
ME_SUMMARY = 'Get current user profile'
module-attribute
¶
ME_DESCRIPTION = '\nReturns the profile information of the currently authenticated user.\n\n**How it works:**\n- Requires a valid JWT Bearer token.\n- Returns user ID, email, name, bio, avatar, and timestamps.\n'
module-attribute
¶
router = APIRouter(tags=['Auth'])
module-attribute
¶
LogExtraDict
¶
Bases: TypedDict
email
instance-attribute
¶
limiter_key
instance-attribute
¶
action
instance-attribute
¶
error
instance-attribute
¶
error_type
instance-attribute
¶
user_id
instance-attribute
¶
token_length
instance-attribute
¶
token
instance-attribute
¶
token_prefix
instance-attribute
¶
traceback
instance-attribute
¶
UserActionLimiterProtocol
¶
is_allowed(key)
async
¶
Source code in api/v1/auth.py
251 252 |
|
check_rate_limit(user_action_limiter, limiter_key, log_extra, action='action')
async
¶
Checks if the action is allowed by the rate limiter. Raises HTTP 429 if not allowed.
Source code in api/v1/auth.py
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 |
|
common_auth_deps(feature)
¶
Returns a tuple of common dependencies for auth endpoints.
Source code in api/v1/auth.py
274 275 276 277 278 279 280 281 282 |
|
rate_limit(action, key_func=None)
¶
Returns a dependency for rate limiting.
Source code in api/v1/auth.py
285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
|
register(data=Body(..., examples=[{'summary': 'A typical registration', 'value': {'email': 'user@example.com', 'password': 'strongpassword123', 'name': 'Jane Doe'}}]), session=Depends(get_db), user_service=Depends(get_user_service), user_action_limiter=Depends(get_user_action_limiter))
async
¶
Registers a new user account and returns a JWT access token.
Raises:
Type | Description |
---|---|
UserAlreadyExistsError | If the user already exists. |
InvalidDataError | If registration data is invalid. |
Exception | For unexpected errors. |
Source code in api/v1/auth.py
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 |
|
login(data, session=Depends(get_db), user_service=Depends(get_user_service), user_action_limiter=Depends(get_user_action_limiter))
async
¶
Authenticates a user and returns a JWT access token.
Raises:
Type | Description |
---|---|
UserNotFoundError | If user is not found. |
ValidationError | If credentials are invalid. |
Exception | For unexpected errors. |
Source code in api/v1/auth.py
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 |
|
logout(request, current_user=Depends(get_current_user), session=Depends(get_db), user_service=Depends(get_user_service), blacklist_token=Depends(get_blacklist_token))
async
¶
Logs out the current user and blacklists the access token.
Raises:
Type | Description |
---|---|
Exception | If token is invalid or expired. |
Source code in api/v1/auth.py
497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 |
|
refresh_token(body=Body(...), session=Depends(get_db), async_refresh_access_token=Depends(get_async_refresh_access_token))
async
¶
Accepts either {"token": ...} or {"refresh_token": ...} for compatibility with tests.
Raises:
Type | Description |
---|---|
RefreshTokenRateLimitError | If too many attempts. |
RefreshTokenBlacklistedError | If token is blacklisted. |
RefreshTokenError | If token is invalid. |
ValueError | If token is missing or invalid. |
Source code in api/v1/auth.py
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 |
|
request_password_reset(data, session=Depends(get_db), user_service=Depends(get_user_service), user_action_limiter=Depends(get_user_action_limiter), validate_email=Depends(get_validate_email))
async
¶
Initiates a password reset flow.
Raises:
Type | Description |
---|---|
Exception | For unexpected errors. |
Source code in api/v1/auth.py
651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 |
|
reset_password(data=Body(...), session=Depends(get_db), user_service=Depends(get_user_service), get_password_validation_error=Depends(get_password_validation_error))
async
¶
Completes the password reset flow using a valid reset token.
Raises:
Type | Description |
---|---|
ValidationError | If password is invalid. |
Exception | For unexpected errors. |
Source code in api/v1/auth.py
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 |
|
get_me(current_user=Depends(get_current_user))
async
¶
Returns the profile information of the currently authenticated user.
Source code in api/v1/auth.py
757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 |
|
api.v1.uploads
¶
ROUTER_PREFIX = '/uploads'
module-attribute
¶
ROUTER_TAGS = ('File',)
module-attribute
¶
FileInDB = DBFile
module-attribute
¶
router = APIRouter(prefix=ROUTER_PREFIX, tags=list(ROUTER_TAGS))
module-attribute
¶
FileDict
¶
FileUploadResponse
¶
FileListResponse
¶
Bases: BaseModel
files
instance-attribute
¶
total
instance-attribute
¶
model_config = ConfigDict(json_schema_extra={'examples': [{'files': [{'filename': 'document.pdf', 'url': '/uploads/document.pdf'}, {'filename': 'image.jpg', 'url': '/uploads/image.jpg'}, {'filename': 'only_filename.pdf'}], 'total': 3}]})
class-attribute
instance-attribute
¶
FileResponse
¶
Bases: BaseModel
filename
instance-attribute
¶
url
instance-attribute
¶
content_type = None
class-attribute
instance-attribute
¶
size = None
class-attribute
instance-attribute
¶
created_at = None
class-attribute
instance-attribute
¶
model_config = ConfigDict(json_schema_extra={'example': {'filename': 'document.pdf', 'url': '/uploads/document.pdf', 'content_type': 'application/pdf', 'size': 1024, 'created_at': '2025-06-20T12:00:00Z'}})
class-attribute
instance-attribute
¶
BulkDeleteRequest
¶
BulkDeleteResponse
¶
ensure_nonempty_filename(file=FastAPIFile(...))
¶
Ensures the uploaded file has a non-empty filename. Raises: HTTPException: If the filename is empty.
Source code in api/v1/uploads.py
156 157 158 159 160 161 162 163 164 165 166 167 168 169 |
|
root_test()
async
¶
Source code in api/v1/uploads.py
215 216 217 |
|
test_alive()
async
¶
Source code in api/v1/uploads.py
248 249 250 |
|
export_alive()
async
¶
Source code in api/v1/uploads.py
279 280 281 |
|
export_test(current_user=Depends(get_current_user))
async
¶
Source code in api/v1/uploads.py
284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 |
|
export_files_csv(session=Depends(get_async_session), current_user=Depends(get_current_user), params=Depends(pagination_params), q=Query(None, description='Search by filename (partial match)'), sort=Query('created_at', description='Sort by field: created_at, filename'), order=Query('desc', description='Sort order: asc or desc'), fields=Query(None, description='Comma-separated list of fields to include in response (e.g. filename,url)'), created_before=Query(None, description='Filter files created before this datetime (ISO 8601, e.g. 2024-01-01T00:00:00Z)'), created_after=Query(None, description='Filter files created after this datetime (ISO 8601, e.g. 2024-01-01T00:00:00Z)'), request_id=Depends(get_request_id), feature_flag_ok=Depends(require_feature('uploads:export')), api_key_ok=Depends(require_api_key))
async
¶
Export the list of uploaded files as a CSV file. Raises: HTTPException: If date parsing fails.
Source code in api/v1/uploads.py
324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
|
upload_file(file=FastAPIFile(..., description='The file to upload. Must be a valid file type.'), session=Depends(get_async_session), current_user=Depends(get_current_user), request_id=Depends(get_request_id), feature_flag_ok=Depends(require_feature('uploads:upload')), api_key_ok=Depends(require_api_key))
async
¶
Uploads a file and returns its filename and URL. Raises: HTTPException: If file is invalid or upload fails.
Source code in api/v1/uploads.py
550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 |
|
bulk_delete_files_endpoint(request_data, session=Depends(get_async_session), current_user=Depends(get_current_user), request_id=Depends(get_request_id), feature_flag_ok=Depends(require_feature('uploads:bulk_delete')), api_key_ok=Depends(require_api_key))
async
¶
Bulk delete files for the current user.
Source code in api/v1/uploads.py
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 |
|
get_file(filename=Path(..., description='The name of the file to retrieve.'), session=Depends(get_async_session), current_user=Depends(get_current_user))
async
¶
Retrieves metadata for an uploaded file by filename. Raises: HTTPException: If file is not found.
Source code in api/v1/uploads.py
979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 |
|
delete_file_by_filename(filename=Path(..., description='The name of the file to delete.'), session=Depends(get_async_session), current_user=Depends(get_current_user), request_id=Depends(get_request_id), feature_flag_ok=Depends(require_feature('uploads:delete')), api_key_ok=Depends(require_api_key))
async
¶
Deletes an uploaded file by filename. Raises: HTTPException: If file is not found.
Source code in api/v1/uploads.py
1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 |
|
download_file(filename=Path(..., description='The name of the file to download.'), session=Depends(get_async_session), current_user=Depends(get_current_user), request_id=Depends(get_request_id), feature_flag_ok=Depends(require_feature('uploads:download')), api_key_ok=Depends(require_api_key))
async
¶
Download file content with proper headers. Raises: HTTPException: If file is not found or access denied.
Source code in api/v1/uploads.py
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 |
|
catch_all_uploads(path, request)
async
¶
Catch-all route for uploads. Always returns status 418.
Source code in api/v1/uploads.py
1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 |
|
list_files(params=Depends(pagination_params), session=Depends(get_async_session), current_user=Depends(get_current_user), request_id=Depends(get_request_id), feature_flag_ok=Depends(require_feature('uploads:list')), api_key_ok=Depends(require_api_key), q=Query(None, description='Search term across all fields'), fields=Query(None, description='Comma-separated list of fields to include'), sort=Query('created_at', description='Field to sort by'), order=Query('desc', description='Sort order (asc or desc)'), created_after=Query(None, description='Filter by creation date (ISO format)'), created_before=Query(None, description='Filter by creation date (ISO format)'))
async
¶
List all uploaded files with pagination and filtering options. Raises: HTTPException: If date parsing fails.
Source code in api/v1/uploads.py
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 |
|
api.v1.users
¶
Aggregate all user-related routers for easy import in the FastAPI app.
all_routers = [exports_router, core_router, test_only_router]
module-attribute
¶
Models¶
models.user
¶
User
¶
Bases: BaseModel
User model.
__tablename__ = 'users'
class-attribute
instance-attribute
¶
email = mapped_column(String(255), unique=True, nullable=False, index=True)
class-attribute
instance-attribute
¶
hashed_password = mapped_column(String(255), nullable=False)
class-attribute
instance-attribute
¶
is_active = mapped_column(Boolean, default=True, nullable=False)
class-attribute
instance-attribute
¶
is_deleted = mapped_column(Boolean, default=False, nullable=False)
class-attribute
instance-attribute
¶
last_login_at = mapped_column(DateTime, nullable=True)
class-attribute
instance-attribute
¶
name = mapped_column(String(128), nullable=True)
class-attribute
instance-attribute
¶
bio = mapped_column(String(512), nullable=True)
class-attribute
instance-attribute
¶
avatar_url = mapped_column(String(255), nullable=True)
class-attribute
instance-attribute
¶
preferences = mapped_column(JSON, nullable=True)
class-attribute
instance-attribute
¶
is_admin = mapped_column(Boolean, default=False, nullable=False)
class-attribute
instance-attribute
¶
files = relationship('File', back_populates='user', passive_deletes=True)
class-attribute
instance-attribute
¶
role
property
writable
¶
Returns the role of the user.
Returns:
Type | Description |
---|---|
Literal['admin', 'user'] | Literal["admin", "user"]: The user's role. |
__repr__()
¶
Return a string representation of the User instance.
Returns:
Name | Type | Description |
---|---|---|
str | str | String representation of the instance. |
Source code in models/user.py
68 69 70 71 72 73 74 75 |
|
models.file
¶
File
¶
Bases: BaseModel
SQLAlchemy model for a file uploaded by a user.
__tablename__ = 'files'
class-attribute
instance-attribute
¶
__table_args__ = (Index('ix_files_user_id', 'user_id'),)
class-attribute
instance-attribute
¶
filename = mapped_column(String(255), nullable=False)
class-attribute
instance-attribute
¶
content_type = mapped_column(String(128), nullable=False)
class-attribute
instance-attribute
¶
size = mapped_column(BigInteger, nullable=True, default=0)
class-attribute
instance-attribute
¶
user_id = mapped_column(ForeignKey('users.id'), nullable=False)
class-attribute
instance-attribute
¶
user = relationship('User', back_populates='files')
class-attribute
instance-attribute
¶
__repr__()
¶
Return a string representation of the File instance.
:raises AttributeError: If 'id' or 'filename' attributes are not set (e.g., before flush). :return: String representation of the File instance.
Source code in models/file.py
35 36 37 38 39 40 41 |
|
models.used_password_reset_token
¶
UsedPasswordResetToken(*args, **kwargs)
¶
Bases: BaseModel
Source code in models/used_password_reset_token.py
45 46 47 48 49 50 51 |
|
__tablename__ = 'used_password_reset_tokens'
class-attribute
instance-attribute
¶
email = mapped_column(String(255), nullable=False, index=True)
class-attribute
instance-attribute
¶
nonce = mapped_column(String(64), nullable=False, index=True)
class-attribute
instance-attribute
¶
used_at_default = lambda: datetime.now(UTC)
class-attribute
¶
used_at = mapped_column('used_at', DateTime(timezone=True), default=used_at_default, nullable=False)
class-attribute
instance-attribute
¶
used_at_aware
property
¶
Always return used_at as a timezone-aware datetime (UTC).
validate_not_empty(key, value)
¶
Validate that the given value is a non-empty string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
key | str | The name of the field being validated. | required |
value | str | The value to validate. | required |
Returns:
Name | Type | Description |
---|---|---|
str | str | The validated value. |
Raises:
Type | Description |
---|---|
ValueError | If the value is not a non-empty string. |
Source code in models/used_password_reset_token.py
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
|
__repr__()
¶
Return a string representation of the UsedPasswordResetToken instance.
Returns:
Name | Type | Description |
---|---|---|
str | str | String representation of the instance. |
Source code in models/used_password_reset_token.py
74 75 76 77 78 79 80 81 |
|
Schemas¶
schemas.auth
¶
TOKEN_TYPE_BEARER = 'bearer'
module-attribute
¶
UserRegisterRequest
¶
Bases: BaseModel
email
instance-attribute
¶
password = Field(..., min_length=8, max_length=128)
class-attribute
instance-attribute
¶
name = Field(None, max_length=128)
class-attribute
instance-attribute
¶
validate_email_field(v)
classmethod
¶
Validates the email field. Raises: ValueError: If the email format is invalid.
Source code in schemas/auth.py
28 29 30 31 32 33 34 35 36 37 38 |
|
validate_password_field(v)
classmethod
¶
Validates the password field. Raises: ValueError: If the password does not meet requirements.
Source code in schemas/auth.py
40 41 42 43 44 45 46 47 48 49 50 51 |
|
PasswordResetRequest
¶
Bases: BaseModel
email
instance-attribute
¶
validate_email_field(v)
classmethod
¶
Validates the email field for password reset. Raises: ValueError: If the email format is invalid.
Source code in schemas/auth.py
67 68 69 70 71 72 73 74 75 76 77 |
|
PasswordResetConfirmRequest
¶
Bases: BaseModel
token
instance-attribute
¶
new_password = Field(..., min_length=8, max_length=128)
class-attribute
instance-attribute
¶
validate_password_field(v)
classmethod
¶
Validates the new password field for password reset confirmation. Raises: ValueError: If the password does not meet requirements.
Source code in schemas/auth.py
89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
|
AuthResponseDict
¶
AuthResponse
¶
schemas.file
¶
FileSchema
¶
Bases: BaseModel
Schema for file metadata used in API requests and responses.
Attributes:
Name | Type | Description |
---|---|---|
id | int | Unique identifier for the file. |
filename | str | Name of the file. |
content_type | str | MIME type of the file. |
user_id | int | ID of the user who owns the file. |
created_at | datetime | Timestamp when the file was created. |
id = Field(..., description='Unique identifier for the file')
class-attribute
instance-attribute
¶
filename = Field(..., max_length=255, description='Name of the file')
class-attribute
instance-attribute
¶
content_type = Field(..., max_length=128, description='MIME type of the file')
class-attribute
instance-attribute
¶
user_id = Field(..., description='ID of the user who owns the file')
class-attribute
instance-attribute
¶
created_at = Field(..., description='Timestamp when the file was created')
class-attribute
instance-attribute
¶
model_config = ConfigDict(from_attributes=True)
class-attribute
instance-attribute
¶
schemas.token
¶
Token-related schemas for authentication and authorization.
TokenResponse
¶
Bases: BaseModel
Response schema for authentication endpoints that return tokens.
access_token = Field(..., description='JWT access token')
class-attribute
instance-attribute
¶
refresh_token = Field(..., description='JWT refresh token')
class-attribute
instance-attribute
¶
token_type = Field(default='bearer', description='Token type')
class-attribute
instance-attribute
¶
expires_in = Field(None, description='Token expiration time in seconds')
class-attribute
instance-attribute
¶
RefreshTokenRequest
¶
Bases: BaseModel
Request schema for refresh token endpoint.
refresh_token = Field(..., description='Refresh token to exchange for new access token')
class-attribute
instance-attribute
¶
TokenData
¶
Bases: BaseModel
Token payload data schema.
user_id = Field(..., description='User ID from token')
class-attribute
instance-attribute
¶
email = Field(None, description='User email from token')
class-attribute
instance-attribute
¶
exp = Field(None, description='Token expiration timestamp')
class-attribute
instance-attribute
¶
jti = Field(None, description='JWT ID for token tracking')
class-attribute
instance-attribute
¶
schemas.user
¶
UserResponse = UserProfile
module-attribute
¶
UserProfile
¶
Bases: BaseModel
id
instance-attribute
¶
email
instance-attribute
¶
name = None
class-attribute
instance-attribute
¶
bio = None
class-attribute
instance-attribute
¶
avatar_url = None
class-attribute
instance-attribute
¶
created_at = None
class-attribute
instance-attribute
¶
updated_at = None
class-attribute
instance-attribute
¶
model_config = ConfigDict(extra='forbid')
class-attribute
instance-attribute
¶
UserProfileUpdate
¶
UserPreferences
¶
Bases: BaseModel
UserRead
¶
Bases: UserProfile
UserCreateRequest
¶
Services¶
services.user
¶
User service: registration, authentication, logout, and authentication check.
InvalidDataError = InvalidDataError
module-attribute
¶
UserAlreadyExistsError = UserAlreadyExistsError
module-attribute
¶
user_service_instance = UserService()
module-attribute
¶
__all__ = ['InvalidDataError', 'RefreshTokenBlacklistedError', 'RefreshTokenError', 'RefreshTokenRateLimitError', 'UserAlreadyExistsError', 'UserNotFoundError', 'ValidationError', 'create_access_token', 'update_last_login', 'user_repo']
module-attribute
¶
UserRole
¶
RegisterUserData
¶
PaginatedUsersResponse
¶
RefreshTokenError
¶
Bases: Exception
RefreshTokenRateLimitError
¶
Bases: Exception
RefreshTokenBlacklistedError
¶
Bases: Exception
UserService
¶
Service class for user registration, authentication, profile, and password management. Wraps the module-level functions for better type safety and DI.
register_user(session, data)
async
¶
Source code in services/user.py
695 696 697 698 699 700 |
|
authenticate_user(session, email, password)
async
¶
Source code in services/user.py
702 703 704 705 706 707 708 |
|
logout_user(session, user_id)
async
¶
Source code in services/user.py
710 711 |
|
reset_password(session, token, new_password)
async
¶
Source code in services/user.py
713 714 715 716 717 718 719 |
|
get_password_reset_token(email)
¶
Source code in services/user.py
721 722 |
|
get_users_paginated(session, page=1, limit=20)
async
¶
Source code in services/user.py
724 725 726 727 728 729 730 |
|
get_user_profile(session, user_id)
async
¶
Source code in services/user.py
732 733 734 735 736 737 |
|
update_user(session, user_id, data)
async
¶
Source code in services/user.py
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 |
|
delete_user(session, user_id)
async
¶
Source code in services/user.py
780 781 782 783 784 785 |
|
list_users(session, offset=0, limit=20, email=None, name=None, created_after=None)
async
¶
Source code in services/user.py
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 |
|
get_user_by_id(session, user_id)
async
¶
Source code in services/user.py
808 809 810 811 |
|
register_user(session, data)
async
¶
Register a new user. Hashes the password and stores the user in the database. Raises ValidationError or UserAlreadyExistsError on error. :raises ValidationError: If email or password is missing. :raises UserAlreadyExistsError: If user already exists.
Source code in services/user.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
|
authenticate_user(session, email, password)
async
¶
Authenticate user credentials and return a tuple of (access_token, refresh_token). Raises ValidationError or UserNotFoundError on error. If authentication is disabled, return default tokens for dev user. :raises ValidationError: If password is incorrect. :raises UserNotFoundError: If user not found or inactive.
Source code in services/user.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 |
|
logout_user(session, user_id)
async
¶
Invalidate the user's session or refresh token (stub: deactivate user for now). :raises Exception: If deactivation fails.
Source code in services/user.py
195 196 197 198 199 200 201 |
|
is_authenticated(user)
¶
Check if a user is currently authenticated. If authentication is disabled, always return True.
Source code in services/user.py
204 205 206 207 208 209 210 211 212 213 214 |
|
refresh_access_token(user_id, refresh_token)
¶
Validate the refresh token and issue a new access token. Stub: No persistent token storage yet. :raises ValidationError: If token is invalid or subject mismatch.
Source code in services/user.py
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 |
|
revoke_refresh_token(user_id, token)
¶
Blacklist or invalidate the refresh token (stub).
Source code in services/user.py
244 245 |
|
verify_email_token(token)
¶
Decode and verify an email confirmation token. :raises ValidationError: If token is invalid.
Source code in services/user.py
249 250 251 252 253 254 255 256 257 258 |
|
get_password_reset_token(email)
¶
Generate a secure token and simulate sending a reset link via logging.
Source code in services/user.py
261 262 263 264 265 266 267 268 269 270 271 272 |
|
reset_password(session, token, new_password)
async
¶
Validate the reset token and update the user's password. Enforces one-time-use tokens. :raises ValidationError: If token is invalid or password is invalid. :raises UserNotFoundError: If user not found.
Source code in services/user.py
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 |
|
change_password(session, user_id, old_pw, new_pw)
async
¶
Check old password and update if correct. :raises UserNotFoundError: If user not found. :raises ValidationError: If password is invalid.
Source code in services/user.py
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 |
|
validate_password_strength(password)
¶
Ensure the password is strong (length, characters, etc). Raise if not. Rejects passwords with whitespace or non-ASCII characters. :raises ValidationError: If password is weak or contains invalid characters.
Source code in services/user.py
382 383 384 385 386 387 388 389 390 391 392 393 394 395 |
|
get_user_profile(session, user_id)
async
¶
Source code in services/user.py
398 399 400 401 402 403 404 405 406 407 408 409 410 |
|
update_user_profile(session, user_id, data)
async
¶
Source code in services/user.py
413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 |
|
set_user_preferences(session, user_id, preferences)
async
¶
Source code in services/user.py
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 |
|
upload_avatar(session, user_id, file)
async
¶
Source code in services/user.py
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 |
|
delete_user_account(session, user_id, *, anonymize=False)
async
¶
Delete or anonymize a user account depending on policy. If anonymize=True, irreversibly remove PII and disable account (GDPR). Otherwise, perform a soft delete (set is_deleted flag). Always logs the action for audit purposes. Returns True if operation succeeded, False otherwise.
Source code in services/user.py
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 |
|
deactivate_user(session, user_id)
async
¶
Mark the user as inactive (is_active=False). Logs the change for audit. Returns True if operation succeeded, False otherwise.
Source code in services/user.py
513 514 515 516 517 518 519 520 521 522 523 524 |
|
reactivate_user(session, user_id)
async
¶
Reactivate a previously deactivated user (is_active=True). Logs the change for audit. Returns True if operation succeeded, False otherwise.
Source code in services/user.py
527 528 529 530 531 532 533 534 535 536 537 538 |
|
get_user_by_username(session, username)
async
¶
Look up a user by username (email). Returns user if found, else None. Validates input. :raises ValidationError: If username is missing or invalid.
Source code in services/user.py
541 542 543 544 545 546 547 548 549 550 551 |
|
get_users_paginated(session, page=1, limit=20, email=None, name=None)
async
¶
Return paginated users and total count. Validates input and returns structured response. :raises ValidationError: If pagination parameters are invalid.
Source code in services/user.py
561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 |
|
user_exists(session, email)
async
¶
Return whether the email is already registered. Validates input. :raises ValidationError: If email is missing or invalid.
Source code in services/user.py
586 587 588 589 590 591 592 593 594 595 596 |
|
assign_role(user_id, role)
async
¶
Assign a role to a user. Allowed roles: admin, user, moderator. This is a stub; in production, store in DB. :raises ValidationError: If role is invalid.
Source code in services/user.py
599 600 601 602 603 604 605 606 607 608 |
|
check_user_role(user_id, required_role)
async
¶
Check if user has the required role. Stub: checks in-memory store.
Source code in services/user.py
611 612 613 614 |
|
async_refresh_access_token(session, token, jwt_secret, jwt_algorithm, max_attempts=15, window_seconds=3600)
async
¶
Validate the refresh token, apply rate limiting, check blacklist, and issue a new access token. Maximized robustness: strict type checks, user existence check, clear error messages, and no debug logs in production. Raises custom exceptions for all error/edge branches. :raises RefreshTokenError: On JWT decode or user not found. :raises RefreshTokenRateLimitError: On rate limit exceeded. :raises RefreshTokenBlacklistedError: If token is blacklisted.
Source code in services/user.py
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 |
|
get_user_service()
¶
Source code in services/user.py
818 819 |
|
services.upload
¶
Upload service for handling file uploads and management.
UploadService()
¶
Service for handling file uploads and management.
Source code in services/upload.py
18 19 20 21 |
|
settings = get_settings()
instance-attribute
¶
upload_dir = Path(self.settings.upload_dir)
instance-attribute
¶
upload_file(session, file, user_id)
async
¶
Upload a file and save it to storage.
Source code in services/upload.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
|
get_file(session, filename)
async
¶
Get file metadata by filename.
Source code in services/upload.py
66 67 68 |
|
delete_file(session, filename, user_id)
async
¶
Delete a file from storage and database.
Source code in services/upload.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
|
get_file_path(filename)
¶
Get the full path to a file.
Source code in services/upload.py
95 96 97 |
|
Repositories¶
repositories.user
¶
user_action_limiter = AsyncRateLimiter(max_calls=5, period=60.0)
module-attribute
¶
logger = logging.getLogger('user_audit')
module-attribute
¶
__all__ = ['safe_get_user_by_id', 'create_user_with_validation', 'sensitive_user_action', 'anonymize_user', 'user_signups_per_month', 'UserNotFoundError', 'select']
module-attribute
¶
UserUpdateData
¶
UserCSVRow
¶
UserJSONRow
¶
get_user_by_id(session, user_id, use_cache=True)
async
¶
Fetch a user by their ID, optionally using async cache (cache only user id, not ORM instance). Raises: None
Source code in repositories/user.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
|
create_user_with_validation(session, email, password, name=None)
async
¶
Create a user with validation and error handling. Raises: ValidationError: If email or password is invalid. UserAlreadyExistsError: If email already exists. Exception: On DB commit failure.
Source code in repositories/user.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
|
sensitive_user_action(session, user_id, action)
async
¶
Example of a rate-limited sensitive action. Raises: UserNotFoundError: If user not found. RateLimitExceededError: If rate limit exceeded.
Source code in repositories/user.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 |
|
safe_get_user_by_id(session, user_id)
async
¶
Get user by ID or raise UserNotFoundError. Raises: UserNotFoundError: If user not found.
Source code in repositories/user.py
133 134 135 136 137 138 139 140 141 |
|
get_users_by_ids(session, user_ids)
async
¶
Fetch multiple users by a list of IDs.
Source code in repositories/user.py
144 145 146 147 148 149 150 151 152 |
|
list_users_paginated(session, offset=0, limit=20)
async
¶
List users with pagination support.
Source code in repositories/user.py
155 156 157 158 159 160 161 162 163 |
|
list_users(session, offset=0, limit=20, email=None, name=None, q=None, sort='created_at', order='desc', created_after=None, created_before=None)
async
¶
List users with filtering and pagination. Returns: (users, total_count)
Source code in repositories/user.py
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 |
|
search_users_by_name_or_email(session, query, offset=0, limit=20)
async
¶
Search users by partial match on email (and name if available).
Source code in repositories/user.py
209 210 211 212 213 214 215 216 217 218 |
|
filter_users_by_status(session, is_active)
async
¶
Fetch users filtered by their active status.
Source code in repositories/user.py
221 222 223 224 225 226 227 |
|
filter_users_by_role(session, role)
async
¶
Stub: Fetch users filtered by role. Not implemented (no role field).
Source code in repositories/user.py
230 231 232 233 |
|
get_users_created_within(session, start, end)
async
¶
Fetch users created within a date range (inclusive).
Source code in repositories/user.py
236 237 238 239 240 241 242 243 244 |
|
count_users(session, is_active=None)
async
¶
Count users, optionally filtered by active status.
Source code in repositories/user.py
247 248 249 250 251 252 253 254 |
|
get_active_users(session)
async
¶
Fetch all active users.
Source code in repositories/user.py
257 258 259 |
|
get_inactive_users(session)
async
¶
Fetch all inactive users.
Source code in repositories/user.py
262 263 264 |
|
get_users_by_custom_field(session, field, value)
async
¶
Stub: Fetch users by a custom field (e.g., organization). Not implemented (no such field).
Source code in repositories/user.py
267 268 269 270 271 272 |
|
bulk_create_users(session, users)
async
¶
Bulk create users and return them with IDs. Raises: Exception: On DB commit failure.
Source code in repositories/user.py
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
|
bulk_update_users(session, user_ids, update_data)
async
¶
Bulk update users by IDs with the given update_data dict. Returns number of updated rows. Raises: Exception: On DB commit failure.
Source code in repositories/user.py
304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 |
|
bulk_delete_users(session, user_ids)
async
¶
Bulk delete users by IDs. Returns number of deleted rows. Raises: Exception: On DB commit failure.
Source code in repositories/user.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
|
soft_delete_user(session, user_id)
async
¶
Mark a user as deleted (soft delete). Raises: Exception: On DB commit failure.
Source code in repositories/user.py
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 |
|
restore_user(session, user_id)
async
¶
Restore a soft-deleted user. Raises: Exception: On DB commit failure.
Source code in repositories/user.py
363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 |
|
upsert_user(session, email, defaults)
async
¶
Insert or update a user by email. Returns the user. Raises: ValidationError: If email is invalid. Exception: On DB commit failure.
Source code in repositories/user.py
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
|
partial_update_user(session, user_id, update_data)
async
¶
Update only provided fields for a user. Raises: Exception: On DB commit failure.
Source code in repositories/user.py
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 |
|
user_exists(session, user_id)
async
¶
Check if a user exists by ID.
Source code in repositories/user.py
433 434 435 436 437 |
|
is_email_unique(session, email, exclude_user_id=None)
async
¶
Check if an email is unique (optionally excluding a user by ID).
Source code in repositories/user.py
440 441 442 443 444 445 446 447 448 449 |
|
change_user_password(session, user_id, new_hashed_password)
async
¶
Change a user's password (hashed). Raises: Exception: On DB commit failure.
Source code in repositories/user.py
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 |
|
audit_log_user_change(session, user_id, action, details='')
async
¶
Log an audit event for a user change. In production, consider integrating with Azure Monitor or Application Insights. Raises: None
Source code in repositories/user.py
475 476 477 478 479 480 481 482 |
|
assign_role_to_user(session, user_id, role)
async
¶
Stub: Assign a role to a user. Not implemented (no role field).
Source code in repositories/user.py
486 487 488 |
|
revoke_role_from_user(session, user_id, role)
async
¶
Stub: Revoke a role from a user. Not implemented (no role field).
Source code in repositories/user.py
491 492 493 |
|
db_session_context()
async
¶
Async context manager for DB session. Yields: AsyncSession
Source code in repositories/user.py
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 |
|
db_transaction(session)
async
¶
Async context manager for DB transaction (atomic operations). Yields: AsyncSession
Source code in repositories/user.py
517 518 519 520 521 522 523 524 |
|
get_user_with_files(session, user_id)
async
¶
Fetch a user and their files separately (WriteOnlyMapped doesn't support eager loading).
Source code in repositories/user.py
527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 |
|
export_users_to_csv(session)
async
¶
Export all users to CSV string.
Source code in repositories/user.py
559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 |
|
export_users_to_json(session)
async
¶
Export all users to JSON string.
Source code in repositories/user.py
601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 |
|
import_users_from_dicts(session, user_dicts)
async
¶
Bulk import users from a list of dicts. Raises: Exception: On DB commit failure.
Source code in repositories/user.py
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 |
|
deactivate_user(session, user_id)
async
¶
Deactivate a user (set is_active=False). Raises: Exception: On DB commit failure.
Source code in repositories/user.py
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 |
|
reactivate_user(session, user_id)
async
¶
Reactivate a user (set is_active=True). Raises: Exception: On DB commit failure.
Source code in repositories/user.py
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 |
|
update_last_login(session, user_id, login_time=None)
async
¶
Update the last_login_at timestamp for a user. Raises: Exception: On DB commit failure.
Source code in repositories/user.py
677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 |
|
anonymize_user(session, user_id)
async
¶
Anonymize user data for privacy/GDPR (irreversibly removes PII, disables account). Raises: Exception: On DB commit failure.
Source code in repositories/user.py
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 |
|
user_signups_per_month(session, year)
async
¶
Return a dict of {month: signup_count} for the given year (1-12).
Source code in repositories/user.py
722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 |
|
repositories.file
¶
get_file_by_filename(session, filename)
async
¶
Source code in repositories/file.py
12 13 14 15 16 17 18 |
|
create_file(session, filename, content_type, user_id, size=0)
async
¶
Create a new File record in the database. Raises: ValidationError: If filename is empty. Exception: If the database operation fails.
Source code in repositories/file.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
|
delete_file(session, filename)
async
¶
Delete a file by filename. Returns: bool: True if file was deleted, False if not found. Raises: Exception: If the database operation fails.
Source code in repositories/file.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
|
bulk_delete_files(session, filenames, user_id)
async
¶
Bulk delete files by filenames for a specific user. Returns: tuple[list[str], list[str]]: (successfully_deleted, failed_to_delete) Raises: Exception: If the database operation fails.
Source code in repositories/file.py
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
|
list_files(session, user_id, offset=0, limit=20, q=None, sort='created_at', order='desc', created_after=None, created_before=None)
async
¶
List files for a user with optional filters and pagination. Returns: tuple[list[File], int]: (files, total count) Raises: Exception: If the database operation fails.
Source code in repositories/file.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 |
|
This page is always up to date with the latest code and docstrings.