Spaces:
Running
Running
Commit ·
08919be
1
Parent(s): 55ae875
ok
Browse files- Dockerfile +2 -2
- app/api/server.py +5 -0
- app/api/v1/auth.py +213 -0
- app/api/v1/router.py +2 -1
- app/config.py +8 -0
- app/core/auth/__init__.py +27 -0
- app/core/auth/deps.py +185 -0
- app/core/auth/models.py +100 -0
- app/core/auth/schemas.py +159 -0
- app/services/auth_service.py +369 -4
- requirements.txt +7 -0
- start.sh +4 -0
Dockerfile
CHANGED
|
@@ -38,8 +38,8 @@ COPY --chown=appuser:appuser . .
|
|
| 38 |
|
| 39 |
RUN mkdir -p /app/models && python3 -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='ibm-granite/granite-embedding-small-english-r2', local_dir='/app/models/bge-384')" && chown -R appuser:appuser /app/models
|
| 40 |
|
| 41 |
-
RUN mkdir -p /app/logs && \
|
| 42 |
-
chown -R appuser:appuser /app/logs
|
| 43 |
|
| 44 |
RUN chmod +x /app/start.sh
|
| 45 |
|
|
|
|
| 38 |
|
| 39 |
RUN mkdir -p /app/models && python3 -c "from huggingface_hub import snapshot_download; snapshot_download(repo_id='ibm-granite/granite-embedding-small-english-r2', local_dir='/app/models/bge-384')" && chown -R appuser:appuser /app/models
|
| 40 |
|
| 41 |
+
RUN mkdir -p /app/data /app/logs && \
|
| 42 |
+
chown -R appuser:appuser /app/data /app/logs
|
| 43 |
|
| 44 |
RUN chmod +x /app/start.sh
|
| 45 |
|
app/api/server.py
CHANGED
|
@@ -8,6 +8,7 @@ from fastapi.middleware.cors import CORSMiddleware
|
|
| 8 |
from fastapi.middleware.gzip import GZipMiddleware
|
| 9 |
|
| 10 |
from app.config import get_settings
|
|
|
|
| 11 |
from app.core.database import pool_manager
|
| 12 |
from app.core.logger import get_logger
|
| 13 |
from app.core.redis_client import create_redis_client, close_redis
|
|
@@ -39,6 +40,10 @@ async def _self_ping():
|
|
| 39 |
|
| 40 |
@asynccontextmanager
|
| 41 |
async def lifespan(app: FastAPI):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
_logger.info("Initializing embedding service (loading 384-dim model)...")
|
| 43 |
loop = asyncio.get_running_loop()
|
| 44 |
await loop.run_in_executor(None, _embedding_service.load_model, 384)
|
|
|
|
| 8 |
from fastapi.middleware.gzip import GZipMiddleware
|
| 9 |
|
| 10 |
from app.config import get_settings
|
| 11 |
+
from app.core.auth.deps import init_auth_db
|
| 12 |
from app.core.database import pool_manager
|
| 13 |
from app.core.logger import get_logger
|
| 14 |
from app.core.redis_client import create_redis_client, close_redis
|
|
|
|
| 40 |
|
| 41 |
@asynccontextmanager
|
| 42 |
async def lifespan(app: FastAPI):
|
| 43 |
+
_logger.info("Initializing authentication database...")
|
| 44 |
+
await init_auth_db()
|
| 45 |
+
_logger.info("Authentication database initialized")
|
| 46 |
+
|
| 47 |
_logger.info("Initializing embedding service (loading 384-dim model)...")
|
| 48 |
loop = asyncio.get_running_loop()
|
| 49 |
await loop.run_in_executor(None, _embedding_service.load_model, 384)
|
app/api/v1/auth.py
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Annotated
|
| 4 |
+
|
| 5 |
+
from fastapi import APIRouter, Depends, Request, status
|
| 6 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 7 |
+
|
| 8 |
+
from app.config import get_settings
|
| 9 |
+
from app.core.auth.deps import get_current_user, get_db, get_temp_db_warning, require_application_id
|
| 10 |
+
from app.core.auth.models import RefreshSession, User
|
| 11 |
+
from app.core.auth.schemas import (
|
| 12 |
+
ChangePasswordSchema,
|
| 13 |
+
ForgotPasswordSchema,
|
| 14 |
+
LoginSchema,
|
| 15 |
+
MessageDataResponse,
|
| 16 |
+
ProfileResponse,
|
| 17 |
+
RegisterSchema,
|
| 18 |
+
ResetPasswordSchema,
|
| 19 |
+
SchemaResponse,
|
| 20 |
+
SessionListResponse,
|
| 21 |
+
SessionOut,
|
| 22 |
+
TokenRefreshSchema,
|
| 23 |
+
TokenResponse,
|
| 24 |
+
UpdateProfileSchema,
|
| 25 |
+
UserSchemaField,
|
| 26 |
+
UserSchemaResponse,
|
| 27 |
+
DataResponse,
|
| 28 |
+
)
|
| 29 |
+
from app.services.auth_service import AuthService
|
| 30 |
+
|
| 31 |
+
router = APIRouter(prefix="/auth", tags=["Authentication"])
|
| 32 |
+
_settings = get_settings()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _build(data, warning):
|
| 36 |
+
result = {"success": True, "data": data}
|
| 37 |
+
if _settings.application_id:
|
| 38 |
+
result["application_id"] = _settings.application_id
|
| 39 |
+
if warning:
|
| 40 |
+
result["warning"] = warning
|
| 41 |
+
return result
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@router.post("/register", response_model=ProfileResponse, status_code=status.HTTP_201_CREATED)
|
| 45 |
+
async def register(
|
| 46 |
+
schema: RegisterSchema,
|
| 47 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 48 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 49 |
+
):
|
| 50 |
+
user = await AuthService.register(db, schema)
|
| 51 |
+
warning = get_temp_db_warning()
|
| 52 |
+
return _build(AuthService.user_to_profile(user).model_dump(), warning)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
@router.post("/login", response_model=TokenResponse)
|
| 56 |
+
async def login(
|
| 57 |
+
schema: LoginSchema,
|
| 58 |
+
request: Request,
|
| 59 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 60 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 61 |
+
):
|
| 62 |
+
tokens = await AuthService.login(db, request, schema)
|
| 63 |
+
warning = get_temp_db_warning()
|
| 64 |
+
return _build(tokens.model_dump(), warning)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@router.post("/refresh", response_model=TokenResponse)
|
| 68 |
+
async def refresh_token(
|
| 69 |
+
schema: TokenRefreshSchema,
|
| 70 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 71 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 72 |
+
):
|
| 73 |
+
tokens = await AuthService.refresh(db, schema.refresh_token)
|
| 74 |
+
warning = get_temp_db_warning()
|
| 75 |
+
return _build(tokens.model_dump(), warning)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@router.post("/logout", response_model=MessageDataResponse)
|
| 79 |
+
async def logout(
|
| 80 |
+
schema: TokenRefreshSchema,
|
| 81 |
+
current_user: Annotated[User, Depends(get_current_user)],
|
| 82 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 83 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 84 |
+
):
|
| 85 |
+
await AuthService.logout(db, current_user, schema.refresh_token)
|
| 86 |
+
warning = get_temp_db_warning()
|
| 87 |
+
return _build({"message": "Logged out successfully"}, warning)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@router.post("/logout-all", response_model=MessageDataResponse)
|
| 91 |
+
async def logout_all(
|
| 92 |
+
current_user: Annotated[User, Depends(get_current_user)],
|
| 93 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 94 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 95 |
+
):
|
| 96 |
+
await AuthService.logout_all(db, current_user)
|
| 97 |
+
warning = get_temp_db_warning()
|
| 98 |
+
return _build({"message": "All sessions revoked"}, warning)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@router.post("/forgot-password", response_model=MessageDataResponse)
|
| 102 |
+
async def forgot_password(
|
| 103 |
+
schema: ForgotPasswordSchema,
|
| 104 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 105 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 106 |
+
):
|
| 107 |
+
await AuthService.forgot_password(db, schema)
|
| 108 |
+
warning = get_temp_db_warning()
|
| 109 |
+
return _build({"message": "If that email exists, a password reset link has been sent."}, warning)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@router.post("/reset-password", response_model=MessageDataResponse)
|
| 113 |
+
async def reset_password(
|
| 114 |
+
schema: ResetPasswordSchema,
|
| 115 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 116 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 117 |
+
):
|
| 118 |
+
await AuthService.reset_password(db, schema)
|
| 119 |
+
warning = get_temp_db_warning()
|
| 120 |
+
return _build({"message": "Password reset successfully"}, warning)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
@router.post("/change-password", response_model=MessageDataResponse)
|
| 124 |
+
async def change_password(
|
| 125 |
+
schema: ChangePasswordSchema,
|
| 126 |
+
current_user: Annotated[User, Depends(get_current_user)],
|
| 127 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 128 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 129 |
+
):
|
| 130 |
+
await AuthService.change_password(db, current_user, schema)
|
| 131 |
+
warning = get_temp_db_warning()
|
| 132 |
+
return _build({"message": "Password changed successfully"}, warning)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@router.get("/me", response_model=ProfileResponse)
|
| 136 |
+
async def get_me(
|
| 137 |
+
current_user: Annotated[User, Depends(get_current_user)],
|
| 138 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 139 |
+
):
|
| 140 |
+
warning = get_temp_db_warning()
|
| 141 |
+
return _build(AuthService.user_to_profile(current_user).model_dump(), warning)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
@router.patch("/me", response_model=ProfileResponse)
|
| 145 |
+
async def update_me(
|
| 146 |
+
schema: UpdateProfileSchema,
|
| 147 |
+
current_user: Annotated[User, Depends(get_current_user)],
|
| 148 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 149 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 150 |
+
):
|
| 151 |
+
user = await AuthService.update_profile(db, current_user, schema)
|
| 152 |
+
warning = get_temp_db_warning()
|
| 153 |
+
return _build(AuthService.user_to_profile(user).model_dump(), warning)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
@router.delete("/me", response_model=MessageDataResponse)
|
| 157 |
+
async def delete_me(
|
| 158 |
+
current_user: Annotated[User, Depends(get_current_user)],
|
| 159 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 160 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 161 |
+
):
|
| 162 |
+
await AuthService.soft_delete(db, current_user)
|
| 163 |
+
warning = get_temp_db_warning()
|
| 164 |
+
return _build({"message": "Account deleted successfully"}, warning)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
@router.get("/schema", response_model=SchemaResponse)
|
| 168 |
+
async def get_user_schema(
|
| 169 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 170 |
+
):
|
| 171 |
+
columns = [
|
| 172 |
+
UserSchemaField(field="id", type="string (UUID)", required=True, description="Unique user identifier", constraints="Auto-generated"),
|
| 173 |
+
UserSchemaField(field="email", type="string", required=True, description="User email address", constraints="Unique, max 255 chars"),
|
| 174 |
+
UserSchemaField(field="username", type="string", required=False, description="Unique username", constraints="Unique, 2-50 chars, alphanumeric + underscore"),
|
| 175 |
+
UserSchemaField(field="full_name", type="string", required=False, description="Display name", constraints="Max 100 chars"),
|
| 176 |
+
UserSchemaField(field="password", type="string", required=True, description="User password (write-only)", constraints="Min 8 chars, uppercase, lowercase, digit"),
|
| 177 |
+
UserSchemaField(field="password_hash", type="string", required=True, description="Argon2id password hash (internal)", constraints="Auto-generated"),
|
| 178 |
+
UserSchemaField(field="is_active", type="boolean", required=False, description="Whether the user account is active", constraints="Default: true"),
|
| 179 |
+
UserSchemaField(field="is_verified", type="boolean", required=False, description="Whether the email is verified", constraints="Default: false"),
|
| 180 |
+
UserSchemaField(field="failed_login_attempts", type="integer", required=False, description="Consecutive failed login count", constraints="Default: 0"),
|
| 181 |
+
UserSchemaField(field="locked_until", type="datetime (ISO 8601)", required=False, description="Account lock expiry", constraints="Nullable"),
|
| 182 |
+
UserSchemaField(field="last_login", type="datetime (ISO 8601)", required=False, description="Last successful login timestamp", constraints="Nullable"),
|
| 183 |
+
UserSchemaField(field="password_changed_at", type="datetime (ISO 8601)", required=False, description="Last password change", constraints="Nullable"),
|
| 184 |
+
UserSchemaField(field="created_at", type="datetime (ISO 8601)", required=False, description="Account creation timestamp", constraints="Auto-set"),
|
| 185 |
+
UserSchemaField(field="updated_at", type="datetime (ISO 8601)", required=False, description="Last update timestamp", constraints="Auto-updated"),
|
| 186 |
+
UserSchemaField(field="deleted_at", type="datetime (ISO 8601)", required=False, description="Soft delete timestamp", constraints="Nullable"),
|
| 187 |
+
UserSchemaField(field="roles", type="array[string]", required=False, description="Assigned role names", constraints="Via user_roles association table"),
|
| 188 |
+
]
|
| 189 |
+
warning = get_temp_db_warning()
|
| 190 |
+
return _build(UserSchemaResponse(table_name="users", columns=columns).model_dump(), warning)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@router.get("/sessions", response_model=SessionListResponse)
|
| 194 |
+
async def list_sessions(
|
| 195 |
+
current_user: Annotated[User, Depends(get_current_user)],
|
| 196 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 197 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 198 |
+
):
|
| 199 |
+
sessions = await AuthService.list_sessions(db, current_user)
|
| 200 |
+
warning = get_temp_db_warning()
|
| 201 |
+
return _build([SessionOut.model_validate(s).model_dump() for s in sessions], warning)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
@router.delete("/sessions/{session_id}", response_model=MessageDataResponse)
|
| 205 |
+
async def revoke_session(
|
| 206 |
+
session_id: str,
|
| 207 |
+
current_user: Annotated[User, Depends(get_current_user)],
|
| 208 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 209 |
+
_: Annotated[bool, Depends(require_application_id)],
|
| 210 |
+
):
|
| 211 |
+
await AuthService.revoke_session(db, current_user, session_id)
|
| 212 |
+
warning = get_temp_db_warning()
|
| 213 |
+
return _build({"message": "Session revoked successfully"}, warning)
|
app/api/v1/router.py
CHANGED
|
@@ -2,10 +2,11 @@ from __future__ import annotations
|
|
| 2 |
|
| 3 |
from fastapi import APIRouter
|
| 4 |
|
| 5 |
-
from app.api.v1 import batch, chat, code_executor, convert, database, embeddings, reconcile, scraper, semantic_router, sql_validator, system, token_counter, token_generator, web_search
|
| 6 |
from app.api.verify import router as verify_router
|
| 7 |
|
| 8 |
api_v1_router = APIRouter()
|
|
|
|
| 9 |
api_v1_router.include_router(convert.router, tags=["Convert"])
|
| 10 |
api_v1_router.include_router(batch.router, tags=["Batch"])
|
| 11 |
api_v1_router.include_router(system.router, tags=["System"])
|
|
|
|
| 2 |
|
| 3 |
from fastapi import APIRouter
|
| 4 |
|
| 5 |
+
from app.api.v1 import auth, batch, chat, code_executor, convert, database, embeddings, reconcile, scraper, semantic_router, sql_validator, system, token_counter, token_generator, web_search
|
| 6 |
from app.api.verify import router as verify_router
|
| 7 |
|
| 8 |
api_v1_router = APIRouter()
|
| 9 |
+
api_v1_router.include_router(auth.router, tags=["Authentication"])
|
| 10 |
api_v1_router.include_router(convert.router, tags=["Convert"])
|
| 11 |
api_v1_router.include_router(batch.router, tags=["Batch"])
|
| 12 |
api_v1_router.include_router(system.router, tags=["System"])
|
app/config.py
CHANGED
|
@@ -66,6 +66,14 @@ class Settings(BaseSettings):
|
|
| 66 |
jwt_default_expiry_minutes: int = 30
|
| 67 |
jwt_issuer: str = "all-api-collection"
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
@property
|
| 70 |
def max_upload_mb(self) -> int:
|
| 71 |
return self.max_upload_bytes // (1024 * 1024)
|
|
|
|
| 66 |
jwt_default_expiry_minutes: int = 30
|
| 67 |
jwt_issuer: str = "all-api-collection"
|
| 68 |
|
| 69 |
+
database_url: str = "sqlite+aiosqlite:///data/auth.db"
|
| 70 |
+
access_token_expire_minutes: int = 15
|
| 71 |
+
refresh_token_expire_days: int = 7
|
| 72 |
+
max_login_attempts: int = 5
|
| 73 |
+
lockout_minutes: int = 15
|
| 74 |
+
application_id: str = ""
|
| 75 |
+
admin_password: str = ""
|
| 76 |
+
|
| 77 |
@property
|
| 78 |
def max_upload_mb(self) -> int:
|
| 79 |
return self.max_upload_bytes // (1024 * 1024)
|
app/core/auth/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from app.core.auth.models import (
|
| 4 |
+
Base, Permission, Role, User, RefreshSession,
|
| 5 |
+
user_roles, role_permissions,
|
| 6 |
+
)
|
| 7 |
+
from app.core.auth.schemas import (
|
| 8 |
+
RegisterSchema, LoginSchema, TokenResponse, TokenRefreshSchema,
|
| 9 |
+
UserProfile, UpdateProfileSchema, ChangePasswordSchema,
|
| 10 |
+
ForgotPasswordSchema, ResetPasswordSchema, SessionOut,
|
| 11 |
+
MessageResponse, UserSchemaResponse, UserSchemaField,
|
| 12 |
+
)
|
| 13 |
+
from app.core.auth.deps import (
|
| 14 |
+
get_db, get_current_user, require_permissions,
|
| 15 |
+
get_temp_db_warning, TempDatabaseWarning,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
__all__ = [
|
| 19 |
+
"Base", "Permission", "Role", "User", "RefreshSession",
|
| 20 |
+
"user_roles", "role_permissions",
|
| 21 |
+
"RegisterSchema", "LoginSchema", "TokenResponse", "TokenRefreshSchema",
|
| 22 |
+
"UserProfile", "UpdateProfileSchema", "ChangePasswordSchema",
|
| 23 |
+
"ForgotPasswordSchema", "ResetPasswordSchema", "SessionOut",
|
| 24 |
+
"MessageResponse", "UserSchemaResponse", "UserSchemaField",
|
| 25 |
+
"get_db", "get_current_user", "require_permissions",
|
| 26 |
+
"get_temp_db_warning", "TempDatabaseWarning",
|
| 27 |
+
]
|
app/core/auth/deps.py
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import logging
|
| 4 |
+
from datetime import datetime, timedelta, timezone
|
| 5 |
+
from typing import Annotated, Any, AsyncGenerator, Optional
|
| 6 |
+
|
| 7 |
+
import jwt
|
| 8 |
+
from argon2 import PasswordHasher
|
| 9 |
+
from argon2.exceptions import VerifyMismatchError
|
| 10 |
+
from fastapi import Depends, HTTPException, Request, status
|
| 11 |
+
from sqlalchemy import select
|
| 12 |
+
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
| 13 |
+
|
| 14 |
+
from app.config import get_settings
|
| 15 |
+
from app.core.auth.models import Base, Permission, RefreshSession, Role, User
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger("auth")
|
| 18 |
+
|
| 19 |
+
_settings = get_settings()
|
| 20 |
+
|
| 21 |
+
_is_temp_db = (
|
| 22 |
+
"sqlite" in _settings.database_url
|
| 23 |
+
and "localhost" not in _settings.database_url
|
| 24 |
+
and "postgres" not in _settings.database_url.lower()
|
| 25 |
+
and "mysql" not in _settings.database_url.lower()
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
_raw_url: str = getattr(_settings, "database_url", None) or "sqlite+aiosqlite:///data/auth.db"
|
| 29 |
+
|
| 30 |
+
if "sqlite" in _raw_url and "sqlite+aiosqlite" not in _raw_url:
|
| 31 |
+
_raw_url = _raw_url.replace("sqlite:///", "sqlite+aiosqlite:///")
|
| 32 |
+
|
| 33 |
+
DATABASE_URL: str = _raw_url
|
| 34 |
+
|
| 35 |
+
engine = create_async_engine(DATABASE_URL, echo=False)
|
| 36 |
+
AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
| 37 |
+
|
| 38 |
+
ph = PasswordHasher()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _now() -> datetime:
|
| 42 |
+
return datetime.now(timezone.utc)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TempDatabaseWarning:
|
| 46 |
+
code: str = "TEMP_DATABASE"
|
| 47 |
+
message: str = (
|
| 48 |
+
"No external database configuration was provided. "
|
| 49 |
+
"The service is currently using its built-in SQLite database intended for development and temporary use. "
|
| 50 |
+
"Data stored in this database should not be considered permanent."
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def get_temp_db_warning() -> Optional[dict]:
|
| 55 |
+
if _is_temp_db:
|
| 56 |
+
return {"code": TempDatabaseWarning.code, "message": TempDatabaseWarning.message}
|
| 57 |
+
return None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
async def init_auth_db():
|
| 61 |
+
async with engine.begin() as conn:
|
| 62 |
+
await conn.run_sync(Base.metadata.create_all)
|
| 63 |
+
|
| 64 |
+
async with AsyncSessionLocal() as session:
|
| 65 |
+
result = await session.execute(select(Role).where(Role.name == "SuperAdmin"))
|
| 66 |
+
if not result.scalars().first():
|
| 67 |
+
sa_role = Role(name="SuperAdmin", description="Full system access")
|
| 68 |
+
admin_role = Role(name="Admin", description="Administrative access")
|
| 69 |
+
user_role = Role(name="User", description="Standard user access")
|
| 70 |
+
session.add_all([sa_role, admin_role, user_role])
|
| 71 |
+
|
| 72 |
+
perms = []
|
| 73 |
+
for code, desc in [
|
| 74 |
+
("users:read", "Read users"),
|
| 75 |
+
("users:write", "Modify users"),
|
| 76 |
+
("users:delete", "Delete users"),
|
| 77 |
+
("admin:access", "Access admin panel"),
|
| 78 |
+
]:
|
| 79 |
+
p = Permission(code=code, description=desc)
|
| 80 |
+
perms.append(p)
|
| 81 |
+
session.add(p)
|
| 82 |
+
|
| 83 |
+
sa_role.permissions.extend(perms)
|
| 84 |
+
admin_role.permissions.extend(perms[:-1])
|
| 85 |
+
user_role.permissions.append(perms[0])
|
| 86 |
+
|
| 87 |
+
await session.commit()
|
| 88 |
+
|
| 89 |
+
admin_email = "admin@example.com"
|
| 90 |
+
result = await session.execute(select(User).where(User.email == admin_email))
|
| 91 |
+
if not result.scalars().first():
|
| 92 |
+
admin_password = _settings.admin_password or "Admin123!"
|
| 93 |
+
admin_user = User(
|
| 94 |
+
email=admin_email,
|
| 95 |
+
full_name="System Administrator",
|
| 96 |
+
password_hash=ph.hash(admin_password),
|
| 97 |
+
is_verified=True,
|
| 98 |
+
)
|
| 99 |
+
role_result = await session.execute(select(Role).where(Role.name == "SuperAdmin"))
|
| 100 |
+
admin_role = role_result.scalars().first()
|
| 101 |
+
if admin_role:
|
| 102 |
+
admin_user.roles.append(admin_role)
|
| 103 |
+
session.add(admin_user)
|
| 104 |
+
await session.commit()
|
| 105 |
+
|
| 106 |
+
from app.services.auth_service import AuthService
|
| 107 |
+
await AuthService.cleanup_expired_sessions(session)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
| 111 |
+
async with AsyncSessionLocal() as session:
|
| 112 |
+
try:
|
| 113 |
+
yield session
|
| 114 |
+
finally:
|
| 115 |
+
await session.close()
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
async def get_current_user(
|
| 119 |
+
request: Request,
|
| 120 |
+
db: Annotated[AsyncSession, Depends(get_db)],
|
| 121 |
+
) -> User:
|
| 122 |
+
credentials_exception = HTTPException(
|
| 123 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 124 |
+
detail="Could not validate credentials",
|
| 125 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
auth_header = request.headers.get("Authorization")
|
| 129 |
+
if not auth_header or not auth_header.startswith("Bearer "):
|
| 130 |
+
raise credentials_exception
|
| 131 |
+
|
| 132 |
+
token = auth_header.split(" ", 1)[1]
|
| 133 |
+
|
| 134 |
+
try:
|
| 135 |
+
payload = jwt.decode(token, _settings.jwt_secret_key, algorithms=[_settings.jwt_algorithm])
|
| 136 |
+
user_id: str = payload.get("sub")
|
| 137 |
+
token_type: str = payload.get("type")
|
| 138 |
+
if user_id is None or token_type != "access":
|
| 139 |
+
raise credentials_exception
|
| 140 |
+
except jwt.PyJWTError:
|
| 141 |
+
raise credentials_exception
|
| 142 |
+
|
| 143 |
+
result = await db.execute(select(User).where(User.id == user_id, User.deleted_at.is_(None)))
|
| 144 |
+
user = result.scalars().first()
|
| 145 |
+
if user is None or not user.is_active:
|
| 146 |
+
raise credentials_exception
|
| 147 |
+
return user
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def require_application_id(request: Request):
|
| 151 |
+
app_id = request.headers.get("X-Application-Id")
|
| 152 |
+
expected = _settings.application_id
|
| 153 |
+
if not expected:
|
| 154 |
+
return True
|
| 155 |
+
if not app_id:
|
| 156 |
+
raise HTTPException(
|
| 157 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
| 158 |
+
detail="Missing X-Application-Id header",
|
| 159 |
+
)
|
| 160 |
+
if app_id != expected:
|
| 161 |
+
raise HTTPException(
|
| 162 |
+
status_code=status.HTTP_403_FORBIDDEN,
|
| 163 |
+
detail="Invalid application_id",
|
| 164 |
+
)
|
| 165 |
+
return True
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def require_permissions(*required_perms: str):
|
| 169 |
+
async def permission_checker(
|
| 170 |
+
user: Annotated[User, Depends(get_current_user)],
|
| 171 |
+
) -> User:
|
| 172 |
+
user_perms = set()
|
| 173 |
+
for role in user.roles:
|
| 174 |
+
for perm in role.permissions:
|
| 175 |
+
user_perms.add(perm.code)
|
| 176 |
+
|
| 177 |
+
missing = [p for p in required_perms if p not in user_perms]
|
| 178 |
+
if missing:
|
| 179 |
+
raise HTTPException(
|
| 180 |
+
status_code=status.HTTP_403_FORBIDDEN,
|
| 181 |
+
detail=f"Missing required permissions: {', '.join(missing)}",
|
| 182 |
+
)
|
| 183 |
+
return user
|
| 184 |
+
|
| 185 |
+
return permission_checker
|
app/core/auth/models.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import uuid
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
|
| 6 |
+
from sqlalchemy import (
|
| 7 |
+
Boolean, Column, DateTime, ForeignKey, Integer, String, Text, Table,
|
| 8 |
+
)
|
| 9 |
+
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Base(DeclarativeBase):
|
| 13 |
+
pass
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _utcnow() -> datetime:
|
| 17 |
+
return datetime.now(timezone.utc)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _uuid() -> str:
|
| 21 |
+
return str(uuid.uuid4())
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
user_roles = Table(
|
| 25 |
+
"user_roles",
|
| 26 |
+
Base.metadata,
|
| 27 |
+
Column("user_id", String(36), ForeignKey("users.id", ondelete="CASCADE"), primary_key=True),
|
| 28 |
+
Column("role_id", String(36), ForeignKey("roles.id", ondelete="CASCADE"), primary_key=True),
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
role_permissions = Table(
|
| 32 |
+
"role_permissions",
|
| 33 |
+
Base.metadata,
|
| 34 |
+
Column("role_id", String(36), ForeignKey("roles.id", ondelete="CASCADE"), primary_key=True),
|
| 35 |
+
Column("permission_id", String(36), ForeignKey("permissions.id", ondelete="CASCADE"), primary_key=True),
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Permission(Base):
|
| 40 |
+
__tablename__ = "permissions"
|
| 41 |
+
|
| 42 |
+
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
|
| 43 |
+
code: Mapped[str] = mapped_column(String(100), unique=True, index=True, nullable=False)
|
| 44 |
+
description: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
| 45 |
+
|
| 46 |
+
roles: Mapped[list[Role]] = relationship(secondary=role_permissions, back_populates="permissions", lazy="selectin")
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Role(Base):
|
| 50 |
+
__tablename__ = "roles"
|
| 51 |
+
|
| 52 |
+
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
|
| 53 |
+
name: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
|
| 54 |
+
description: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
| 55 |
+
|
| 56 |
+
users: Mapped[list[User]] = relationship(secondary=user_roles, back_populates="roles", lazy="selectin")
|
| 57 |
+
permissions: Mapped[list[Permission]] = relationship(secondary=role_permissions, back_populates="roles", lazy="selectin")
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class User(Base):
|
| 61 |
+
__tablename__ = "users"
|
| 62 |
+
|
| 63 |
+
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
|
| 64 |
+
email: Mapped[str] = mapped_column(String(255), unique=True, index=True, nullable=False)
|
| 65 |
+
username: Mapped[str | None] = mapped_column(String(50), unique=True, index=True, nullable=True)
|
| 66 |
+
full_name: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
| 67 |
+
password_hash: Mapped[str] = mapped_column(Text, nullable=False)
|
| 68 |
+
|
| 69 |
+
is_active: Mapped[bool] = mapped_column(Boolean, default=True, nullable=False)
|
| 70 |
+
is_verified: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
|
| 71 |
+
|
| 72 |
+
failed_login_attempts: Mapped[int] = mapped_column(Integer, default=0, nullable=False)
|
| 73 |
+
locked_until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 74 |
+
last_login: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 75 |
+
password_changed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 76 |
+
|
| 77 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False)
|
| 78 |
+
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow, nullable=False)
|
| 79 |
+
deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 80 |
+
|
| 81 |
+
roles: Mapped[list[Role]] = relationship(secondary=user_roles, back_populates="users", lazy="selectin")
|
| 82 |
+
sessions: Mapped[list[RefreshSession]] = relationship(back_populates="user", cascade="all, delete-orphan", lazy="selectin")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class RefreshSession(Base):
|
| 86 |
+
__tablename__ = "refresh_sessions"
|
| 87 |
+
|
| 88 |
+
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=_uuid)
|
| 89 |
+
user_id: Mapped[str] = mapped_column(String(36), ForeignKey("users.id", ondelete="CASCADE"), nullable=False, index=True)
|
| 90 |
+
token_key: Mapped[str] = mapped_column(String(64), unique=True, index=True, nullable=False)
|
| 91 |
+
token_hash: Mapped[str] = mapped_column(String(255), nullable=False)
|
| 92 |
+
device_info: Mapped[str | None] = mapped_column(String(255), nullable=True)
|
| 93 |
+
ip_address: Mapped[str | None] = mapped_column(String(45), nullable=True)
|
| 94 |
+
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
| 95 |
+
revoked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
| 96 |
+
|
| 97 |
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, nullable=False)
|
| 98 |
+
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_utcnow, onupdate=_utcnow, nullable=False)
|
| 99 |
+
|
| 100 |
+
user: Mapped[User] = relationship(back_populates="sessions")
|
app/core/auth/schemas.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import re
|
| 4 |
+
from datetime import datetime
|
| 5 |
+
from typing import Any, Optional
|
| 6 |
+
|
| 7 |
+
from pydantic import BaseModel, EmailStr, Field, field_validator
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _validate_password(v: str) -> str:
|
| 11 |
+
if len(v) < 8:
|
| 12 |
+
raise ValueError("Password must be at least 8 characters")
|
| 13 |
+
if len(v) > 128:
|
| 14 |
+
raise ValueError("Password must not exceed 128 characters")
|
| 15 |
+
if not re.search(r"[A-Z]", v):
|
| 16 |
+
raise ValueError("Password must contain at least one uppercase letter")
|
| 17 |
+
if not re.search(r"[a-z]", v):
|
| 18 |
+
raise ValueError("Password must contain at least one lowercase letter")
|
| 19 |
+
if not re.search(r"\d", v):
|
| 20 |
+
raise ValueError("Password must contain at least one digit")
|
| 21 |
+
return v
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class RegisterSchema(BaseModel):
|
| 25 |
+
email: EmailStr
|
| 26 |
+
password: str
|
| 27 |
+
username: Optional[str] = Field(None, min_length=2, max_length=50, pattern=r"^[a-zA-Z0-9_]+$")
|
| 28 |
+
full_name: Optional[str] = Field(None, min_length=1, max_length=100)
|
| 29 |
+
|
| 30 |
+
_validate_password = field_validator("password")(_validate_password)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class LoginSchema(BaseModel):
|
| 34 |
+
email: EmailStr
|
| 35 |
+
password: str
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TokenData(BaseModel):
|
| 39 |
+
access_token: str
|
| 40 |
+
refresh_token: str
|
| 41 |
+
token_type: str = "bearer"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class TokenRefreshSchema(BaseModel):
|
| 45 |
+
refresh_token: str
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class UserProfile(BaseModel):
|
| 49 |
+
id: str
|
| 50 |
+
email: str
|
| 51 |
+
username: Optional[str] = None
|
| 52 |
+
full_name: Optional[str] = None
|
| 53 |
+
is_active: bool
|
| 54 |
+
is_verified: bool
|
| 55 |
+
roles: list[str]
|
| 56 |
+
created_at: datetime
|
| 57 |
+
|
| 58 |
+
@field_validator("roles", mode="before")
|
| 59 |
+
@classmethod
|
| 60 |
+
def _extract_role_names(cls, v: Any) -> list[str]:
|
| 61 |
+
if not v:
|
| 62 |
+
return []
|
| 63 |
+
if isinstance(v[0], str):
|
| 64 |
+
return v
|
| 65 |
+
return [r.name for r in v]
|
| 66 |
+
|
| 67 |
+
model_config = {"from_attributes": True}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class UpdateProfileSchema(BaseModel):
|
| 71 |
+
username: Optional[str] = Field(None, min_length=2, max_length=50, pattern=r"^[a-zA-Z0-9_]+$")
|
| 72 |
+
full_name: Optional[str] = Field(None, min_length=1, max_length=100)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class ChangePasswordSchema(BaseModel):
|
| 76 |
+
current_password: str
|
| 77 |
+
new_password: str
|
| 78 |
+
|
| 79 |
+
_validate_new_password = field_validator("new_password")(_validate_password)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class ForgotPasswordSchema(BaseModel):
|
| 83 |
+
email: EmailStr
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class ResetPasswordSchema(BaseModel):
|
| 87 |
+
token: str
|
| 88 |
+
new_password: str
|
| 89 |
+
|
| 90 |
+
_validate_new_password = field_validator("new_password")(_validate_password)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class SessionOut(BaseModel):
|
| 94 |
+
id: str
|
| 95 |
+
device_info: Optional[str] = None
|
| 96 |
+
ip_address: Optional[str] = None
|
| 97 |
+
created_at: datetime
|
| 98 |
+
expires_at: datetime
|
| 99 |
+
|
| 100 |
+
model_config = {"from_attributes": True}
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class MessageResponse(BaseModel):
|
| 104 |
+
message: str
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
class UserSchemaField(BaseModel):
|
| 108 |
+
field: str
|
| 109 |
+
type: str
|
| 110 |
+
required: bool
|
| 111 |
+
description: str
|
| 112 |
+
constraints: Optional[str] = None
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class UserSchemaResponse(BaseModel):
|
| 116 |
+
table_name: str = "users"
|
| 117 |
+
columns: list[UserSchemaField]
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
# --- Wrapped API response schemas ---
|
| 121 |
+
|
| 122 |
+
class ApiResponse(BaseModel):
|
| 123 |
+
success: bool = True
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
class DataResponse(ApiResponse):
|
| 127 |
+
data: dict
|
| 128 |
+
application_id: Optional[str] = None
|
| 129 |
+
warning: Optional[dict] = None
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class TokenResponse(ApiResponse):
|
| 133 |
+
data: TokenData
|
| 134 |
+
application_id: Optional[str] = None
|
| 135 |
+
warning: Optional[dict] = None
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
class ProfileResponse(ApiResponse):
|
| 139 |
+
data: UserProfile
|
| 140 |
+
application_id: Optional[str] = None
|
| 141 |
+
warning: Optional[dict] = None
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class MessageDataResponse(ApiResponse):
|
| 145 |
+
data: MessageResponse
|
| 146 |
+
application_id: Optional[str] = None
|
| 147 |
+
warning: Optional[dict] = None
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class SchemaResponse(ApiResponse):
|
| 151 |
+
data: UserSchemaResponse
|
| 152 |
+
application_id: Optional[str] = None
|
| 153 |
+
warning: Optional[dict] = None
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class SessionListResponse(ApiResponse):
|
| 157 |
+
data: list[SessionOut]
|
| 158 |
+
application_id: Optional[str] = None
|
| 159 |
+
warning: Optional[dict] = None
|
app/services/auth_service.py
CHANGED
|
@@ -1,11 +1,376 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from app.config import get_settings
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
|
| 6 |
class AuthService:
|
| 7 |
-
def __init__(self) -> None:
|
| 8 |
-
self._settings = get_settings()
|
| 9 |
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import hashlib
|
| 4 |
+
import logging
|
| 5 |
+
import secrets
|
| 6 |
+
from datetime import datetime, timedelta, timezone
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
import jwt
|
| 10 |
+
from argon2 import PasswordHasher
|
| 11 |
+
from argon2.exceptions import VerifyMismatchError
|
| 12 |
+
from fastapi import HTTPException, Request, status
|
| 13 |
+
from sqlalchemy import select, update
|
| 14 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 15 |
+
|
| 16 |
from app.config import get_settings
|
| 17 |
+
from app.core.auth.models import RefreshSession, Role, User
|
| 18 |
+
from app.core.auth.schemas import (
|
| 19 |
+
ChangePasswordSchema,
|
| 20 |
+
ForgotPasswordSchema,
|
| 21 |
+
LoginSchema,
|
| 22 |
+
RegisterSchema,
|
| 23 |
+
ResetPasswordSchema,
|
| 24 |
+
TokenData,
|
| 25 |
+
UpdateProfileSchema,
|
| 26 |
+
UserProfile,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
logger = logging.getLogger("auth_service")
|
| 30 |
+
_settings = get_settings()
|
| 31 |
+
ph = PasswordHasher()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _now() -> datetime:
|
| 35 |
+
return datetime.now(timezone.utc)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _token_key(raw: str) -> str:
|
| 39 |
+
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
|
| 40 |
|
| 41 |
|
| 42 |
class AuthService:
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
@staticmethod
|
| 45 |
+
async def register(db: AsyncSession, schema: RegisterSchema) -> User:
|
| 46 |
+
result = await db.execute(select(User).where(User.email == schema.email))
|
| 47 |
+
if result.scalars().first():
|
| 48 |
+
raise HTTPException(status_code=409, detail="Email already registered")
|
| 49 |
+
|
| 50 |
+
if schema.username:
|
| 51 |
+
result = await db.execute(select(User).where(User.username == schema.username))
|
| 52 |
+
if result.scalars().first():
|
| 53 |
+
raise HTTPException(status_code=409, detail="Username already taken")
|
| 54 |
+
|
| 55 |
+
user = User(
|
| 56 |
+
email=schema.email,
|
| 57 |
+
username=schema.username,
|
| 58 |
+
full_name=schema.full_name,
|
| 59 |
+
password_hash=ph.hash(schema.password),
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
role_result = await db.execute(select(Role).where(Role.name == "User"))
|
| 63 |
+
default_role = role_result.scalars().first()
|
| 64 |
+
if default_role:
|
| 65 |
+
user.roles.append(default_role)
|
| 66 |
+
|
| 67 |
+
db.add(user)
|
| 68 |
+
await db.commit()
|
| 69 |
+
await db.refresh(user)
|
| 70 |
+
return user
|
| 71 |
+
|
| 72 |
+
@staticmethod
|
| 73 |
+
async def login(db: AsyncSession, request: Request, schema: LoginSchema) -> TokenData:
|
| 74 |
+
result = await db.execute(
|
| 75 |
+
select(User).where(User.email == schema.email, User.deleted_at.is_(None))
|
| 76 |
+
)
|
| 77 |
+
user = result.scalars().first()
|
| 78 |
+
|
| 79 |
+
if not user:
|
| 80 |
+
raise HTTPException(status_code=401, detail="Incorrect email or password")
|
| 81 |
+
|
| 82 |
+
if user.locked_until and user.locked_until > _now():
|
| 83 |
+
raise HTTPException(
|
| 84 |
+
status_code=403,
|
| 85 |
+
detail=f"Account locked until {user.locked_until.isoformat()}",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
if not AuthService._verify_password(schema.password, user.password_hash):
|
| 89 |
+
user.failed_login_attempts += 1
|
| 90 |
+
if user.failed_login_attempts >= _settings.max_login_attempts:
|
| 91 |
+
user.locked_until = _now() + timedelta(minutes=_settings.lockout_minutes)
|
| 92 |
+
await db.commit()
|
| 93 |
+
raise HTTPException(status_code=401, detail="Incorrect email or password")
|
| 94 |
+
|
| 95 |
+
user.failed_login_attempts = 0
|
| 96 |
+
user.locked_until = None
|
| 97 |
+
user.last_login = _now()
|
| 98 |
+
|
| 99 |
+
access_token = AuthService._create_access_token(user.id)
|
| 100 |
+
raw_refresh, refresh_hash, token_key, expires_at = AuthService._create_refresh_token()
|
| 101 |
+
|
| 102 |
+
session = RefreshSession(
|
| 103 |
+
user_id=user.id,
|
| 104 |
+
token_key=token_key,
|
| 105 |
+
token_hash=refresh_hash,
|
| 106 |
+
expires_at=expires_at,
|
| 107 |
+
device_info=request.headers.get("User-Agent", "Unknown"),
|
| 108 |
+
ip_address=request.client.host if request.client else "Unknown",
|
| 109 |
+
)
|
| 110 |
+
db.add(session)
|
| 111 |
+
await db.commit()
|
| 112 |
+
|
| 113 |
+
return TokenData(access_token=access_token, refresh_token=raw_refresh)
|
| 114 |
+
|
| 115 |
+
@staticmethod
|
| 116 |
+
async def refresh(db: AsyncSession, raw_refresh_token: str) -> TokenData:
|
| 117 |
+
key = _token_key(raw_refresh_token)
|
| 118 |
+
|
| 119 |
+
result = await db.execute(
|
| 120 |
+
select(RefreshSession).where(
|
| 121 |
+
RefreshSession.token_key == key,
|
| 122 |
+
RefreshSession.revoked_at.is_(None),
|
| 123 |
+
RefreshSession.expires_at > _now(),
|
| 124 |
+
)
|
| 125 |
+
)
|
| 126 |
+
session = result.scalars().first()
|
| 127 |
+
|
| 128 |
+
if not session:
|
| 129 |
+
session = await db.execute(
|
| 130 |
+
select(RefreshSession).where(RefreshSession.token_key == key)
|
| 131 |
+
)
|
| 132 |
+
existing = session.scalars().first()
|
| 133 |
+
if existing and existing.revoked_at is not None:
|
| 134 |
+
await db.execute(
|
| 135 |
+
update(RefreshSession)
|
| 136 |
+
.where(RefreshSession.user_id == existing.user_id, RefreshSession.revoked_at.is_(None))
|
| 137 |
+
.values(revoked_at=_now())
|
| 138 |
+
)
|
| 139 |
+
await db.commit()
|
| 140 |
+
raise HTTPException(
|
| 141 |
+
status_code=401,
|
| 142 |
+
detail="Session compromised. All sessions revoked. Please login again.",
|
| 143 |
+
)
|
| 144 |
+
raise HTTPException(status_code=401, detail="Invalid or expired refresh token")
|
| 145 |
+
|
| 146 |
+
if not AuthService._verify_token(raw_refresh_token, session.token_hash):
|
| 147 |
+
raise HTTPException(status_code=401, detail="Invalid refresh token")
|
| 148 |
+
|
| 149 |
+
user_result = await db.execute(
|
| 150 |
+
select(User).where(
|
| 151 |
+
User.id == session.user_id, User.deleted_at.is_(None), User.is_active.is_(True)
|
| 152 |
+
)
|
| 153 |
+
)
|
| 154 |
+
user = user_result.scalars().first()
|
| 155 |
+
if not user:
|
| 156 |
+
raise HTTPException(status_code=401, detail="User not found or inactive")
|
| 157 |
+
|
| 158 |
+
session.revoked_at = _now()
|
| 159 |
+
|
| 160 |
+
new_access = AuthService._create_access_token(user.id)
|
| 161 |
+
new_raw_refresh, new_hash, new_key, new_expires = AuthService._create_refresh_token()
|
| 162 |
+
|
| 163 |
+
new_session = RefreshSession(
|
| 164 |
+
user_id=user.id,
|
| 165 |
+
token_key=new_key,
|
| 166 |
+
token_hash=new_hash,
|
| 167 |
+
expires_at=new_expires,
|
| 168 |
+
device_info=session.device_info,
|
| 169 |
+
ip_address=session.ip_address,
|
| 170 |
+
)
|
| 171 |
+
db.add(new_session)
|
| 172 |
+
|
| 173 |
+
user.last_login = _now()
|
| 174 |
+
await db.commit()
|
| 175 |
+
|
| 176 |
+
return TokenData(access_token=new_access, refresh_token=new_raw_refresh)
|
| 177 |
+
|
| 178 |
+
@staticmethod
|
| 179 |
+
async def logout(db: AsyncSession, user: User, raw_refresh_token: str):
|
| 180 |
+
key = _token_key(raw_refresh_token)
|
| 181 |
+
result = await db.execute(
|
| 182 |
+
select(RefreshSession).where(
|
| 183 |
+
RefreshSession.token_key == key,
|
| 184 |
+
RefreshSession.user_id == user.id,
|
| 185 |
+
RefreshSession.revoked_at.is_(None),
|
| 186 |
+
)
|
| 187 |
+
)
|
| 188 |
+
session = result.scalars().first()
|
| 189 |
+
if not session:
|
| 190 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 191 |
+
session.revoked_at = _now()
|
| 192 |
+
await db.commit()
|
| 193 |
+
|
| 194 |
+
@staticmethod
|
| 195 |
+
async def logout_all(db: AsyncSession, user: User):
|
| 196 |
+
now = _now()
|
| 197 |
+
await db.execute(
|
| 198 |
+
update(RefreshSession)
|
| 199 |
+
.where(
|
| 200 |
+
RefreshSession.user_id == user.id,
|
| 201 |
+
RefreshSession.revoked_at.is_(None),
|
| 202 |
+
)
|
| 203 |
+
.values(revoked_at=now)
|
| 204 |
+
)
|
| 205 |
+
await db.commit()
|
| 206 |
+
|
| 207 |
+
@staticmethod
|
| 208 |
+
async def change_password(db: AsyncSession, user: User, schema: ChangePasswordSchema):
|
| 209 |
+
if not AuthService._verify_password(schema.current_password, user.password_hash):
|
| 210 |
+
raise HTTPException(status_code=400, detail="Incorrect current password")
|
| 211 |
+
user.password_hash = ph.hash(schema.new_password)
|
| 212 |
+
user.password_changed_at = _now()
|
| 213 |
+
await db.commit()
|
| 214 |
+
|
| 215 |
+
@staticmethod
|
| 216 |
+
async def forgot_password(db: AsyncSession, schema: ForgotPasswordSchema):
|
| 217 |
+
result = await db.execute(
|
| 218 |
+
select(User).where(User.email == schema.email, User.deleted_at.is_(None))
|
| 219 |
+
)
|
| 220 |
+
user = result.scalars().first()
|
| 221 |
+
if user:
|
| 222 |
+
reset_token = jwt.encode(
|
| 223 |
+
{
|
| 224 |
+
"sub": user.id,
|
| 225 |
+
"type": "reset_password",
|
| 226 |
+
"exp": _now() + timedelta(hours=1),
|
| 227 |
+
},
|
| 228 |
+
_settings.jwt_secret_key,
|
| 229 |
+
algorithm=_settings.jwt_algorithm,
|
| 230 |
+
)
|
| 231 |
+
logger.info("Password reset token for %s: %s", user.email, reset_token)
|
| 232 |
+
|
| 233 |
+
@staticmethod
|
| 234 |
+
async def reset_password(db: AsyncSession, schema: ResetPasswordSchema):
|
| 235 |
+
try:
|
| 236 |
+
payload = jwt.decode(
|
| 237 |
+
schema.token,
|
| 238 |
+
_settings.jwt_secret_key,
|
| 239 |
+
algorithms=[_settings.jwt_algorithm],
|
| 240 |
+
)
|
| 241 |
+
if payload.get("type") != "reset_password":
|
| 242 |
+
raise HTTPException(status_code=400, detail="Invalid token type")
|
| 243 |
+
user_id = payload.get("sub")
|
| 244 |
+
except jwt.PyJWTError:
|
| 245 |
+
raise HTTPException(status_code=400, detail="Invalid or expired reset token")
|
| 246 |
+
|
| 247 |
+
result = await db.execute(select(User).where(User.id == user_id))
|
| 248 |
+
user = result.scalars().first()
|
| 249 |
+
if not user:
|
| 250 |
+
raise HTTPException(status_code=404, detail="User not found")
|
| 251 |
+
|
| 252 |
+
user.password_hash = ph.hash(schema.new_password)
|
| 253 |
+
user.password_changed_at = _now()
|
| 254 |
+
|
| 255 |
+
await db.execute(
|
| 256 |
+
update(RefreshSession)
|
| 257 |
+
.where(RefreshSession.user_id == user.id, RefreshSession.revoked_at.is_(None))
|
| 258 |
+
.values(revoked_at=_now())
|
| 259 |
+
)
|
| 260 |
+
await db.commit()
|
| 261 |
+
|
| 262 |
+
@staticmethod
|
| 263 |
+
async def update_profile(db: AsyncSession, user: User, schema: UpdateProfileSchema) -> User:
|
| 264 |
+
if schema.username is not None:
|
| 265 |
+
result = await db.execute(
|
| 266 |
+
select(User).where(User.username == schema.username, User.id != user.id)
|
| 267 |
+
)
|
| 268 |
+
if result.scalars().first():
|
| 269 |
+
raise HTTPException(status_code=409, detail="Username already taken")
|
| 270 |
+
user.username = schema.username
|
| 271 |
+
if schema.full_name is not None:
|
| 272 |
+
user.full_name = schema.full_name
|
| 273 |
+
await db.commit()
|
| 274 |
+
await db.refresh(user)
|
| 275 |
+
return user
|
| 276 |
+
|
| 277 |
+
@staticmethod
|
| 278 |
+
async def soft_delete(db: AsyncSession, user: User):
|
| 279 |
+
user.deleted_at = _now()
|
| 280 |
+
user.is_active = False
|
| 281 |
+
await db.execute(
|
| 282 |
+
update(RefreshSession)
|
| 283 |
+
.where(RefreshSession.user_id == user.id, RefreshSession.revoked_at.is_(None))
|
| 284 |
+
.values(revoked_at=_now())
|
| 285 |
+
)
|
| 286 |
+
await db.commit()
|
| 287 |
+
|
| 288 |
+
@staticmethod
|
| 289 |
+
async def list_sessions(db: AsyncSession, user: User) -> list[RefreshSession]:
|
| 290 |
+
result = await db.execute(
|
| 291 |
+
select(RefreshSession)
|
| 292 |
+
.where(
|
| 293 |
+
RefreshSession.user_id == user.id,
|
| 294 |
+
RefreshSession.revoked_at.is_(None),
|
| 295 |
+
)
|
| 296 |
+
.order_by(RefreshSession.created_at.desc())
|
| 297 |
+
)
|
| 298 |
+
return list(result.scalars().all())
|
| 299 |
+
|
| 300 |
+
@staticmethod
|
| 301 |
+
async def revoke_session(db: AsyncSession, user: User, session_id: str):
|
| 302 |
+
result = await db.execute(
|
| 303 |
+
select(RefreshSession).where(
|
| 304 |
+
RefreshSession.id == session_id,
|
| 305 |
+
RefreshSession.user_id == user.id,
|
| 306 |
+
RefreshSession.revoked_at.is_(None),
|
| 307 |
+
)
|
| 308 |
+
)
|
| 309 |
+
session = result.scalars().first()
|
| 310 |
+
if not session:
|
| 311 |
+
raise HTTPException(status_code=404, detail="Session not found")
|
| 312 |
+
session.revoked_at = _now()
|
| 313 |
+
await db.commit()
|
| 314 |
+
|
| 315 |
+
@staticmethod
|
| 316 |
+
async def cleanup_expired_sessions(db: AsyncSession):
|
| 317 |
+
result = await db.execute(
|
| 318 |
+
select(RefreshSession).where(RefreshSession.expires_at < _now())
|
| 319 |
+
)
|
| 320 |
+
count = 0
|
| 321 |
+
for s in result.scalars().all():
|
| 322 |
+
if s.revoked_at is None:
|
| 323 |
+
s.revoked_at = _now()
|
| 324 |
+
count += 1
|
| 325 |
+
if count:
|
| 326 |
+
await db.commit()
|
| 327 |
+
logger.info("Cleaned up %s expired sessions", count)
|
| 328 |
+
|
| 329 |
+
@staticmethod
|
| 330 |
+
def _create_access_token(user_id: str) -> str:
|
| 331 |
+
now = _now()
|
| 332 |
+
payload = {
|
| 333 |
+
"sub": user_id,
|
| 334 |
+
"type": "access",
|
| 335 |
+
"iat": now,
|
| 336 |
+
"exp": now + timedelta(minutes=_settings.access_token_expire_minutes),
|
| 337 |
+
"iss": _settings.jwt_issuer,
|
| 338 |
+
}
|
| 339 |
+
return jwt.encode(payload, _settings.jwt_secret_key, algorithm=_settings.jwt_algorithm)
|
| 340 |
+
|
| 341 |
+
@staticmethod
|
| 342 |
+
def _create_refresh_token() -> tuple[str, str, str, datetime]:
|
| 343 |
+
token = secrets.token_urlsafe(64)
|
| 344 |
+
token_hash = ph.hash(token)
|
| 345 |
+
token_key = _token_key(token)
|
| 346 |
+
expires_at = _now() + timedelta(days=_settings.refresh_token_expire_days)
|
| 347 |
+
return token, token_hash, token_key, expires_at
|
| 348 |
+
|
| 349 |
+
@staticmethod
|
| 350 |
+
def _verify_password(plain: str, hashed: str) -> bool:
|
| 351 |
+
try:
|
| 352 |
+
ph.verify(hashed, plain)
|
| 353 |
+
return True
|
| 354 |
+
except VerifyMismatchError:
|
| 355 |
+
return False
|
| 356 |
+
|
| 357 |
+
@staticmethod
|
| 358 |
+
def _verify_token(raw: str, hashed: str) -> bool:
|
| 359 |
+
try:
|
| 360 |
+
ph.verify(hashed, raw)
|
| 361 |
+
return True
|
| 362 |
+
except VerifyMismatchError:
|
| 363 |
+
return False
|
| 364 |
+
|
| 365 |
+
@staticmethod
|
| 366 |
+
def user_to_profile(user: User) -> UserProfile:
|
| 367 |
+
return UserProfile(
|
| 368 |
+
id=user.id,
|
| 369 |
+
email=user.email,
|
| 370 |
+
username=user.username,
|
| 371 |
+
full_name=user.full_name,
|
| 372 |
+
is_active=user.is_active,
|
| 373 |
+
is_verified=user.is_verified,
|
| 374 |
+
roles=[r.name for r in user.roles],
|
| 375 |
+
created_at=user.created_at,
|
| 376 |
+
)
|
requirements.txt
CHANGED
|
@@ -27,7 +27,14 @@ sqlglot>=20.0.0
|
|
| 27 |
tiktoken>=0.9.0
|
| 28 |
PyJWT>=2.9.0
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
# Async database drivers
|
|
|
|
|
|
|
| 31 |
aiomysql>=0.3.2
|
| 32 |
asyncpg>=0.31.0
|
| 33 |
motor>=3.7.1
|
|
|
|
| 27 |
tiktoken>=0.9.0
|
| 28 |
PyJWT>=2.9.0
|
| 29 |
|
| 30 |
+
# Authentication
|
| 31 |
+
argon2-cffi>=23.1.0
|
| 32 |
+
email-validator>=2.1.0
|
| 33 |
+
slowapi>=0.1.9
|
| 34 |
+
|
| 35 |
# Async database drivers
|
| 36 |
+
aiosqlite>=0.20.0
|
| 37 |
+
sqlalchemy[asyncio]>=2.0.0
|
| 38 |
aiomysql>=0.3.2
|
| 39 |
asyncpg>=0.31.0
|
| 40 |
motor>=3.7.1
|
start.sh
CHANGED
|
@@ -9,6 +9,10 @@ log "=== Starting up ==="
|
|
| 9 |
log "Python: $(python --version 2>&1)"
|
| 10 |
log "Working dir: $(pwd)"
|
| 11 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
# Check core deps
|
| 13 |
python -c "import markitdown, fastapi, httpx, pandas" 2>/dev/null
|
| 14 |
if [ $? -ne 0 ]; then
|
|
|
|
| 9 |
log "Python: $(python --version 2>&1)"
|
| 10 |
log "Working dir: $(pwd)"
|
| 11 |
|
| 12 |
+
# Ensure required directories exist
|
| 13 |
+
mkdir -p /app/data /app/logs
|
| 14 |
+
log "Data directories: OK"
|
| 15 |
+
|
| 16 |
# Check core deps
|
| 17 |
python -c "import markitdown, fastapi, httpx, pandas" 2>/dev/null
|
| 18 |
if [ $? -ne 0 ]; then
|