Spaces:
Runtime error
Runtime error
FEAT: Code for crud completed
Browse filesFiles changed (12)
- main.py+37-11
- src/auth.py+33-24
- src/crud/clearance.py+23-23
- src/crud/devices.py+6-1
- src/crud/students.py+59-61
- src/crud/users.py+31-40
- src/crud/utils.py+6-9
- src/models.py+6-3
- src/routers/admin.py+71-31
- src/routers/rfid.py+5-4
- src/routers/students.py+23-16
- src/routers/token.py+2-1
3 unmodified lines456789101112131415161718192021222324252627283 unmodified linesfrom fastapi.middleware.cors import CORSMiddlewareimport uvicornfrom contextlib import asynccontextmanager# Correctly import the database table creation functionfrom src.database import create_db_and_tables# Import all the necessary routers for the applicationfrom src.routers import students, devices, clearance, token, users, admin@asynccontextmanagerasync def lifespan(app_instance: FastAPI):"""Handles application startup and shutdown events.- On startup, it ensures that all necessary database tables are created.- On shutdown, it can be used for cleanup tasks."""print("Application startup: Initializing...")# Correctly call the function to create database tablescreate_db_and_tables()print("Application startup: Database tables checked/created.")yieldprint("Application shutdown: Cleaning up.")# Initialize the FastAPI application instance with metadata for documentation3 unmodified lines4567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253543 unmodified linesfrom fastapi.middleware.cors import CORSMiddlewareimport uvicornfrom contextlib import asynccontextmanagerimport osfrom fastapi import FastAPIfrom sqlmodel import Sessionfrom starlette.middleware.cors import CORSMiddleware# Correctly import the database table creation functionfrom src.database import create_db_and_tables, engine# Import all the necessary routers for the applicationfrom src.routers import students, devices, clearance, token, users, adminfrom src.crud import users as user_crudfrom src.models import UserCreate, Role@asynccontextmanagerasync def lifespan(app: FastAPI):# On startupprint("Starting up...")create_db_and_tables()# --- Create first superuser ---# This runs only on startup. It checks if an admin exists and creates one if not.# It's best practice to get credentials from environment variables for security.with Session(engine) as session:initial_username = os.getenv("INITIAL_ADMIN_USERNAME", "admin")# Check if the user already existsuser = user_crud.get_user_by_username(session, username=initial_username)if not user:print("Initial admin user not found, creating one...")initial_user = UserCreate(username=initial_username,email=os.getenv("INITIAL_ADMIN_EMAIL", "admin@example.com"),full_name="Initial Admin",password=os.getenv("INITIAL_ADMIN_PASSWORD", "changethispassword"),role=Role.ADMIN)user_crud.create_user(db=session, user=initial_user)print("Initial admin user created successfully.")else:print("Initial admin user already exists.")yield# On shutdownprint("Shutting down...")# Initialize the FastAPI application instance with metadata for documentation
123456789101112131415161710 unmodified lines282930313233343536373839406 unmodified lines474849505152535455565758596061626364656631 unmodified lines9899100from fastapi import Depends, HTTPException, statusfrom fastapi.security import APIKeyHeader, OAuth2PasswordBearerfrom jose import JWTError, jwtfrom sqlmodel import Session, selectfrom typing import List, Optionalfrom typing import List, Optionalfrom datetime import datetime, timedeltafrom src.config import settingsfrom src.database import get_sessionfrom src.crud import users as user_crudfrom src.crud import devices as device_crudfrom src.models import User, Role, Device# --- Configuration ---oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")10 unmodified linesencoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)return encoded_jwt# --- Password Hashing ---def verify_password(plain_password: str, hashed_password: str) -> bool:return settings.PWD_CONTEXT.verify(plain_password, hashed_password)def hash_password(password: str) -> str:return settings.PWD_CONTEXT.hash(password)# --- User Authentication ---def authenticate_user(db: Session, username: str, password: str):"""Authenticate user by username and password."""6 unmodified lines# --- Dependency for API Key Authentication ---def get_api_key(key: str = Depends(api_key_header), db: Session = Depends(get_session)) -> Device:"""Dependency to validate the API key from the x-api-key header.Ensures the device is registered in the database."""db_device = device_crud.get_device_by_api_key(db, api_key=key)if not db_device:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Invalid or missing API Key",)return db_device# --- Dependency for User Authentication and Authorization ---31 unmodified linesreturn userreturn dependency1234567891011121314151610 unmodified lines2728293031326 unmodified lines394041424344454647484950515253545556575831 unmodified lines90919293949596979899100101102103104105106107108109from fastapi import Depends, HTTPException, status, Securityfrom fastapi.security import APIKeyHeader, OAuth2PasswordBearerfrom jose import JWTError, jwtfrom sqlmodel import Session, selectfrom typing import List, Optionalfrom datetime import datetime, timedeltafrom src.config import settingsfrom src.database import get_sessionfrom src.crud import users as user_crudfrom src.crud import devices as device_crudfrom src.models import User, Role, Devicefrom src.crud.utils import verify_password, hash_password# --- Configuration ---oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")10 unmodified linesencoded_jwt = jwt.encode(to_encode, settings.SECRET_KEY, algorithm=settings.ALGORITHM)return encoded_jwt# --- User Authentication ---def authenticate_user(db: Session, username: str, password: str):"""Authenticate user by username and password."""6 unmodified lines# --- Dependency for API Key Authentication ---# def get_api_key(# key: str = Depends(api_key_header), db: Session = Depends(get_session)# ) -> Device:# """# Dependency to validate the API key from the x-api-key header.# Ensures the device is registered in the database.# """# db_device = device_crud.get_device_by_api_key(db, api_key=key)# if not db_device:# raise HTTPException(# status_code=status.HTTP_401_UNAUTHORIZED,# detail="Invalid or missing API Key",# )# return db_device# --- Dependency for User Authentication and Authorization ---31 unmodified linesreturn userreturn dependencyasync def get_api_key(api_key: str = Security(api_key_header), db: Session = Depends(get_session)):"""Validate device API key."""if not api_key:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="API key required")device = device_crud.get_device_by_api_key(db, api_key=api_key)if not device or not device.is_active:raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED,detail="Invalid or inactive API key")return api_key
12345671 unmodified line91011121314151617181920212223242526272829303132333435363738394041424344455 unmodified lines51525354555657from sqlmodel import Session, selectfrom typing import List, Optionalfrom src.models import Student, ClearanceStatus, ClearanceUpdate, Department, ClearanceProcessdef get_clearance_status_for_student(db: Session, student: Student) -> List[ClearanceStatus]:"""1 unmodified line"""return student.clearance_statusesdef update_clearance_status(db: Session, clearance_update: ClearanceUpdate) -> Optional[ClearanceStatus]:"""Updates the clearance status for a student in a specific department.This function performs a direct lookup on the ClearanceStatus table, which ismore efficient than fetching the student and iterating through their statuses."""# First, find the student to ensure they exist.student = db.exec(select(Student).where(Student.matric_no == clearance_update.matric_no)).first()if not student:return None # Student not found# Directly query for the specific clearance status record.statement = select(ClearanceStatus).where(ClearanceStatus.student_id == student.id,ClearanceStatus.department == clearance_update.department)status_to_update = db.exec(statement).first()if not status_to_update:# This case should theoretically not happen if students are created correctly,# but it's a good safeguard.return None# Update the status and commit the change.status_to_update.status = clearance_update.statusdb.add(status_to_update)db.commit()db.refresh(status_to_update)return status_to_updatedef is_student_fully_cleared(db: Session, matric_no: str) -> bool:"""5 unmodified lines# Check if any of the student's clearance statuses are NOT 'approved'.for status in student.clearance_statuses:if status.status != ClearanceProcess.APPROVED:return False# If the loop completes without returning, all statuses are approved.1234561 unmodified line891011121314151617181920212223242526272829303132333435363738394041424344455 unmodified lines51525354555657from sqlmodel import Session, selectfrom typing import List, Optionalfrom src.models import ClearanceStatus, Student, ClearanceUpdate, ClearanceStatusEnumdef get_clearance_status_for_student(db: Session, student: Student) -> List[ClearanceStatus]:"""1 unmodified line"""return student.clearance_statusesdef update_clearance_status(db: Session, update_data: ClearanceUpdate) -> ClearanceStatus | None:"""Updates the clearance status for a specific student and department."""# Find the student firststudent_statement = select(Student).where(Student.matric_no == update_data.matric_no)student = db.exec(student_statement).first()if not student:return None # Student not found# Now find the specific clearance status record for that studentstatus_statement = select(ClearanceStatus).where(ClearanceStatus.student_id == student.id,ClearanceStatus.department == update_data.department)clearance_record = db.exec(status_statement).first()if not clearance_record:# This case should ideally not happen if students are created correctlyreturn None# Update the status and remarksclearance_record.status = update_data.statusif update_data.remarks is not None:clearance_record.remarks = update_data.remarksdb.add(clearance_record)db.commit()db.refresh(clearance_record)return clearance_recorddef is_student_fully_cleared(db: Session, matric_no: str) -> bool:"""5 unmodified lines# Check if any of the student's clearance statuses are NOT 'approved'.for status in student.clearance_statuses:if status.status != ClearanceStatusEnum.APPROVED:return False# If the loop completes without returning, all statuses are approved.
19 unmodified lines202122232425263 unmodified lines30313233343519 unmodified linesdb_device = Device(device_name=device.device_name,department=device.department,api_key=api_key,is_active=True)3 unmodified linesdb.refresh(db_device)return db_devicedef get_device_by_api_key(db: Session, api_key: str) -> Optional[Device]:"""Retrieves an active device by its API key."""statement = select(Device).where(Device.api_key == api_key, Device.is_active == True)19 unmodified lines20212223242526273 unmodified lines3132333435363738394019 unmodified linesdb_device = Device(device_name=device.device_name,location=device.location, # ADD THISdepartment=device.department, # ADD THISapi_key=api_key,is_active=True)3 unmodified linesdb.refresh(db_device)return db_devicedef get_device_by_id(db: Session, device_id: int) -> Optional[Device]:"""Retrieves a device by its primary key ID."""return db.get(Device, device_id)def get_device_by_api_key(db: Session, api_key: str) -> Optional[Device]:"""Retrieves an active device by its API key."""statement = select(Device).where(Device.api_key == api_key, Device.is_active == True)
1234567895 unmodified lines151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798from sqlmodel import Session, selectfrom typing import List, Optionalfrom src.models import Student, StudentCreate, StudentUpdate, RFIDTag, ClearanceStatus, Department, ClearanceProcessfrom src.auth import hash_password# --- Read Operations ---def get_student_by_id(db: Session, student_id: int) -> Optional[Student]:5 unmodified linesreturn db.exec(select(Student).where(Student.matric_no == matric_no)).first()def get_student_by_tag_id(db: Session, tag_id: str) -> Optional[Student]:"""Retrieves a student by their linked RFID tag ID."""statement = select(Student).join(RFIDTag).where(RFIDTag.tag_id == tag_id)return db.exec(statement).first()def get_all_students(db: Session, skip: int = 0, limit: int = 100) -> List[Student]:"""Retrieves a paginated list of all students."""return db.exec(select(Student).offset(skip).limit(limit)).all()# --- Write Operations ---def create_student(db: Session, student: StudentCreate) -> Student:"""Creates a new student and initializes their clearance statuses.This is a critical business logic function. When a student is created,this function automatically creates a 'pending' clearance record for everydepartment defined in the `Department` enum."""hashed_pass = hash_password(student.password)db_student = Student(matric_no=student.matric_no,full_name=student.full_name,email=student.email,hashed_password=hashed_pass,# Department will be set from the StudentCreate modeldepartment=student.department)# --- Auto-populate clearance statuses ---initial_statuses = []for dept in Department:status = ClearanceStatus(department=dept,status=ClearanceProcess.PENDING)initial_statuses.append(status)db_student.clearance_statuses = initial_statuses# --- End of auto-population ---db.add(db_student)db.commit()db.refresh(db_student)return db_studentdef update_student(db: Session, student_id: int, student_update: StudentUpdate) -> Optional[Student]:"""Updates a student's information.If a new password is provided, it will be hashed."""db_student = db.get(Student, student_id)if not db_student:return Noneupdate_data = student_update.model_dump(exclude_unset=True)if "password" in update_data:update_data["hashed_password"] = hash_password(update_data.pop("password"))for key, value in update_data.items():setattr(db_student, key, value)db.add(db_student)db.commit()db.refresh(db_student)return db_studentdef delete_student(db: Session, student_id: int) -> Optional[Student]:"""Deletes a student from the database.All associated clearance statuses and the linked RFID tag will also bedeleted automatically due to the cascade settings in the data models."""db_student = db.get(Student, student_id)if not db_student:return Nonedb.delete(db_student)db.commit()return db_student123456789105 unmodified lines161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596from sqlmodel import Session, selectfrom typing import List, Optionalfrom src.models import (Student, StudentCreate, StudentUpdate, User, Role, ClearanceStatus, ClearanceDepartment, RFIDTag)from src.crud import users as user_crud# --- Read Operations ---def get_student_by_id(db: Session, student_id: int) -> Optional[Student]:5 unmodified linesreturn db.exec(select(Student).where(Student.matric_no == matric_no)).first()def get_student_by_tag_id(db: Session, tag_id: str) -> Optional[Student]:"""Get student by RFID tag ID."""from src.models import RFIDTagtag = db.exec(select(RFIDTag).where(RFIDTag.tag_id == tag_id)).first()if tag and tag.student_id:return db.exec(select(Student).where(Student.id == tag.student_id)).first()return Nonedef get_all_students(db: Session, skip: int = 0, limit: int = 100) -> List[Student]:"""Retrieves a paginated list of all students."""return db.exec(select(Student).offset(skip).limit(limit)).all()# --- Write Operations ---def create_student(db: Session, student_data: StudentCreate) -> Student:"""Creates a new student along with their associated user account for loginand initializes their clearance statuses."""# 1. Create the associated User account for the student to log in# The student's username is their matriculation number.user_for_student = user_crud.UserCreate(username=student_data.matric_no,password=student_data.password,email=student_data.email,full_name=student_data.full_name,role=Role.STUDENT)# This might raise an exception if username/email exists, which is good.db_user = user_crud.create_user(db, user=user_for_student)# 2. Create the Student profiledb_student = Student(full_name=student_data.full_name,matric_no=student_data.matric_no,email=student_data.email,department=student_data.department,# Note: The User linkage is handled via the RFID tag linking process)db.add(db_student)db.commit()db.refresh(db_student)# 3. Initialize all clearance statuses for the new studentfor dept in ClearanceDepartment:status = ClearanceStatus(student_id=db_student.id, department=dept)db.add(status)db.commit()db.refresh(db_student)return db_studentdef update_student(db: Session, student: Student, updates: StudentUpdate) -> Student:"""Updates a student's profile information."""student = get_student_by_id(db, student_id=student.id)if not student:return Noneupdate_data = updates.model_dump(exclude_unset=True)student.sqlmodel_update(update_data)db.add(student)db.commit()db.refresh(student)return studentdef delete_student(db: Session, student_id: int) -> Student | None:"""Deletes a student and their associated clearance records."""student_to_delete = db.get(Student, student_id)if not student_to_delete:return None# Also delete the associated user accountuser_to_delete = user_crud.get_user_by_username(db, username=student_to_delete.matric_no)if user_to_delete:db.delete(user_to_delete)db.delete(student_to_delete)db.commit()return student_to_delete
1 unmodified line234567810 unmodified lines192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384851 unmodified linefrom typing import List, Optionalfrom src.models import User, UserCreate, UserUpdate, RFIDTagfrom src.auth import hash_password# --- Read Operations ---10 unmodified linesreturn db.exec(select(User).where(User.email == email)).first()def get_user_by_tag_id(db: Session, tag_id: str) -> Optional[User]:"""Retrieves a user by their linked RFID tag ID."""statement = select(User).join(RFIDTag).where(RFIDTag.tag_id == tag_id)return db.exec(statement).first()def get_all_users(db: Session, skip: int = 0, limit: int = 100) -> List[User]:"""Retrieves a paginated list of all users."""return db.exec(select(User).offset(skip).limit(limit)).all()# --- Write Operations ---def create_user(db: Session, user: UserCreate) -> User:"""Creates a new user.- Hashes the password before saving.- The router should handle checks for existing username/email to provide clean HTTP errors."""hashed_pass = hash_password(user.password)db_user = User(username=user.username,email=user.email,full_name=user.full_name,hashed_password=hashed_pass,role=user.role)db.add(db_user)db.commit()db.refresh(db_user)return db_userdef update_user(db: Session, user_id: int, user_update: UserUpdate) -> Optional[User]:"""Updates a user's information.- If a new password is provided, it will be hashed."""db_user = db.get(User, user_id)if not db_user:return Noneupdate_data = user_update.model_dump(exclude_unset=True)# Hash password if it's being updatedif "password" in update_data:update_data["hashed_password"] = hash_password(update_data.pop("password"))for key, value in update_data.items():setattr(db_user, key, value)db.add(db_user)db.commit()db.refresh(db_user)return db_userdef delete_user(db: Session, user_id: int) -> Optional[User]:"""Deletes a user from the database.The linked RFID tag will also be deleted due to cascade settings."""db_user = db.get(User, user_id)if not db_user:return Nonedb.delete(db_user)db.commit()return db_user1 unmodified line234567810 unmodified lines192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475761 unmodified linefrom typing import List, Optionalfrom src.models import User, UserCreate, UserUpdate, RFIDTagfrom src.crud.utils import hash_password# --- Read Operations ---10 unmodified linesreturn db.exec(select(User).where(User.email == email)).first()def get_user_by_tag_id(db: Session, tag_id: str) -> Optional[User]:"""Get user by RFID tag ID."""from src.models import RFIDTagtag = db.exec(select(RFIDTag).where(RFIDTag.tag_id == tag_id)).first()if tag and tag.user_id:return db.exec(select(User).where(User.id == tag.user_id)).first()return Nonedef get_all_users(db: Session, skip: int = 0, limit: int = 100) -> List[User]:"""Retrieves a paginated list of all users."""return db.exec(select(User).offset(skip).limit(limit)).all()def create_user(db: Session, user: UserCreate) -> User:"""Creates a new user and hashes their password."""hashed_password = hash_password(user.password)db_user = User(username=user.username,hashed_password=hashed_password,email=user.email,full_name=user.full_name,role=user.role,department=user.department)db.add(db_user)db.commit()db.refresh(db_user)return db_userdef update_user(db: Session, user: User, updates: UserUpdate) -> User:"""Updates a user's information."""user = get_user_by_id(db, user_id=user.id)if not user:return Noneupdate_data = updates.model_dump(exclude_unset=True)if "password" in update_data:# Hash the new password if it's being updatedupdate_data["hashed_password"] = hash_password(update_data.pop("password"))user.sqlmodel_update(update_data)db.add(user)db.commit()db.refresh(user)return userdef delete_user(db: Session, user_id: int) -> User | None:"""Deletes a user by their ID."""user_to_delete = db.get(User, user_id)if not user_to_delete:return Nonedb.delete(user_to_delete)db.commit()# The user object is no longer valid after deletion, so we return the in-memory objectreturn user_to_delete
1234567891011121314"""Utility functions for CRUD operations."""import bcryptdef hash_password(password: str) -> str:"""Hashes a password using bcrypt."""return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')def verify_password(plain_password: str, hashed_password_str: str) -> bool:"""Verifies a plain password against a hashed password."""if not plain_password or not hashed_password_str:return Falsereturn bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password_str.encode('utf-8'))1234567891011"""Utility functions for CRUD operations."""from src.config import settings# --- Password Hashing ---def verify_password(plain_password: str, hashed_password: str) -> bool:return settings.PWD_CONTEXT.verify(plain_password, hashed_password)def hash_password(password: str) -> str:return settings.PWD_CONTEXT.hash(password)
69 unmodified lines70717273747580 unmodified lines1561571581591601611621631641652 unmodified lines16816917017117217317417517617769 unmodified linesdevice_name: str = Field(unique=True, index=True)api_key: str = Field(unique=True, index=True)location: stris_active: bool = Field(default=True)# --- Pydantic Models for API Operations ---80 unmodified linestag_id: strclass RFIDStatusResponse(SQLModel):status: strfull_name: Optional[str] = Nonemessage: Optional[str] = Noneclearance: Optional[str] = Noneclass TagScan(SQLModel):tag_id: str2 unmodified linesclass DeviceCreate(SQLModel):device_name: strlocation: strclass DeviceRead(SQLModel):id: intdevice_name: strapi_key: strlocation: stris_active: bool69 unmodified lines7071727374757680 unmodified lines1571581591601611621631641651662 unmodified lines16917017117217317417517617717817918069 unmodified linesdevice_name: str = Field(unique=True, index=True)api_key: str = Field(unique=True, index=True)location: strdepartment: Department # ADD THIS - referenced in devices.py CRUDis_active: bool = Field(default=True)# --- Pydantic Models for API Operations ---80 unmodified linestag_id: strclass RFIDStatusResponse(SQLModel):status: str # "found" or "unregistered" # "found" or "unregistered"full_name: Optional[str] = Noneentity_type: Optional[str] = None # "Student", "Admin", "Staff"None # "Student", "Admin", "Staff"clearance_status: Optional[str] = None # "Fully Cleared", "Pending Clearance", "N/A" = None # "Fully Cleared", "Pending Clearance", "N/A"class TagScan(SQLModel):tag_id: str2 unmodified linesclass DeviceCreate(SQLModel):device_name: strlocation: strdepartment: Department # ADD THISclass DeviceRead(SQLModel):id: intdevice_name: strapi_key: strlocation: strdepartment: Department # ADD THISis_active: bool
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 unmodified lines1281291301311321331347 unmodified lines142143144145146147148149150151152153from fastapi import APIRouter, Depends, HTTPException, status, Queryfrom sqlmodel import Sessionfrom typing import List, Optional, Dictfrom src.database import get_sessionfrom src.auth import get_current_active_userfrom src.models import (User, UserCreate, UserRead, UserUpdate, Role,Student, StudentCreate, StudentRead, StudentUpdate, StudentReadWithClearance,TagLink, RFIDTagRead, TagScan,Device, DeviceCreate, DeviceRead)from src.crud import users as user_crudfrom src.crud import students as student_crudfrom src.crud import tag_linking as tag_crudfrom src.crud import devices as device_crud# In-memory storage for last scanned tags by an admin.# Key: admin user ID, Value: last scanned tag ID.# This is simple and effective for a non-distributed system.admin_scanned_tags: Dict[int, str] = {}# Define the router.# It's accessible to both Admins and Staff, providing a unified management panel.router = APIRouter(prefix="/admin",tags=["Administration"],dependencies=[Depends(get_current_active_user(required_roles=[Role.ADMIN, Role.STAFF]))],)# --- Admin Tag Scanning for Web UI ---@router.post("/tags/scan", status_code=status.HTTP_204_NO_CONTENT)def report_scanned_tag(scan_data: TagScan,current_user: User = Depends(get_current_active_user(required_roles=[Role.ADMIN, Role.STAFF]))):"""(Admin & Staff) Endpoint for the admin's desk RFID reader to report a scanned tag.The backend stores this tag ID temporarily against the admin's user ID."""admin_scanned_tags[current_user.id] = scan_data.tag_idreturn@router.get("/tags/scan", response_model=TagScan)def retrieve_scanned_tag(current_user: User = Depends(get_current_active_user(required_roles=[Role.ADMIN, Role.STAFF]))):"""(Admin & Staff) Endpoint for the admin's web portal to retrieve the last scanned tag.The tag is removed after being retrieved to prevent re-use."""tag_id = admin_scanned_tags.pop(current_user.id, None)if not tag_id:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No tag has been scanned recently.")return TagScan(tag_id=tag_id)# --- Student Management (Admin + Staff) ---@router.post("/students/", response_model=StudentReadWithClearance, status_code=status.HTTP_201_CREATED)def create_student(student: StudentCreate, db: Session = Depends(get_session)):"""(Admin & Staff) Creates a new student and initializes their clearance status."""64 unmodified lines"""(Admin & Staff) Unlinks an RFID tag, making it available again."""deleted_tag = tag_crud.unlink_tag(db, tag_id)if not deleted_tag:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="RFID Tag not found.")return deleted_tag7 unmodified linesdetail="This action requires Super Admin privileges.")@router.post("/users/", response_model=UserRead, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_super_admin)])def create_user(user: UserCreate, db: Session = Depends(get_session)):"""(Super Admin Only) Creates a new user (Staff or Admin)."""db_user = user_crud.get_user_by_username(db, username=user.username)if db_user:raise HTTPException(status_code=400, detail="Username already registered")return user_crud.create_user(db=db, user=user)@router.get("/users/", response_model=List[UserRead], dependencies=[Depends(require_super_admin)])1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939464 unmodified lines1591601611621631641651661671687 unmodified lines176177178179180181182183184185186187188189190191192193from fastapi import APIRouter, Depends, HTTPException, status, Queryfrom sqlmodel import Session, SQLModelfrom typing import List, Optional, Dictfrom src.database import get_sessionfrom src.auth import get_current_active_user, get_api_keyfrom src.models import (User, UserCreate, UserRead, UserUpdate, Role,Student, StudentCreate, StudentReadWithClearance, StudentUpdate, StudentRead,TagLink, RFIDTagRead, Device, DeviceCreate, DeviceRead, TagScan)from src.crud import users as user_crudfrom src.crud import students as student_crudfrom src.crud import tag_linking as tag_crudfrom src.crud import devices as device_crud# --- New State Management for Secure Admin Scanning ---# Maps a device's API key to the admin user ID who activated it.# This "activates" a scanner for a specific admin.activated_scanners: Dict[str, int] = {}# Stores the last tag scanned by a device, keyed by the admin ID who was waiting.admin_scanned_tags: Dict[int, str] = {}# Define the main administrative routerrouter = APIRouter(prefix="/admin",tags=["Administration"],dependencies=[Depends(get_current_active_user(required_roles=[Role.ADMIN, Role.STAFF]))],)# --- New Secure Scanning Workflow ---class ActivationRequest(SQLModel):device_id: int@router.post("/scanners/activate", status_code=status.HTTP_204_NO_CONTENT)def activate_admin_scanner(activation: ActivationRequest,db: Session = Depends(get_session),current_user: User = Depends(get_current_active_user(required_roles=[Role.ADMIN, Role.STAFF]))):"""STEP 1 (Browser): Admin clicks "Scan Card" in the UI.The browser calls this endpoint to 'arm' their designated desk scanner."""device = device_crud.get_device_by_id(db, device_id=activation.device_id)if not device:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Device not found.")# Map the device's API key to the currently logged-in admin's ID.activated_scanners[device.api_key] = current_user.idreturn@router.post("/scanners/scan", status_code=status.HTTP_204_NO_CONTENT)def receive_scan_from_activated_device(scan_data: TagScan,api_key: str = Depends(get_api_key) # Device authenticates with its API Key):"""STEP 2 (Device): The ESP32 device sends the scanned tag to this endpoint.This endpoint is protected by the device's API Key."""# Check if this device was activated by an admin.admin_id = activated_scanners.pop(api_key, None)if admin_id is None:raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="This scanner has not been activated for a scan.")# Store the scanned tag against the admin who was waiting for it.admin_scanned_tags[admin_id] = scan_data.tag_idreturn@router.get("/scanners/retrieve", response_model=TagScan)def retrieve_scanned_tag_for_ui(current_user: User = Depends(get_current_active_user(required_roles=[Role.ADMIN, Role.STAFF]))):"""STEP 3 (Browser): The browser polls this endpoint to get the tag IDthat the device reported in STEP 2."""tag_id = admin_scanned_tags.pop(current_user.id, None)if not tag_id:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No tag has been scanned by the activated device yet.")return TagScan(tag_id=tag_id)# --- All other administrative endpoints remain the same ---# ... (Student Management, User Management, etc.) ...@router.post("/students/", response_model=StudentReadWithClearance, status_code=status.HTTP_201_CREATED)def create_student(student: StudentCreate, db: Session = Depends(get_session)):"""(Admin & Staff) Creates a new student and initializes their clearance status."""64 unmodified lines"""(Admin & Staff) Unlinks an RFID tag, making it available again."""deleted_tag = tag_crud.unlink_tag(db, tag_id)if not deleted_tag:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail="RFID Tag not found.")return deleted_tag7 unmodified linesdetail="This action requires Super Admin privileges.")@router.post("/users/",response_model=UserRead,status_code=status.HTTP_201_CREATED,dependencies=[Depends(get_current_active_user(required_roles=[Role.ADMIN]))])def create_user_as_admin(user: UserCreate, db: Session = Depends(get_session)):"""(Super Admin Only) Creates a new user (admin or staff)."""if user_crud.get_user_by_username(db, username=user.username):raise HTTPException(status_code=400, detail="Username already registered.")if user_crud.get_user_by_email(db, email=user.email):raise HTTPException(status_code=400, detail="Email already registered.")return user_crud.create_user(db=db, user=user)@router.get("/users/", response_model=List[UserRead], dependencies=[Depends(require_super_admin)])
3 unmodified lines4567891017 unmodified lines28293031323334353610 unmodified lines474849505152533 unmodified linesfrom src.database import get_sessionfrom src.auth import get_api_keyfrom src.models import RFIDStatusResponse, RFIDScanRequestfrom src.crud import students as student_crudfrom src.crud import users as user_crud17 unmodified lines# 1. Check if the tag belongs to a studentstudent = student_crud.get_student_by_tag_id(db, tag_id=tag_id)if student:# Check overall clearance statusis_cleared = all(status.status == "approved" for status in student.clearance_statuses)clearance_status_str = "Fully Cleared" if is_cleared else "Pending Clearance"10 unmodified linesreturn RFIDStatusResponse(status="found",full_name=user.full_name,entity_type=user.role.value, # e.g. "Admin" or "Staff"clearance_status="N/A",)3 unmodified lines4567891017 unmodified lines2829303132333435363710 unmodified lines484950515253543 unmodified linesfrom src.database import get_sessionfrom src.auth import get_api_keyfrom src.models import RFIDStatusResponse, RFIDScanRequest, ClearanceStatusEnumfrom src.crud import students as student_crudfrom src.crud import users as user_crud17 unmodified lines# 1. Check if the tag belongs to a studentstudent = student_crud.get_student_by_tag_id(db, tag_id=tag_id)if student:# Check overall clearance status using proper enum comparisonis_cleared = all(clearance.status == ClearanceStatusEnum.APPROVEDfor clearance in student.clearance_statuses)clearance_status_str = "Fully Cleared" if is_cleared else "Pending Clearance"10 unmodified linesreturn RFIDStatusResponse(status="found",full_name=user.full_name,entity_type=user.role.value.title(), # "Admin" or "Staff"clearance_status="N/A",)
1234567891011121314151617181920212223242526272829from fastapi import APIRouter, Depends, HTTPException, statusfrom sqlmodel import Sessionfrom src.database import get_sessionfrom src.auth import get_current_active_userfrom src.models import Student, StudentReadWithClearancerouter = APIRouter(prefix="/students",tags=["Students"],)@router.get("/me", response_model=StudentReadWithClearance)def read_student_me(# This dependency ensures the user is an authenticated student# and injects their database object into the 'current_student' parameter.current_student: Student = Depends(get_current_active_user)):"""Endpoint for a logged-in student to retrieve their own profileand clearance information. The user is identified via their JWT token."""# Because the dependency returns the full student object, we can just return it.# No need for another database call.if not current_student:# This should not happen if the dependency is set up correctlyraise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Student not found")return current_student123456789101112131415161718192021222324252627282930313233343536from fastapi import APIRouter, Depends, HTTPException, statusfrom sqlmodel import Session, SQLModelfrom src.auth import get_current_active_userfrom src.database import get_sessionfrom src.models import StudentReadWithClearance# This is the new request body model for the POST request.class StudentLookupRequest(SQLModel):matric_no: strrouter = APIRouter(prefix="/students",tags=["Students"],# This endpoint still requires a user to be logged in.dependencies=[Depends(get_current_active_user)])@router.post("/lookup", response_model=StudentReadWithClearance)def lookup_student_by_matric_no(request: StudentLookupRequest,db: Session = Depends(get_session)):"""Endpoint for a logged-in user to retrieve a student's profileand clearance information by providing their matriculation number."""student = student_crud.get_student_by_matric_no(db=db, matric_no=request.matric_no)if not student:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail="Student with the provided matriculation number not found.")return student
33 unmodified lines343536373839404133 unmodified lines# Create the JWT tokenaccess_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)access_token = create_access_token(data={"sub": user.email}, expires_delta=access_token_expires)return {"access_token": access_token, "token_type": "bearer"}33 unmodified lines34353637383940414233 unmodified lines# Create the JWT tokenaccess_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)# FIX: Use username instead of emailaccess_token = create_access_token(data={"sub": user.username}, expires_delta=access_token_expires # CHANGED from user.email)return {"access_token": access_token, "token_type": "bearer"}
main.py+37-11
src/auth.py+33-24
src/crud/clearance.py+23-23
src/crud/devices.py+6-1
src/crud/students.py+59-61
src/crud/users.py+31-40
src/crud/utils.py+6-9
src/models.py+6-3
src/routers/admin.py+71-31
src/routers/rfid.py+5-4
src/routers/students.py+23-16
src/routers/token.py+2-1