Spaces:
Sleeping
Sleeping
File size: 47,720 Bytes
da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 603a537 da54a72 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 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 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 93 94 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 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 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 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 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 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 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 543 544 545 546 547 548 549 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 892 893 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 972 973 974 975 976 977 978 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 1063 1064 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 1141 1142 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 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 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 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 | # Skin Disease Detection API β Full Specification
> **Base URL:** `https://alihamzach-skinmodel.hf.space`
> **API Prefix:** `/v1`
> **Model:** EfficientNetB0 (224Γ224, 22 disease classes)
> **Auth:** JWT (access + refresh tokens)
> **Rate Limiting:** IP-based + user-based tiered quotas
> **Database:** PostgreSQL (Neon) via SQLAlchemy async + asyncpg
---
## Table of Contents
1. [Authentication & User Management](#1-authentication--user-management)
2. [Image Scanning & Detection](#2-image-scanning--detection)
3. [Recommendations & Personalization](#3-recommendations--personalization)
4. [Monetization & Subscriptions](#4-monetization--subscriptions)
5. [Database Schema](#5-database-schema)
6. [Rate Limiting Logic](#6-rate-limiting-logic)
7. [Error Handling](#7-error-handling)
8. [Middleware & Configuration](#8-middleware--configuration)
---
## 1. Authentication & User Management
### 1.1 Signup
Creates a new user account with email + password.
```
POST /auth/signup
```
**Request Body:**
```json
{
"email": "user@example.com",
"password": "Str0ng!Pass123",
"full_name": "Jane Doe",
"medical_history": {
"allergies": ["penicillin", "sulfa"],
"chronic_conditions": ["eczema"],
"current_medications": ["cetirizine"]
}
}
```
**Validation Rules:**
- `email`: valid email format, max 255 chars, unique in system
- `password`: min 8 chars, at least 1 uppercase, 1 lowercase, 1 digit, 1 special char
- `full_name`: 1β100 chars, letters/spaces/hyphens only
- `medical_history`: optional JSON object
**Response `201 Created`:**
```json
{
"id": "uuid",
"email": "user@example.com",
"full_name": "Jane Doe",
"is_verified": false,
"created_at": "2026-05-17T10:30:00Z"
}
```
**Error `409 Conflict`:**
```json
{
"detail": "An account with this email already exists."
}
```
**Error `422 Unprocessable Entity`:**
```json
{
"detail": [
{ "loc": ["body", "password"], "msg": "Password must contain at least one uppercase letter" }
]
}
```
---
### 1.2 Login
Authenticates user and returns JWT tokens.
```
POST /auth/login
```
**Request Body:**
```json
{
"email": "user@example.com",
"password": "Str0ng!Pass123"
}
```
**Response `200 OK`:**
```json
{
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"refresh_token": "eyJhbGciOiJIUzI1NiIs...",
"token_type": "bearer",
"expires_in": 3600,
"user": {
"id": "uuid",
"email": "user@example.com",
"full_name": "Jane Doe",
"subscription_plan": "free",
"scans_remaining_today": 5
}
}
```
**Error `401 Unauthorized`:**
```json
{
"detail": "Invalid email or password."
}
```
**Token Specs:**
| Token | Lifetime | Payload |
|-------|----------|---------|
| Access | 1 hour | `sub` (user_id), `exp`, `iat`, `type: "access"` |
| Refresh | 30 days | `sub` (user_id), `exp`, `iat`, `type: "refresh"` |
---
### 1.3 Social Login (OAuth 2.0)
Initiates or completes social login via Google or Facebook.
```
POST /auth/social/{provider}
```
**Path Parameters:**
- `provider`: `"google"` | `"facebook"`
**Request Body:**
```json
{
"access_token": "ya29.a0AfH6SMC..."
}
```
**Server-Side Flow:**
1. Receive OAuth access token from client
2. Verify token with Google/Facebook tokeninfo endpoint
3. Extract email, name, profile photo from provider
4. If email exists β link social account + login
5. If email new β create user with `auth_provider` = provider + `social_id` = provider user ID
**Response `200 OK`** (same shape as login response)
**Error `401 Unauthorized`:**
```json
{
"detail": "Invalid or expired social token."
}
```
---
### 1.4 Forgot Password
Initiates password reset email flow.
```
POST /auth/forgot-password
```
**Request Body:**
```json
{
"email": "user@example.com"
}
```
**Flow:**
1. Validate email exists (silent fail if not β security best practice)
2. Generate cryptographically secure 6-digit code (or UUIDv4 token)
3. Store hashed token in `password_reset_tokens` table with 15-min expiry
4. Send email with reset link/code
**Response `200 OK` (always):**
```json
{
"message": "If an account with that email exists, a password reset link has been sent."
}
```
---
### 1.5 Reset Password
Completes password reset using token from email.
```
POST /auth/reset-password
```
**Request Body:**
```json
{
"token": "a1b2c3d4-e5f6-...",
"new_password": "NewStr0ng!Pass456"
}
```
**Validation:**
- Token must exist in DB, not expired, not used
- Token is marked `is_used = true` after successful reset (one-time use)
- Password follows same rules as signup
**Response `200 OK`:**
```json
{
"message": "Password has been reset successfully."
}
```
**Error `400 Bad Request`:**
```json
{
"detail": "Invalid or expired reset token."
}
```
---
### 1.6 Change Password (Authenticated)
```
PUT /auth/change-password
```
**Headers:** `Authorization: Bearer <access_token>`
**Request Body:**
```json
{
"current_password": "OldPass123!",
"new_password": "NewStr0ng!Pass456"
}
```
**Response `200 OK`:**
```json
{
"message": "Password changed successfully."
}
```
**Error `401 Unauthorized`:**
```json
{
"detail": "Current password is incorrect."
}
```
---
### 1.7 Refresh Token
```
POST /auth/refresh
```
**Request Body:**
```json
{
"refresh_token": "eyJhbGciOiJIUzI1NiIs..."
}
```
**Response `200 OK`:**
```json
{
"access_token": "eyJhbGciOiJIUzI1NiIs...",
"expires_in": 3600
}
```
---
### 1.8 Update Profile (Authenticated)
```
PUT /auth/profile
```
**Headers:** `Authorization: Bearer <access_token>`
**Request Body:**
```json
{
"full_name": "Jane Smith",
"profile_photo": "data:image/png;base64,iVBOR...",
"medical_history": {
"allergies": ["penicillin"],
"chronic_conditions": ["eczema", "psoriasis"],
"current_medications": ["diphenhydramine"],
"skin_type": "oily",
"known_sensitivities": ["fragrance", "parabens"]
}
}
```
**Response `200 OK`:**
```json
{
"id": "uuid",
"email": "user@example.com",
"full_name": "Jane Smith",
"profile_photo_url": "https://cdn.skindetect.com/users/uuid/photo.jpg",
"medical_history": { ... },
"updated_at": "2026-05-17T11:00:00Z"
}
```
---
## 2. Image Scanning & Detection
### 2.1 Scan Image
Upload a skin image for AI-based disease detection.
```
POST /scans
```
**Unauthenticated users:** IP-based rate limit of **3 total scans per IP**.
**Authenticated users:** Daily limit based on subscription plan (default: **5/day** for free tier).
**Headers:** `Authorization: Bearer <access_token>` *(optional for unauthenticated)*
**Request Body** (`multipart/form-data`):
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `image` | file | yes | JPEG or PNG, max 10MB, min 224Γ224px |
| `location` | string | no | Lat,lng for geo-recommendations (e.g. `"40.7128,-74.0060"`) |
**Processing Pipeline:**
1. Validate file type and size
2. Check rate limits (IP for unauth, user quota for auth)
3. Upload image to CDN (S3/GCS) with UUID filename
4. Preprocess: resize to 224Γ224, normalize to [0,1]
5. Run model inference β softmax probabilities over 22 classes
6. Apply confidence threshold (default: 15%) to filter low-confidence results
7. Log scan record in database
8. Increment quota counters
9. Return results
**Response `200 OK`:**
```json
{
"items": [
{
"scan_id": "uuid",
"title": "skin_photo.jpg",
"image_url": "https://cdn.skindetect.com/scans/uuid/thumb.jpg",
"primary_detection": {
"disease": "Eczema",
"confidence": 87.32,
"urgency_level": "consult_recommended"
},
"all_results": [
{ "disease": "Eczema", "confidence": 87.32, "severity": "moderate" },
{ "disease": "Psoriasis", "confidence": 8.15 },
{ "disease": "Acne", "confidence": 2.41 }
],
"created_at": "2026-05-17T10:30:00Z"
}
],
"total": 42,
"page": 1,
"page_size": 20,
"total_pages": 3
}
```
**Error `401 Unauthorized`:**
```json
{
"detail": "Authentication required to view scan history."
}
```
---
### 2.3 Get Single Scan Detail (Authenticated)
```
GET /scans/{scan_id}
```
**Headers:** `Authorization: Bearer <access_token>`
**Response `200 OK`:** Full scan result (same shape as scan response)
**Error `404 Not Found`:**
```json
{
"detail": "Scan not found."
}
```
---
### 2.4 Rename Scan (Authenticated)
Updates the title of an existing scan.
```
PATCH /v1/scans/{scan_id}
```
**Headers:** `Authorization: Bearer <access_token>`
**Request Body:**
```json
{
"title": "My updated scan name"
}
```
**Response `200 OK`:**
```json
{
"scan_id": "uuid",
"title": "My updated scan name"
}
```
**Error `404 Not Found`:**
```json
{
"detail": "Scan not found."
}
```
---
### 2.5 Delete Scan (Authenticated)
Permanently deletes a scan record.
```
DELETE /v1/scans/{scan_id}
```
**Headers:** `Authorization: Bearer <access_token>`
**Response `204 No Content`** (no body)
**Error `404 Not Found`:**
```json
{
"detail": "Scan not found."
}
```
---
## 3. Recommendations & Personalization
### 3.1 Dermatologist Recommendations
Returns a list of dermatologists ranked by proximity to the user's IP location.
```
GET /recommendations/dermatologists
```
**Headers:** `Authorization: Bearer <access_token>` *(optional β wider results if authenticated)*
**Query Parameters:**
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `lat` | float | no | IP geo-lookup | Latitude |
| `lng` | float | no | IP geo-lookup | Longitude |
| `radius_km` | int | no | 50 | Search radius |
| `specialization` | string | no | β | Filter by specialty (e.g. "pediatric_dermatology") |
| `page` | int | no | 1 | β |
| `page_size` | int | no | 20 | β |
**Response `200 OK`:**
```json
{
"items": [
{
"id": "uuid",
"name": "Dr. Sarah Johnson",
"specialization": ["general_dermatology", "pediatric_dermatology"],
"address": "123 Medical Plaza, Suite 200, New York, NY 10001",
"phone": "+1-212-555-0198",
"email": "dr.johnson@dermclinic.com",
"website": "https://dermclinic.com/dr-johnson",
"rating": 4.8,
"review_count": 124,
"distance_km": 2.3,
"coordinates": { "lat": 40.7580, "lng": -73.9855 },
"available_slots": ["2026-05-18T09:00", "2026-05-18T10:30"],
"insurance_accepted": ["Aetna", "Cigna", "UnitedHealthcare"]
}
],
"user_location": { "lat": 40.7484, "lng": -73.9967, "source": "ip" },
"total": 12,
"page": 1,
"page_size": 20
}
```
**Location Resolution Priority:**
1. Explicit `lat`/`lng` query params (highest priority)
2. User's saved location from profile (if authenticated)
3. IP geolocation lookup (MaxMind GeoIP or similar)
---
### 3.2 Skin Care Product Recommendations
Returns product/medicine recommendations. May include affiliate links.
```
GET /recommendations/products
```
**Headers:** `Authorization: Bearer <access_token>` *(optional)*
**Query Parameters:**
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `condition` | string | no | β | Target condition (e.g. "Eczema") |
| `product_type` | string | no | β | `medicine` \| `moisturizer` \| `cleanser` \| `sunscreen` \| `treatment` |
| `lat` | float | no | IP geo | For pharmacy availability |
| `lng` | float | no | IP geo | β |
| `page` | int | no | 1 | β |
| `page_size` | int | no | 20 | β |
**Response `200 OK`:**
```json
{
"items": [
{
"id": "uuid",
"name": "Cetaphil Moisturizing Cream",
"brand": "Cetaphil",
"category": "moisturizer",
"type": "over_the_counter",
"description": "Non-greasy, fragrance-free moisturizer for sensitive skin.",
"key_ingredients": ["glycerin", "petrolatum", "dimethicone"],
"recommended_for": ["Eczema", "Psoriasis", "dry_skin"],
"average_rating": 4.6,
"price": {
"amount": 14.99,
"currency": "USD",
"retailer": "Walmart"
},
"affiliate_link": "https://www.amazon.com/dp/B001B4...?tag=skindetect-20",
"image_url": "https://cdn.skindetect.com/products/uuid/image.jpg",
"medical_rating": 4.5,
"side_effects": ["rare: mild irritation"],
"prescription_required": false
}
],
"total": 8,
"page": 1,
"page_size": 20
}
```
**Affiliate Link Strategy:**
- Append tracking tag `?tag=skindetect-{source}-{user_id_hash}` to all product links
- Link to Amazon Pharmacy, Walmart, CVS, Walgreens affiliate programs
- Track clicks via redirect service (`/r/{product_id}`) for analytics
---
### 3.3 Clinic Recommendations
Returns nearby skin clinics/hospitals.
```
GET /recommendations/clinics
```
**Headers:** `Authorization: Bearer <access_token>` *(optional)*
**Query Parameters:** (same location params as dermatologists)
**Response `200 OK`:**
```json
{
"items": [
{
"id": "uuid",
"name": "Manhattan Dermatology Center",
"type": "clinic",
"address": "500 Fifth Avenue, Floor 15, New York, NY 10110",
"phone": "+1-212-555-0246",
"distance_km": 0.8,
"rating": 4.5,
"review_count": 89,
"services": ["general_dermatology", "mohs_surgery", "cosmetic"],
"open_hours": {
"monday": "08:00-18:00",
"tuesday": "08:00-18:00",
"wednesday": "08:00-20:00",
"thursday": "08:00-18:00",
"friday": "08:00-16:00",
"saturday": "09:00-13:00",
"sunday": "closed"
},
"accepts_insurance": true,
"walkins_accepted": false,
"coordinates": { "lat": 40.7527, "lng": -73.9822 }
}
],
"total": 5,
"page": 1,
"page_size": 20
}
```
---
## 4. Monetization & Subscriptions
### 4.1 List Subscription Plans
```
GET /subscriptions/plans
```
**Response `200 OK`:**
```json
{
"plans": [
{
"id": "plan_free",
"name": "Free",
"price_cents": 0,
"currency": "USD",
"billing_interval": "month",
"features": {
"daily_scans": 5,
"scan_history_days": 30,
"detailed_results": true,
"product_recommendations": true,
"dermatologist_referrals": false,
"priority_support": false,
"data_export": false
}
},
{
"id": "plan_basic",
"name": "Basic",
"price_cents": 499,
"currency": "USD",
"billing_interval": "month",
"features": {
"daily_scans": 20,
"scan_history_days": 365,
"detailed_results": true,
"product_recommendations": true,
"dermatologist_referrals": true,
"priority_support": false,
"data_export": false
},
"stripe_price_id": "price_1ABC2Def3Ghi4Jkl"
},
{
"id": "plan_premium",
"name": "Premium",
"price_cents": 999,
"currency": "USD",
"billing_interval": "month",
"features": {
"daily_scans": 100,
"scan_history_days": null,
"detailed_results": true,
"product_recommendations": true,
"dermatologist_referrals": true,
"priority_support": true,
"data_export": true
},
"stripe_price_id": "price_5Mno6Pqr7Stu8Vwx"
}
]
}
```
---
### 4.2 Create Checkout Session
Initiates Stripe Checkout Session for subscription purchase.
```
POST /subscriptions/create-checkout-session
```
**Headers:** `Authorization: Bearer <access_token>`
**Request Body:**
```json
{
"plan_id": "plan_basic",
"success_url": "https://skindetect.com/subscriptions/success?session_id={CHECKOUT_SESSION_ID}",
"cancel_url": "https://skindetect.com/subscriptions/cancel"
}
```
**Response `200 OK`:**
```json
{
"checkout_url": "https://checkout.stripe.com/c/pay/cs_test_..."
}
```
**Error `400 Bad Request`:**
```json
{
"detail": "Invalid plan ID."
}
```
---
### 4.3 Stripe Webhook
Receives Stripe webhook events for subscription lifecycle management.
```
POST /subscriptions/webhook
```
**Headers:** `Stripe-Signature: <webhook_signature>`
**No auth** (verified via Stripe signature).
**Events Handled:**
| Event | Action |
|-------|--------|
| `checkout.session.completed` | Activate subscription, set end_date |
| `invoice.paid` | Renew subscription period |
| `invoice.payment_failed` | Send payment failure email, mark subscription past_due |
| `customer.subscription.updated` | Sync plan changes |
| `customer.subscription.deleted` | Cancel subscription, revert to free plan |
**Response `200 OK`:**
```json
{
"received": true
}
```
---
### 4.4 Get My Subscription
Returns the authenticated user's current subscription details.
```
GET /subscriptions/my
```
**Headers:** `Authorization: Bearer <access_token>`
**Response `200 OK`:**
```json
{
"user_id": "uuid",
"plan": {
"id": "plan_basic",
"name": "Basic",
"daily_scans": 20,
"features": { ... }
},
"status": "active",
"current_period_start": "2026-05-01T00:00:00Z",
"current_period_end": "2026-06-01T00:00:00Z",
"cancel_at_period_end": false,
"scans_used_today": 3,
"scans_remaining_today": 17,
"stripe_subscription_id": "sub_1ABC2Def3Ghi4Jkl"
}
```
---
### 4.5 Cancel Subscription
```
POST /subscriptions/cancel
```
**Headers:** `Authorization: Bearer <access_token>`
**Response `200 OK`:**
```json
{
"message": "Subscription will be cancelled at the end of the current billing period.",
"cancel_at_period_end": true,
"current_period_end": "2026-06-01T00:00:00Z"
}
```
---
## 5. Database Schema
### 5.1 Entity-Relationship Diagram (Textual)
```
users ββ1:1ββ user_subscriptions ββN:1ββ subscription_plans
users ββ1:Nββ scan_records
users ββ1:Nββ scan_daily_usage
users ββ1:Nββ password_reset_tokens
users ββ1:Nββ payment_transactions
scan_records ββN:1ββ users (nullable)
ip_scan_tracking (standalone, keyed by IP)
```
### 5.2 Table Definitions
```sql
-- ============================================================
-- USERS
-- ============================================================
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
CREATE TABLE users (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
email VARCHAR(255) UNIQUE NOT NULL,
password_hash VARCHAR(255),
full_name VARCHAR(100) NOT NULL,
profile_photo_url TEXT,
medical_history JSONB DEFAULT '{}',
auth_provider VARCHAR(20) DEFAULT 'email'
CHECK (auth_provider IN ('email', 'google', 'facebook')),
social_id VARCHAR(255),
is_verified BOOLEAN DEFAULT false,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_users_email ON users(email);
CREATE INDEX idx_users_social ON users(auth_provider, social_id);
-- ============================================================
-- SUBSCRIPTION PLANS (seed data)
-- ============================================================
CREATE TABLE subscription_plans (
id VARCHAR(50) PRIMARY KEY, -- 'plan_free', 'plan_basic', 'plan_premium'
name VARCHAR(100) NOT NULL,
price_cents INTEGER NOT NULL,
currency VARCHAR(3) DEFAULT 'USD',
billing_interval VARCHAR(20) DEFAULT 'month',
daily_scan_limit INTEGER NOT NULL,
features JSONB NOT NULL DEFAULT '{}',
stripe_price_id VARCHAR(255),
is_active BOOLEAN DEFAULT true,
sort_order INTEGER DEFAULT 0
);
-- Seed data
INSERT INTO subscription_plans (id, name, price_cents, daily_scan_limit, features, sort_order) VALUES
('plan_free', 'Free', 0, 5, '{"scan_history_days": 30, "detailed_results": true, "product_recommendations": true, "dermatologist_referrals": false, "priority_support": false, "data_export": false}', 1),
('plan_basic', 'Basic', 499, 20, '{"scan_history_days": 365, "detailed_results": true, "product_recommendations": true, "dermatologist_referrals": true, "priority_support": false, "data_export": false}', 2),
('plan_premium', 'Premium', 999, 100,'{"scan_history_days": null, "detailed_results": true, "product_recommendations": true, "dermatologist_referrals": true, "priority_support": true, "data_export": true}', 3);
-- ============================================================
-- USER SUBSCRIPTIONS
-- ============================================================
CREATE TABLE user_subscriptions (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
plan_id VARCHAR(50) NOT NULL REFERENCES subscription_plans(id),
status VARCHAR(20) NOT NULL DEFAULT 'active'
CHECK (status IN ('active', 'past_due', 'canceled', 'expired')),
current_period_start TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
current_period_end TIMESTAMP WITH TIME ZONE,
cancel_at_period_end BOOLEAN DEFAULT false,
stripe_subscription_id VARCHAR(255),
stripe_customer_id VARCHAR(255),
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
UNIQUE(user_id) -- one active subscription per user
);
CREATE INDEX idx_user_sub_status ON user_subscriptions(user_id, status);
-- ============================================================
-- SCAN RECORDS
-- ============================================================
CREATE TABLE scan_records (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID REFERENCES users(id) ON DELETE SET NULL,
ip_address VARCHAR(45) NOT NULL,
image_url TEXT NOT NULL,
thumbnail_url TEXT,
original_filename VARCHAR(255),
image_size_bytes INTEGER,
processing_time_ms INTEGER,
results JSONB NOT NULL,
primary_detection JSONB,
detected_conditions TEXT[],
model_version VARCHAR(50),
is_flagged BOOLEAN DEFAULT false,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_scan_user ON scan_records(user_id, created_at DESC);
CREATE INDEX idx_scan_ip ON scan_records(ip_address, created_at DESC);
CREATE INDEX idx_scan_conditions ON scan_records USING GIN(detected_conditions);
-- ============================================================
-- SCAN DAILY USAGE (per-user quota tracking)
-- ============================================================
CREATE TABLE scan_daily_usage (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
scan_date DATE NOT NULL DEFAULT CURRENT_DATE,
scan_count INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (user_id, scan_date)
);
-- ============================================================
-- IP SCAN TRACKING (anonymous rate limiting)
-- ============================================================
CREATE TABLE ip_scan_tracking (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
ip_address VARCHAR(45) UNIQUE NOT NULL,
scan_count INTEGER NOT NULL DEFAULT 0,
first_scan_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
last_scan_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
-- ============================================================
-- PASSWORD RESET TOKENS
-- ============================================================
CREATE TABLE password_reset_tokens (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
token_hash VARCHAR(255) NOT NULL,
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
is_used BOOLEAN DEFAULT false,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_reset_token ON password_reset_tokens(user_id, is_used);
-- ============================================================
-- PAYMENT TRANSACTIONS
-- ============================================================
CREATE TABLE payment_transactions (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
amount_cents INTEGER NOT NULL,
currency VARCHAR(3) DEFAULT 'USD',
payment_provider VARCHAR(50) DEFAULT 'stripe',
payment_provider_id VARCHAR(255),
subscription_id UUID REFERENCES user_subscriptions(id),
status VARCHAR(20) NOT NULL
CHECK (status IN ('pending', 'completed', 'failed', 'refunded')),
metadata JSONB DEFAULT '{}',
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_payment_user ON payment_transactions(user_id, created_at DESC);
-- ============================================================
-- DOCTORS / CLINICS / PRODUCTS (for recommendations)
-- ============================================================
CREATE TABLE doctors (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name VARCHAR(200) NOT NULL,
specializations TEXT[],
address TEXT,
phone VARCHAR(50),
email VARCHAR(255),
website TEXT,
rating DECIMAL(2,1) DEFAULT 0.0,
review_count INTEGER DEFAULT 0,
coordinates POINT,
insurance_accepted TEXT[],
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_doctor_location ON doctors USING GIST(coordinates);
CREATE TABLE clinics (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name VARCHAR(200) NOT NULL,
type VARCHAR(50) DEFAULT 'clinic',
address TEXT,
phone VARCHAR(50),
rating DECIMAL(2,1) DEFAULT 0.0,
review_count INTEGER DEFAULT 0,
services TEXT[],
open_hours JSONB,
accepts_insurance BOOLEAN,
walkins_accepted BOOLEAN,
coordinates POINT,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_clinic_location ON clinics USING GIST(coordinates);
CREATE TABLE products (
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
name VARCHAR(200) NOT NULL,
brand VARCHAR(100),
category VARCHAR(50),
type VARCHAR(50) CHECK (type IN ('over_the_counter', 'prescription')),
description TEXT,
key_ingredients TEXT[],
recommended_for TEXT[],
average_rating DECIMAL(2,1),
price_amount DECIMAL(10,2),
price_currency VARCHAR(3) DEFAULT 'USD',
retailer VARCHAR(100),
affiliate_link TEXT,
image_url TEXT,
prescription_required BOOLEAN DEFAULT false,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW()
);
CREATE INDEX idx_product_condition ON products USING GIN(recommended_for);
```
---
## 6. Rate Limiting Logic
### 6.1 Architecture Overview
```
βββββββββββββββββββ
β Client Request β
ββββββββββ¬βββββββββ
β
ββββββββββΌβββββββββ
β Rate Limit β
β Middleware β
ββββββββββ¬βββββββββ
β
ββββββββββββββββΌβββββββββββββββ
β β
βββββββββββΌββββββββββ ββββββββββββΌβββββββββββ
β Has valid JWT? β β No JWT / Invalid β
β => User-based β β => IP-based β
β rate limiting β β rate limiting β
βββββββββββ¬βββββββββββ ββββββββββββ¬βββββββββββ
β β
βββββββββββΌββββββββββ ββββββββββββΌβββββββββββ
β Check scan_daily β β Check ip_scan_track β
β _usage table β β _ing table β
β WHERE user_id=X β β WHERE ip=X β
β AND date=TODAY β β β
βββββββββββ¬βββββββββββ ββββββββββββ¬βββββββββββ
β β
β ββββββββββββββββββββββββ
β β
βββββΌβββββββΌββββ
β Under limit? ββββNoβββ 429 Too Many Requests
βββββ¬βββββββ¬ββββ
βYes βYes
β β
βββββββββββΌβ ββββΌβββββββββ
β Incrementβ β Proceed β
β counter β β to scan β
ββββββββββββ βββββββββββββ
```
### 6.2 Rate Limit Rules
| Scope | Limit | Window | Storage | Reset |
|-------|-------|--------|---------|-------|
| Anonymous (per IP) | 3 scans total | Lifetime (per IP) | `ip_scan_tracking` table | Never (manual reset) |
| Free tier (per user) | 5 scans | Daily (UTC) | `scan_daily_usage` table | Midnight UTC |
| Basic plan (per user) | 20 scans | Daily (UTC) | `scan_daily_usage` table | Midnight UTC |
| Premium plan (per user) | 100 scans | Daily (UTC) | `scan_daily_usage` table | Midnight UTC |
### 6.3 Quota Check Algorithm (Pseudocode)
```python
async def check_scan_quota(request: Request, user: User | None) -> QuotaResult:
if user:
# ββ Authenticated user ββββββββββββββββββββββββββββββ
plan = await get_user_plan(user.id) # default: free plan
daily_limit = plan.daily_scan_limit
today = date.today()
usage = await ScanDailyUsage.objects.get_or_create(
user_id=user.id, scan_date=today,
defaults={"scan_count": 0}
)
if usage.scan_count >= daily_limit:
raise HTTPException(
status_code=429,
detail={
"message": "Daily scan limit reached.",
"limit": daily_limit,
"plan": plan.name,
"reset_at": f"{today + timedelta(days=1)}T00:00:00Z",
"upgrade_url": "/subscriptions/plans"
}
)
usage.scan_count += 1
await usage.save()
return QuotaResult(remaining=daily_limit - usage.scan_count)
else:
# ββ Anonymous user βββββββββββββββββββββββββββββββββββ
ip = get_client_ip(request)
ANON_LIMIT = 3
tracking = await ip_scan_tracking.objects.get_or_create(
ip_address=ip,
defaults={"scan_count": 0, "first_scan_at": now()}
)
if tracking.scan_count >= ANON_LIMIT:
raise HTTPException(
status_code=429,
detail={
"message": "Anonymous scan limit reached (3 scans). Sign up to continue.",
"limit": ANON_LIMIT,
"reset_at": None # never resets for anonymous
}
)
tracking.scan_count += 1
tracking.last_scan_at = now()
await tracking.save()
return QuotaResult(remaining=ANON_LIMIT - tracking.scan_count)
```
### 6.4 IP Address Detection
```python
def get_client_ip(request: Request) -> str:
# Priority: X-Forwarded-For > X-Real-IP > direct remote
forwarded = request.headers.get("X-Forwarded-For")
if forwarded:
return forwarded.split(",")[0].strip()
real_ip = request.headers.get("X-Real-IP")
if real_ip:
return real_ip
return request.client.host
```
### 6.5 IP Geolocation (for Recommendations)
```python
# Use MaxMind GeoLite2 database
from geoip2.database import Reader
geo_reader = Reader("data/GeoLite2-City.mmdb")
async def get_location_from_ip(ip: str) -> GeoLocation:
if ip in ("127.0.0.1", "::1", "localhost"):
return GeoLocation(lat=40.7128, lng=-74.0060) # default fallback
response = geo_reader.city(ip)
return GeoLocation(
lat=response.location.latitude,
lng=response.location.longitude,
city=response.city.name,
country=response.country.name
)
```
---
## 7. Error Handling
### 7.1 Global Error Schema
All error responses follow this structure:
```json
{
"detail": "Human-readable error message.",
"code": "ERROR_CODE",
"timestamp": "2026-05-17T10:30:00Z",
"path": "/v1/scans",
"extra": {}
}
```
### 7.2 Standard Error Codes
| HTTP Code | Code String | When |
|-----------|-------------|------|
| 400 | `VALIDATION_ERROR` | Invalid input (Pydantic validation) |
| 400 | `INVALID_IMAGE` | Bad image format/dimensions/size |
| 401 | `UNAUTHORIZED` | Missing/invalid/expired JWT |
| 403 | `FORBIDDEN` | Valid JWT but insufficient permissions |
| 404 | `NOT_FOUND` | Resource doesn't exist |
| 409 | `CONFLICT` | Duplicate email, etc. |
| 422 | `UNPROCESSABLE_ENTITY` | Request body fails schema validation |
| 429 | `RATE_LIMIT_EXCEEDED` | Quota exceeded |
| 500 | `INTERNAL_ERROR` | Unexpected server error |
| 502 | `AI_MODEL_ERROR` | Model inference failure |
| 503 | `SERVICE_UNAVAILABLE` | Model not loaded / maintenance |
### 7.3 FastAPI Exception Handler Setup
```python
@app.exception_handler(HTTPException)
async def http_exception_handler(request, exc):
return JSONResponse(
status_code=exc.status_code,
content={
"detail": exc.detail,
"code": ERROR_CODE_MAP.get(exc.status_code, "UNKNOWN"),
"timestamp": datetime.utcnow().isoformat() + "Z",
"path": request.url.path,
}
)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request, exc):
return JSONResponse(
status_code=422,
content={
"detail": exc.errors(),
"code": "VALIDATION_ERROR",
"timestamp": datetime.utcnow().isoformat() + "Z",
"path": request.url.path,
}
)
```
---
## 8. Middleware & Configuration
### 8.1 CORS Configuration
```python
origins = [
"https://skindetect.com",
"https://app.skindetect.com",
"https://admin.skindetect.com",
"http://localhost:3000", # dev
"http://localhost:5173", # vite dev
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "X-Request-ID"],
expose_headers=["X-RateLimit-Remaining", "X-RateLimit-Reset"],
max_age=600,
)
```
### 8.2 Audit Logging Middleware
```python
@app.middleware("http")
async def audit_log_middleware(request: Request, call_next):
start_time = time.perf_counter()
request_id = str(uuid4())
request.state.request_id = request_id
response = await call_next(request)
elapsed = (time.perf_counter() - start_time) * 1000
logger.info(
"audit_log",
extra={
"request_id": request_id,
"method": request.method,
"path": request.url.path,
"status_code": response.status_code,
"elapsed_ms": round(elapsed, 2),
"ip": get_client_ip(request),
"user_agent": request.headers.get("user-agent"),
"user_id": getattr(request.state, "user_id", None),
}
)
return response
```
### 8.3 Security Headers Middleware
```python
@app.middleware("http")
async def security_headers(request: Request, call_next):
response = await call_next(request)
response.headers["X-Content-Type-Options"] = "nosniff"
response.headers["X-Frame-Options"] = "DENY"
response.headers["X-XSS-Protection"] = "1; mode=block"
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
response.headers["Cache-Control"] = "no-store"
return response
```
### 8.4 Rate Limit Response Headers
Every scan response includes these headers:
```
X-RateLimit-Limit: 5 # Total daily limit
X-RateLimit-Remaining: 3 # Remaining scans today
X-RateLimit-Reset: 1715904000 # Unix timestamp of reset (midnight UTC)
```
---
## 9. Complete API Route Table
| Method | Route | Auth | Rate Limited | Description |
|--------|-------|------|-------------|-------------|
| POST | `/auth/signup` | No | No | Create account |
| POST | `/auth/login` | No | 10/min per IP | Login |
| POST | `/auth/social/{provider}` | No | 10/min per IP | Social login |
| POST | `/auth/forgot-password` | No | 3/hr per email | Request reset |
| POST | `/auth/reset-password` | No | 5/hr per IP | Complete reset |
| PUT | `/auth/change-password` | Yes | No | Change password |
| POST | `/auth/refresh` | No | No | Refresh JWT |
| PUT | `/auth/profile` | Yes | No | Update profile |
| POST | `/scans` | Optional | Yes (IP/user) | Scan image |
| GET | `/scans` | Yes | 60/min | Scan history |
| GET | `/scans/{id}` | Yes | 60/min | Scan detail |
| PATCH | `/scans/{id}` | Yes | 60/min | Rename scan |
| DELETE | `/scans/{id}` | Yes | 60/min | Delete scan |
| GET | `/recommendations/dermatologists` | Optional | 30/min | Find doctors |
| GET | `/recommendations/products` | Optional | 30/min | Find products |
| GET | `/recommendations/clinics` | Optional | 30/min | Find clinics |
| GET | `/subscriptions/plans` | No | No | List plans |
| POST | `/subscriptions/create-checkout-session` | Yes | 5/min | Start checkout |
| POST | `/subscriptions/webhook` | No (sig) | No | Stripe webhook |
| GET | `/subscriptions/my` | Yes | 30/min | My subscription |
| POST | `/subscriptions/cancel` | Yes | 5/min | Cancel subscription |
| GET | `/health` | No | No | Health check |
---
## 10. Environment Variables
```bash
# ββ App ββββββββββββββββββββββββββββββββββββββββββββββ
APP_ENV=production
APP_SECRET_KEY=<random-64-char-hex>
APP_DEBUG=false
API_PREFIX=/v1
# ββ Database ββββββββββββββββββββββββββββββββββββββββββ
DATABASE_URL=postgresql+asyncpg://user:pass@localhost:5432/skindetect
# ββ JWT ββββββββββββββββββββββββββββββββββββββββββββββ
JWT_ACCESS_SECRET=<random-64-char-hex>
JWT_REFRESH_SECRET=<different-random-64-char-hex>
JWT_ACCESS_EXPIRE_MINUTES=60
JWT_REFRESH_EXPIRE_DAYS=30
JWT_ALGORITHM=HS256
# ββ AI Model βββββββββββββββββββββββββββββββββββββββββ
MODEL_PATH=best_skin_model_3.keras
CLASS_NAMES_PATH=class_names.json
MODEL_INPUT_SIZE=224
CONFIDENCE_THRESHOLD=15.0
# ββ Storage (CDN) ββββββββββββββββββββββββββββββββββββ
CDN_PROVIDER=s3
AWS_ACCESS_KEY_ID=...
AWS_SECRET_ACCESS_KEY=...
AWS_S3_BUCKET=skindetect-scans
AWS_REGION=us-east-1
CDN_BASE_URL=https://cdn.skindetect.com
# ββ OAuth ββββββββββββββββββββββββββββββββββββββββββββ
GOOGLE_CLIENT_ID=...
GOOGLE_CLIENT_SECRET=...
FACEBOOK_APP_ID=...
FACEBOOK_APP_SECRET=...
# ββ Stripe βββββββββββββββββββββββββββββββββββββββββββ
STRIPE_SECRET_KEY=sk_live_...
STRIPE_WEBHOOK_SECRET=whsec_...
STRIPE_PRICE_FREE=price_1...
STRIPE_PRICE_BASIC=price_2...
STRIPE_PRICE_PREMIUM=price_3...
# ββ Rate Limiting ββββββββββββββββββββββββββββββββββββ
ANONYMOUS_SCAN_LIMIT=3
FREE_TIER_DAILY_SCANS=5
BASIC_PLAN_DAILY_SCANS=20
PREMIUM_PLAN_DAILY_SCANS=100
# ββ Email ββββββββββββββββββββββββββββββββββββββββββββ
SMTP_HOST=smtp.sendgrid.net
SMTP_PORT=587
SMTP_USER=apikey
SMTP_PASSWORD=...
FROM_EMAIL=noreply@skindetect.com
# ββ GeoIP ββββββββββββββββββββββββββββββββββββββββββββ
GEOIP_DB_PATH=data/GeoLite2-City.mmdb
# ββ Affiliate ββββββββββββββββββββββββββββββββββββββββ
AMAZON_AFFILIATE_TAG=skindetect-20
WALMART_AFFILIATE_TAG=skindetect-20
CVS_AFFILIATE_TAG=skindetect-20
```
---
## 11. Pydantic Model Definitions
```python
# ββ Schemas ββββββββββββββββββββββββββββββββββββββββββββββ
class SignupRequest(BaseModel):
email: EmailStr
password: str = Field(..., min_length=8, max_length=128)
full_name: str = Field(..., min_length=1, max_length=100, pattern=r"^[a-zA-Z\s\-]+$")
medical_history: Optional[dict] = None
class LoginRequest(BaseModel):
email: EmailStr
password: str
class SocialLoginRequest(BaseModel):
access_token: str
class ForgotPasswordRequest(BaseModel):
email: EmailStr
class ResetPasswordRequest(BaseModel):
token: str
new_password: str = Field(..., min_length=8, max_length=128)
class ChangePasswordRequest(BaseModel):
current_password: str
new_password: str = Field(..., min_length=8, max_length=128)
class RefreshTokenRequest(BaseModel):
refresh_token: str
class UpdateProfileRequest(BaseModel):
full_name: Optional[str] = Field(None, min_length=1, max_length=100)
profile_photo: Optional[str] = None # base64
medical_history: Optional[dict] = None
class ScanResponse(BaseModel):
scan_id: str
image_url: str
results: list[DiseaseResult]
primary_detection: PrimaryDetection
processing_time_ms: int
disclaimer: str
quota_remaining: int
class DiseaseResult(BaseModel):
disease: str
scientific_name: Optional[str] = None
confidence: float # 0β100
severity: Optional[str] = None
description: Optional[str] = None
common_symptoms: list[str] = []
urgency_level: str # low | consult_recommended | urgent | emergency
class PrimaryDetection(BaseModel):
disease: str
confidence: float
severity: Optional[str] = None
urgency_level: str
class PaginatedResponse(BaseModel, Generic[T]):
items: list[T]
total: int
page: int
page_size: int
total_pages: int
class TokenResponse(BaseModel):
access_token: str
refresh_token: str
token_type: str = "bearer"
expires_in: int
user: UserSummary
class UserSummary(BaseModel):
id: str
email: str
full_name: str
subscription_plan: str
scans_remaining_today: int
class ErrorResponse(BaseModel):
detail: str
code: str
timestamp: str
path: str
extra: dict = {}
```
---
## 12. File Structure (Recommended)
```
app/
βββ main.py # FastAPI app creation, middleware, exception handlers
βββ config.py # Settings from env vars (pydantic-settings)
βββ database.py # SQLAlchemy async engine + session
βββ models/ # SQLAlchemy ORM models
β βββ __init__.py
β βββ user.py
β βββ scan.py
β βββ subscription.py
β βββ recommendation.py
βββ schemas/ # Pydantic request/response schemas
β βββ __init__.py
β βββ auth.py
β βββ user.py
β βββ scan.py
β βββ subscription.py
β βββ recommendation.py
βββ api/
β βββ __init__.py
β βββ deps.py # Dependency injection (get_db, get_current_user, etc.)
β βββ v1/
β βββ __init__.py
β βββ auth.py # /auth/* routes
β βββ users.py # /auth/profile route
β βββ scans.py # /scans/* routes
β βββ recommendations.py # /recommendations/* routes
β βββ subscriptions.py # /subscriptions/* routes
β βββ payments.py # payment webhook
βββ core/
β βββ __init__.py
β βββ security.py # JWT encode/decode, password hashing
β βββ rate_limiter.py # Quota check logic
β βββ ip_geo.py # IP geolocation
β βββ logging.py # Logger setup
βββ services/
β βββ __init__.py
β βββ ai_detector.py # Model loading + inference
β βββ payment_gateway.py # Stripe integration
β βββ email_service.py # SendGrid/SMTP
β βββ recommendation_engine.py # Doctor/product/clinic lookup
βββ middleware/
β βββ __init__.py
β βββ rate_limit.py # Rate limit middleware
βββ tests/
βββ __init__.py
βββ conftest.py
βββ test_auth.py
βββ test_scans.py
βββ test_recommendations.py
βββ test_subscriptions.py
```
---
## 13. Security Checklist
- [x] Passwords hashed with bcrypt (β₯12 rounds)
- [x] JWT signed with separate secrets for access/refresh tokens
- [x] Refresh tokens are single-use (rotate on each refresh)
- [x] Rate limiting on auth endpoints (3/hr forgot password, 10/min login)
- [x] CORS restricted to specific origins
- [x] Security headers via middleware
- [x] Stripe webhook verified via signature, not auth token
- [x] Uploaded images scanned for malware (ClamAV)
- [x] Image EXIF data stripped before storage
- [x] Input validation on all endpoints (Pydantic)
- [x] SQL injection prevention (parameterized queries via SQLAlchemy)
- [x] No secrets in code (all via env vars)
- [x] Rate limit headers exposed to clients
- [x] Password reset tokens are one-time-use with short expiry (15 min)
- [x] Silent fail on forgot-password email lookup (don't reveal if email exists)
---
## 14. Performance Considerations
| Concern | Strategy |
|---------|----------|
| Model inference latency | Load model at startup, warm up with dummy input, use async executor |
| Image upload | Upload to CDN (S3/GCS) directly via presigned URL, process async |
| Scan history queries | Composite indexes on (user_id, created_at DESC), GIN on detected_conditions |
| Rate limit counters | Use Redis for production; fallback to DB for simplicity |
| Geo-recommendations | PostGIS for spatial queries, cache results (5-min TTL) |
| Database connections | Async SQLAlchemy with connection pooling (min 5, max 20) |
| CDN | Serve scan thumbnails (256Γ256 WebP) from CDN with 1-year cache |
| Monitoring | Prometheus metrics: scan latency histogram, error rate, quota exhaustion rate |
---
> **Document Version:** 1.0.0
> **Last Updated:** 2026-05-17
> **Author:** FastAPI Backend Architecture Team
|