feat: PocketVeto v1.0.0 — initial public release
Self-hosted US Congress monitoring platform with AI policy briefs, bill/member/topic follows, ntfy + RSS + email notifications, alignment scoring, collections, and draft-letter generator. Authored by: Jack Levy
This commit is contained in:
0
backend/app/core/__init__.py
Normal file
0
backend/app/core/__init__.py
Normal file
44
backend/app/core/crypto.py
Normal file
44
backend/app/core/crypto.py
Normal file
@@ -0,0 +1,44 @@
|
||||
"""Symmetric encryption for sensitive user prefs (e.g. ntfy password).
|
||||
|
||||
Key priority:
|
||||
1. ENCRYPTION_SECRET_KEY env var (recommended — dedicated key, easily rotatable)
|
||||
2. Derived from JWT_SECRET_KEY (fallback for existing installs)
|
||||
|
||||
Generate a dedicated key:
|
||||
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
_PREFIX = "enc:"
|
||||
_fernet_instance: Fernet | None = None
|
||||
|
||||
|
||||
def _fernet() -> Fernet:
|
||||
global _fernet_instance
|
||||
if _fernet_instance is None:
|
||||
from app.config import settings
|
||||
if settings.ENCRYPTION_SECRET_KEY:
|
||||
# Use dedicated key directly (must be a valid 32-byte base64url key)
|
||||
_fernet_instance = Fernet(settings.ENCRYPTION_SECRET_KEY.encode())
|
||||
else:
|
||||
# Fallback: derive from JWT secret
|
||||
key_bytes = hashlib.sha256(settings.JWT_SECRET_KEY.encode()).digest()
|
||||
_fernet_instance = Fernet(base64.urlsafe_b64encode(key_bytes))
|
||||
return _fernet_instance
|
||||
|
||||
|
||||
def encrypt_secret(plaintext: str) -> str:
|
||||
"""Encrypt a string and return a prefixed ciphertext."""
|
||||
if not plaintext:
|
||||
return plaintext
|
||||
return _PREFIX + _fernet().encrypt(plaintext.encode()).decode()
|
||||
|
||||
|
||||
def decrypt_secret(value: str) -> str:
|
||||
"""Decrypt a value produced by encrypt_secret. Returns plaintext as-is (legacy support)."""
|
||||
if not value or not value.startswith(_PREFIX):
|
||||
return value # legacy plaintext — return unchanged
|
||||
return _fernet().decrypt(value[len(_PREFIX):].encode()).decode()
|
||||
55
backend/app/core/dependencies.py
Normal file
55
backend/app/core/dependencies.py
Normal file
@@ -0,0 +1,55 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import JWTError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.security import decode_token
|
||||
from app.database import get_db
|
||||
from app.models.user import User
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
||||
oauth2_scheme_optional = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
||||
|
||||
|
||||
async def get_current_user(
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User:
|
||||
credentials_error = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid or expired token",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
try:
|
||||
user_id = decode_token(token)
|
||||
except JWTError:
|
||||
raise credentials_error
|
||||
|
||||
user = await db.get(User, user_id)
|
||||
if user is None:
|
||||
raise credentials_error
|
||||
return user
|
||||
|
||||
|
||||
async def get_optional_user(
|
||||
token: str | None = Depends(oauth2_scheme_optional),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> User | None:
|
||||
if not token:
|
||||
return None
|
||||
try:
|
||||
user_id = decode_token(token)
|
||||
return await db.get(User, user_id)
|
||||
except (JWTError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
async def get_current_admin(
|
||||
current_user: User = Depends(get_current_user),
|
||||
) -> User:
|
||||
if not current_user.is_admin:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Admin access required",
|
||||
)
|
||||
return current_user
|
||||
36
backend/app/core/security.py
Normal file
36
backend/app/core/security.py
Normal file
@@ -0,0 +1,36 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
|
||||
from app.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
ALGORITHM = "HS256"
|
||||
|
||||
|
||||
def hash_password(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
return pwd_context.verify(plain, hashed)
|
||||
|
||||
|
||||
def create_access_token(user_id: int) -> str:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.JWT_EXPIRE_MINUTES)
|
||||
return jwt.encode(
|
||||
{"sub": str(user_id), "exp": expire},
|
||||
settings.JWT_SECRET_KEY,
|
||||
algorithm=ALGORITHM,
|
||||
)
|
||||
|
||||
|
||||
def decode_token(token: str) -> int:
|
||||
"""Decode JWT and return user_id. Raises JWTError on failure."""
|
||||
payload = jwt.decode(token, settings.JWT_SECRET_KEY, algorithms=[ALGORITHM])
|
||||
user_id = payload.get("sub")
|
||||
if user_id is None:
|
||||
raise JWTError("Missing sub claim")
|
||||
return int(user_id)
|
||||
Reference in New Issue
Block a user