mirror of
https://github.com/blackboxprogramming/BlackRoad-Operating-System.git
synced 2026-03-17 05:57:21 -05:00
This commit adds a complete backend infrastructure with: **Core Infrastructure:** - FastAPI application with async/await support - PostgreSQL database with SQLAlchemy ORM - Redis caching layer - JWT authentication and authorization - Docker and Docker Compose configuration **API Services:** - Authentication API (register, login, JWT tokens) - RoadMail API (email service with folders, send/receive) - BlackRoad Social API (posts, comments, likes, follows) - BlackStream API (video streaming with views/likes) - File Storage API (file explorer with upload/download) - RoadCoin Blockchain API (mining, transactions, wallet) - AI Chat API (conversations with AI assistant) **Database Models:** - User accounts with wallet integration - Email and folder management - Social media posts and engagement - Video metadata and analytics - File storage with sharing - Blockchain blocks and transactions - AI conversation history **Features:** - Complete CRUD operations for all services - Real-time blockchain mining with proof-of-work - Transaction validation and wallet management - File upload with S3 integration (ready) - Social feed with engagement metrics - Email system with threading support - AI chat with conversation persistence **Documentation:** - Comprehensive README with setup instructions - API documentation (Swagger/ReDoc auto-generated) - Deployment guide for multiple platforms - Testing framework with pytest **DevOps:** - Docker containerization - Docker Compose for local development - Database migrations with Alembic - Health check endpoints - Makefile for common tasks All APIs are production-ready with proper error handling, input validation, and security measures.
101 lines
3.1 KiB
Python
101 lines
3.1 KiB
Python
"""Authentication utilities"""
|
|
from datetime import datetime, timedelta
|
|
from typing import Optional
|
|
from jose import JWTError, jwt
|
|
from passlib.context import CryptContext
|
|
from fastapi import Depends, HTTPException, status
|
|
from fastapi.security import OAuth2PasswordBearer
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
from sqlalchemy import select
|
|
|
|
from app.config import settings
|
|
from app.database import get_db
|
|
from app.models.user import User
|
|
|
|
# Password hashing
|
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
|
|
# OAuth2 scheme
|
|
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
|
|
|
|
|
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
|
"""Verify a password against a hash"""
|
|
return pwd_context.verify(plain_password, hashed_password)
|
|
|
|
|
|
def get_password_hash(password: str) -> str:
|
|
"""Hash a password"""
|
|
return pwd_context.hash(password)
|
|
|
|
|
|
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
|
|
"""Create a JWT access token"""
|
|
to_encode = data.copy()
|
|
if expires_delta:
|
|
expire = datetime.utcnow() + expires_delta
|
|
else:
|
|
expire = datetime.utcnow() + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
|
|
|
to_encode.update({"exp": expire, "type": "access"})
|
|
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
|
return encoded_jwt
|
|
|
|
|
|
def create_refresh_token(data: dict) -> str:
|
|
"""Create a JWT refresh token"""
|
|
to_encode = data.copy()
|
|
expire = datetime.utcnow() + timedelta(days=settings.REFRESH_TOKEN_EXPIRE_DAYS)
|
|
to_encode.update({"exp": expire, "type": "refresh"})
|
|
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
|
return encoded_jwt
|
|
|
|
|
|
async def get_current_user(
|
|
token: str = Depends(oauth2_scheme),
|
|
db: AsyncSession = Depends(get_db)
|
|
) -> User:
|
|
"""Get the current authenticated user"""
|
|
credentials_exception = HTTPException(
|
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
|
detail="Could not validate credentials",
|
|
headers={"WWW-Authenticate": "Bearer"},
|
|
)
|
|
|
|
try:
|
|
payload = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
|
|
user_id: int = payload.get("user_id")
|
|
if user_id is None:
|
|
raise credentials_exception
|
|
except JWTError:
|
|
raise credentials_exception
|
|
|
|
result = await db.execute(select(User).where(User.id == user_id))
|
|
user = result.scalar_one_or_none()
|
|
|
|
if user is None:
|
|
raise credentials_exception
|
|
|
|
return user
|
|
|
|
|
|
async def get_current_active_user(
|
|
current_user: User = Depends(get_current_user)
|
|
) -> User:
|
|
"""Get the current active user"""
|
|
if not current_user.is_active:
|
|
raise HTTPException(status_code=400, detail="Inactive user")
|
|
return current_user
|
|
|
|
|
|
async def get_current_admin_user(
|
|
current_user: User = Depends(get_current_active_user)
|
|
) -> User:
|
|
"""Get the current admin user"""
|
|
if not current_user.is_admin:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="Not enough permissions"
|
|
)
|
|
return current_user
|