Init commit
This commit is contained in:
parent
2ba9e2f8b9
commit
925077eca1
|
|
@ -0,0 +1,40 @@
|
|||
from typing import Generator
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from jose import jwt, JWTError
|
||||
from pydantic import ValidationError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app import crud, models, schemas
|
||||
from app.models.user import User
|
||||
from app.core import security
|
||||
from app.core.config import settings
|
||||
from app.db.session import SessionLocal
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/v1/auth/login")
|
||||
|
||||
def get_db() -> Generator:
|
||||
try:
|
||||
db = SessionLocal()
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
def get_current_user(
|
||||
db: Session = Depends(get_db),
|
||||
token: str = Depends(oauth2_scheme)
|
||||
) -> User:
|
||||
try:
|
||||
payload = jwt.decode(
|
||||
token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM]
|
||||
)
|
||||
token_data = schemas.TokenPayload(**payload)
|
||||
except (JWTError, ValidationError):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Could not validate credentials",
|
||||
)
|
||||
user = crud.user.get_user(db, user_id=token_data.sub)
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return user
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
from fastapi import APIRouter
|
||||
from app.api.v1.endpoints import auth, users, messages, verification
|
||||
|
||||
api_router = APIRouter()
|
||||
|
||||
# api_router.include_router(auth.router, prefix="/auth", tags=["authentication"])
|
||||
api_router.include_router(users.router, prefix="/users", tags=["users"])
|
||||
# api_router.include_router(messages.router, prefix="/messages", tags=["messages"])
|
||||
# api_router.include_router(verification.router, prefix="/verification", tags=["verification"])
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
from typing import Any
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from app import crud
|
||||
from app.api import deps
|
||||
from app.schemas.user import User, UserCreate
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/{user_id}", response_model=User)
|
||||
def read_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(deps.get_db),
|
||||
current_user: User = Depends(deps.get_current_user)
|
||||
) -> Any:
|
||||
"""
|
||||
Get user by ID.
|
||||
"""
|
||||
user = crud.user.get_user(db, user_id=user_id)
|
||||
if user is None:
|
||||
raise HTTPException(
|
||||
status_code=404,
|
||||
detail="User not found"
|
||||
)
|
||||
return user
|
||||
|
||||
@router.post("/", response_model=User)
|
||||
def create_user(
|
||||
*,
|
||||
db: Session = Depends(deps.get_db),
|
||||
user_in: UserCreate,
|
||||
) -> Any:
|
||||
"""
|
||||
Create new user.
|
||||
"""
|
||||
user = crud.user.get_user_by_email(db, email=user_in.email)
|
||||
if user:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail="Email already registered"
|
||||
)
|
||||
user = crud.user.create_user(db, user=user_in)
|
||||
return user
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
from pydantic_settings import BaseSettings
|
||||
|
||||
class Settings(BaseSettings):
|
||||
SECRET_KEY: str = "your-secret-key-here" # Change in production!
|
||||
ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
|
||||
class Config:
|
||||
env_file = ".env"
|
||||
|
||||
settings = Settings()
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
from datetime import datetime, timedelta
|
||||
from typing import Optional
|
||||
from jose import JWTError, jwt
|
||||
from passlib.context import CryptContext
|
||||
from app.core.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
|
||||
to_encode = data.copy()
|
||||
if expires_delta:
|
||||
expire = datetime.utcnow() + expires_delta
|
||||
else:
|
||||
expire = datetime.utcnow() + timedelta(minutes=15)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)
|
||||
return encoded_jwt
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
from sqlalchemy.orm import Session
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate
|
||||
from app.core.security import get_password_hash
|
||||
|
||||
def get_user(db: Session, user_id: int):
|
||||
return db.query(User).filter(User.id == user_id).first()
|
||||
|
||||
def get_user_by_email(db: Session, email: str):
|
||||
return db.query(User).filter(User.email == email).first()
|
||||
|
||||
def create_user(db: Session, user: UserCreate):
|
||||
hashed_password = get_password_hash(user.password)
|
||||
db_user = User(
|
||||
email=user.email,
|
||||
hashed_password=hashed_password,
|
||||
full_name=user.full_name,
|
||||
graduation_year=user.graduation_year
|
||||
)
|
||||
db.add(db_user)
|
||||
db.commit()
|
||||
db.refresh(db_user)
|
||||
return db_user
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
from app.db.session import Base, engine
|
||||
|
||||
def init_db():
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, declarative_base
|
||||
|
||||
SQLALCHEMY_DATABASE_URL = "sqlite:///./alumni.db"
|
||||
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
||||
)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
# Dependency
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
|
@ -0,0 +1,22 @@
|
|||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.api.v1.api import api_router
|
||||
from app.core.config import settings
|
||||
|
||||
app = FastAPI(
|
||||
title="Alumni API",
|
||||
description="API for Alumni Network",
|
||||
version="1.0.0"
|
||||
)
|
||||
|
||||
# CORS middleware
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"], # Modify in production
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Include API router
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
from app.models.user import User
|
||||
|
||||
__all__ = ["User"]
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
from sqlalchemy import Boolean, Column, Integer, String
|
||||
from app.db.session import Base
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String, unique=True, index=True)
|
||||
hashed_password = Column(String)
|
||||
full_name = Column(String)
|
||||
graduation_year = Column(Integer)
|
||||
is_verified = Column(Boolean, default=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
|
|
@ -0,0 +1 @@
|
|||
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
from pydantic import BaseModel, EmailStr
|
||||
|
||||
class UserBase(BaseModel):
|
||||
email: EmailStr
|
||||
full_name: str
|
||||
graduation_year: int
|
||||
|
||||
class UserCreate(UserBase):
|
||||
password: str
|
||||
|
||||
class User(UserBase):
|
||||
id: int
|
||||
is_verified: bool
|
||||
is_active: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
fastapi>=0.68.0
|
||||
uvicorn>=0.15.0
|
||||
sqlalchemy>=1.4.23
|
||||
pydantic>=1.8.2
|
||||
python-jose[cryptography]>=3.3.0
|
||||
passlib[bcrypt]>=1.7.4
|
||||
python-multipart>=0.0.5
|
||||
alembic>=1.7.1
|
||||
pytest>=6.2.5
|
||||
httpx>=0.19.0
|
||||
python-dotenv>=0.19.0
|
||||
pydantic-settings
|
||||
pydantic[email]
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import uvicorn
|
||||
from app.main import app
|
||||
from app.db.init_db import init_db
|
||||
|
||||
if __name__ == "__main__":
|
||||
init_db() # Initialize database tables
|
||||
uvicorn.run("run:app", host="0.0.0.0", port=8000, reload=True)
|
||||
Loading…
Reference in New Issue