diff --git a/workshop-three/admin.py b/workshop-three/admin.py index e69de29..c81cfc5 100644 --- a/workshop-three/admin.py +++ b/workshop-three/admin.py @@ -0,0 +1,46 @@ +from fastapi import APIRouter, HTTPException, Depends +from fastapi.security import HTTPBasic, HTTPBasicCredentials +from typing import Annotated +from courses import COURSES +from models import Course + + +admin = APIRouter() + +security = HTTPBasic() + + +def authenticate(credentials: Annotated[HTTPBasicCredentials, Depends(security)]): + if not (credentials.username == "admin") or not (credentials.password == "password"): + raise HTTPException( + status_code=401, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Basic"}, + ) + return credentials.username + + +@admin.get("/users/me") +def read_current_user(username: Annotated[HTTPBasicCredentials, Depends(authenticate)]): + return {"username": username} + + +@admin.post("/add-course/{course_id}") +async def add_course(course_id: int, + course: Course, + username: Annotated[HTTPBasicCredentials, Depends(authenticate)] + ) -> Course: + if course_id in COURSES: + raise HTTPException(403, detail="Course already exists") + COURSES[course_id] = course + return COURSES[course_id] + + +@admin.delete("/delete-course/{course_id}") +async def delete_course(course_id: int, + username: Annotated[HTTPBasicCredentials, Depends(authenticate)] + ) -> Course: + if course_id in COURSES: + deleted = COURSES.pop(course_id) + return deleted + raise HTTPException(404, detail="Course not found") \ No newline at end of file diff --git a/workshop-three/main.py b/workshop-three/main.py index 5a94e62..5196c0d 100644 --- a/workshop-three/main.py +++ b/workshop-three/main.py @@ -1,34 +1,15 @@ from fastapi import FastAPI, Path, Query, HTTPException from typing import Optional +from courses import COURSES +from admin import admin app = FastAPI() -COURSES = { - 1: { - "name": "Data Visualization", - "professor": "Dana Willner", - "current_enr": 34, - "max_enr": 35, - }, - 2: { - "name": "Data Structures", - "professor": "Jim Deverick", - "current_enr": 35, - "max_enr": 35, - }, - 3: { - "name": "Computational Problem Solving", - "professor": "Timothy Davis", - "current_enr": 30, - "max_enr": 35, - }, - 4: { - "name": "Intro to Data Science", - "professor": "Dana Willner", - "current_enr": 36, - "max_enr": 35, - } -} +app.include_router(admin, tags=["admin"]) + +my_courses= {} + +my_times={} @app.get("/") diff --git a/workshop-three/models.py b/workshop-three/models.py index e69de29..44dd632 100644 --- a/workshop-three/models.py +++ b/workshop-three/models.py @@ -0,0 +1,18 @@ +from pydantic import BaseModel, Field +from typing import Optional + + +class Time(BaseModel): + days: str = Field(description="Course meeting days", pattern="^[MTWRF]+$") + start: int + end: int + + +class Course(BaseModel): + name: str + professor: str + current_enr: Optional[int] = 0 + max_enr: int + time: Time + +