first commit

This commit is contained in:
2025-11-30 00:07:24 +01:00
commit b5e642aecb
78 changed files with 15162 additions and 0 deletions

75
app/schemas/__init__.py Normal file
View File

@ -0,0 +1,75 @@
"""
Schemas Module
Provides Pydantic schemas for request validation and response serialization.
Usage:
from app.schemas.user import UserCreate, UserResponse
from app.schemas.client import ClientCreate, ClientResponse
from app.schemas.auth import TokenRequest, TokenResponse
"""
from app.schemas.user import (
UserBase,
UserCreate,
UserUpdate,
UserLogin,
UserResponse,
UserListResponse,
UserStatistics,
PasswordChange
)
from app.schemas.client import (
ClientBase,
ClientCreate,
ClientUpdate,
ClientResponse,
ClientWithSecret,
ClientListResponse
)
from app.schemas.auth import (
AuthorizationRequest,
AuthorizationResponse,
TokenRequest,
TokenResponse,
UserInfoResponse,
LoginRequest,
LoginResponse,
RegisterRequest,
RegisterResponse,
OIDCDiscoveryResponse
)
__all__ = [
# User schemas
'UserBase',
'UserCreate',
'UserUpdate',
'UserLogin',
'UserResponse',
'UserListResponse',
'UserStatistics',
'PasswordChange',
# Client schemas
'ClientBase',
'ClientCreate',
'ClientUpdate',
'ClientResponse',
'ClientWithSecret',
'ClientListResponse',
# Auth schemas
'AuthorizationRequest',
'AuthorizationResponse',
'TokenRequest',
'TokenResponse',
'UserInfoResponse',
'LoginRequest',
'LoginResponse',
'RegisterRequest',
'RegisterResponse',
'OIDCDiscoveryResponse',
]

159
app/schemas/auth.py Normal file
View File

@ -0,0 +1,159 @@
"""
Authentication Schemas
Pydantic schemas for authentication and OIDC-related requests/responses.
"""
from pydantic import BaseModel, Field, field_validator
from typing import Optional, List
# ==========================================
# OIDC Authorization Schemas
# ==========================================
class AuthorizationRequest(BaseModel):
"""Schema for OIDC authorization request."""
client_id: str = Field(..., description="OAuth client ID")
redirect_uri: str = Field(..., description="Callback URL")
response_type: str = Field("code", description="Response type (only 'code' supported)")
scope: str = Field("openid", description="Requested scopes (space-separated)")
state: Optional[str] = Field(None, description="CSRF protection state")
@field_validator('response_type')
@classmethod
def validate_response_type(cls, v: str) -> str:
"""Validate that response_type is 'code'."""
if v != "code":
raise ValueError("Only 'code' response_type is supported (Authorization Code Flow)")
return v
@field_validator('scope')
@classmethod
def validate_scope(cls, v: str) -> str:
"""Validate that scope includes 'openid'."""
scopes = v.split()
if 'openid' not in scopes:
raise ValueError("Scope must include 'openid'")
return v
class AuthorizationResponse(BaseModel):
"""Schema for OIDC authorization response."""
code: str = Field(..., description="Authorization code")
state: Optional[str] = Field(None, description="State from request")
# ==========================================
# OIDC Token Schemas
# ==========================================
class TokenRequest(BaseModel):
"""Schema for OIDC token request."""
grant_type: str = Field(..., description="Grant type (authorization_code)")
code: str = Field(..., description="Authorization code")
redirect_uri: str = Field(..., description="Redirect URI (must match authorization request)")
client_id: str = Field(..., description="OAuth client ID")
client_secret: str = Field(..., description="OAuth client secret")
@field_validator('grant_type')
@classmethod
def validate_grant_type(cls, v: str) -> str:
"""Validate grant_type."""
if v != "authorization_code":
raise ValueError("Only 'authorization_code' grant_type is supported")
return v
class TokenResponse(BaseModel):
"""Schema for OIDC token response."""
access_token: str = Field(..., description="Access token")
token_type: str = Field("Bearer", description="Token type")
expires_in: int = Field(..., description="Token expiration time in seconds")
id_token: str = Field(..., description="OpenID Connect ID token")
scope: str = Field(..., description="Granted scopes")
# ==========================================
# UserInfo Schemas
# ==========================================
class UserInfoResponse(BaseModel):
"""Schema for OIDC UserInfo response."""
sub: str = Field(..., description="Subject identifier (user ID)")
username: str
email: str
name: str
preferred_username: str
role: str
permissions: List[str]
# ==========================================
# Login/Registration Schemas
# ==========================================
class LoginRequest(BaseModel):
"""Schema for user login."""
username: str = Field(..., description="Username")
password: str = Field(..., description="Password")
class LoginResponse(BaseModel):
"""Schema for login response."""
success: bool
message: str
user: Optional[dict] = None
redirect_url: Optional[str] = None
class RegisterRequest(BaseModel):
"""Schema for user registration."""
username: str = Field(..., min_length=3, max_length=80)
email: str = Field(..., description="Email address")
name: str = Field(..., min_length=1, max_length=120)
password: str = Field(..., min_length=8)
password_confirm: str = Field(..., description="Password confirmation")
preferred_username: Optional[str] = Field(None, max_length=80)
@field_validator('password')
@classmethod
def validate_password(cls, v: str) -> str:
"""Validate password strength."""
if len(v) < 8:
raise ValueError('Password must be at least 8 characters long')
return v
@field_validator('password_confirm')
@classmethod
def passwords_match(cls, v: str, info) -> str:
"""Validate that passwords match."""
if 'password' in info.data and v != info.data['password']:
raise ValueError('Passwords do not match')
return v
class RegisterResponse(BaseModel):
"""Schema for registration response."""
success: bool
message: str
user_id: Optional[int] = None
# ==========================================
# OIDC Discovery Schemas
# ==========================================
class OIDCDiscoveryResponse(BaseModel):
"""Schema for OIDC discovery document."""
issuer: str
authorization_endpoint: str
token_endpoint: str
userinfo_endpoint: str
jwks_uri: str
response_types_supported: List[str]
subject_types_supported: List[str]
id_token_signing_alg_values_supported: List[str]
scopes_supported: List[str]
token_endpoint_auth_methods_supported: List[str]
claims_supported: List[str]

93
app/schemas/client.py Normal file
View File

@ -0,0 +1,93 @@
"""
Client Schemas
Pydantic schemas for OIDC client-related requests and responses.
"""
from pydantic import BaseModel, Field, field_validator
from typing import List, Optional
from datetime import datetime
# ==========================================
# Base Schemas
# ==========================================
class ClientBase(BaseModel):
"""Base client schema with common fields."""
client_name: str = Field(..., min_length=1, max_length=255, description="Client application name")
redirect_uris: List[str] = Field(..., min_items=1, description="List of allowed redirect URIs")
allowed_scopes: List[str] = Field(default_factory=lambda: ["openid", "profile", "email"], description="Allowed OAuth scopes")
# ==========================================
# Request Schemas (Input)
# ==========================================
class ClientCreate(ClientBase):
"""Schema for creating a new OIDC client."""
client_id: Optional[str] = Field(None, description="Client ID (auto-generated if not provided)")
client_secret: Optional[str] = Field(None, description="Client secret (auto-generated if not provided)")
@field_validator('redirect_uris')
@classmethod
def validate_redirect_uris(cls, v: List[str]) -> List[str]:
"""Validate redirect URIs."""
if not v:
raise ValueError('At least one redirect URI is required')
for uri in v:
if not uri.startswith(('http://', 'https://')):
raise ValueError(f'Invalid redirect URI: {uri}. Must start with http:// or https://')
return v
class ClientUpdate(BaseModel):
"""Schema for updating an OIDC client."""
client_name: Optional[str] = Field(None, min_length=1, max_length=255)
redirect_uris: Optional[List[str]] = None
allowed_scopes: Optional[List[str]] = None
new_client_secret: Optional[str] = Field(None, description="New client secret (optional)")
@field_validator('redirect_uris')
@classmethod
def validate_redirect_uris(cls, v: Optional[List[str]]) -> Optional[List[str]]:
"""Validate redirect URIs if provided."""
if v is not None:
if not v:
raise ValueError('At least one redirect URI is required')
for uri in v:
if not uri.startswith(('http://', 'https://')):
raise ValueError(f'Invalid redirect URI: {uri}')
return v
# ==========================================
# Response Schemas (Output)
# ==========================================
class ClientResponse(BaseModel):
"""Schema for client responses."""
id: int
client_id: str
client_name: str
redirect_uris: List[str]
allowed_scopes: List[str]
created_at: datetime
updated_at: datetime
model_config = {"from_attributes": True}
class ClientWithSecret(ClientResponse):
"""Schema for client response including secret (only for creation)."""
client_secret: str = Field(..., description="Client secret (only shown once)")
class ClientListResponse(BaseModel):
"""Schema for client list."""
clients: List[ClientResponse]
total: int

136
app/schemas/user.py Normal file
View File

@ -0,0 +1,136 @@
"""
User Schemas
Pydantic schemas for user-related requests and responses.
Provides input validation and output serialization.
"""
from pydantic import BaseModel, EmailStr, Field, field_validator
from typing import Optional, List
from datetime import datetime
# ==========================================
# Base Schemas
# ==========================================
class UserBase(BaseModel):
"""Base user schema with common fields."""
username: str = Field(..., min_length=3, max_length=80, description="Username (3-80 characters)")
email: EmailStr = Field(..., description="Email address")
name: str = Field(..., min_length=1, max_length=120, description="Full name")
preferred_username: Optional[str] = Field(None, max_length=80, description="Preferred display name")
# ==========================================
# Request Schemas (Input)
# ==========================================
class UserCreate(UserBase):
"""Schema for creating a new user."""
password: str = Field(..., min_length=8, description="Password (minimum 8 characters)")
password_confirm: str = Field(..., description="Password confirmation")
role: Optional[str] = Field("user", description="User role")
is_admin: Optional[bool] = Field(False, description="Admin flag")
is_active: Optional[bool] = Field(True, description="Active status")
permissions: Optional[List[str]] = Field(default_factory=list, description="List of permissions")
@field_validator('password')
@classmethod
def validate_password(cls, v: str) -> str:
"""Validate password strength."""
if len(v) < 8:
raise ValueError('Password must be at least 8 characters long')
return v
@field_validator('password_confirm')
@classmethod
def passwords_match(cls, v: str, info) -> str:
"""Validate that passwords match."""
if 'password' in info.data and v != info.data['password']:
raise ValueError('Passwords do not match')
return v
class UserUpdate(BaseModel):
"""Schema for updating a user."""
username: Optional[str] = Field(None, min_length=3, max_length=80)
email: Optional[EmailStr] = None
name: Optional[str] = Field(None, min_length=1, max_length=120)
preferred_username: Optional[str] = Field(None, max_length=80)
role: Optional[str] = None
is_admin: Optional[bool] = None
is_active: Optional[bool] = None
permissions: Optional[List[str]] = None
new_password: Optional[str] = Field(None, min_length=8, description="New password (optional)")
@field_validator('new_password')
@classmethod
def validate_password(cls, v: Optional[str]) -> Optional[str]:
"""Validate password strength if provided."""
if v is not None and len(v) < 8:
raise ValueError('Password must be at least 8 characters long')
return v
class UserLogin(BaseModel):
"""Schema for user login."""
username: str = Field(..., description="Username")
password: str = Field(..., description="Password")
class PasswordChange(BaseModel):
"""Schema for changing user password."""
current_password: str = Field(..., description="Current password")
new_password: str = Field(..., min_length=8, description="New password")
new_password_confirm: str = Field(..., description="New password confirmation")
@field_validator('new_password')
@classmethod
def validate_password(cls, v: str) -> str:
"""Validate password strength."""
if len(v) < 8:
raise ValueError('Password must be at least 8 characters long')
return v
@field_validator('new_password_confirm')
@classmethod
def passwords_match(cls, v: str, info) -> str:
"""Validate that passwords match."""
if 'new_password' in info.data and v != info.data['new_password']:
raise ValueError('Passwords do not match')
return v
# ==========================================
# Response Schemas (Output)
# ==========================================
class UserResponse(UserBase):
"""Schema for user responses."""
id: int
role: str
is_admin: bool
is_active: bool
permissions: List[str]
created_at: datetime
updated_at: datetime
model_config = {"from_attributes": True}
class UserListResponse(BaseModel):
"""Schema for paginated user list."""
users: List[UserResponse]
total: int
page: int
per_page: int
total_pages: int
class UserStatistics(BaseModel):
"""Schema for user statistics."""
total_users: int
active_users: int
inactive_users: int
admin_users: int