Fix dependency installation error and fix linting issues
This commit is contained in:
parent
d776b59b82
commit
aab6d7f29a
110
alembic.ini
Normal file
110
alembic.ini
Normal file
@ -0,0 +1,110 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts
|
||||||
|
script_location = migrations
|
||||||
|
|
||||||
|
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||||
|
# Uncomment the line below if you want the files to be prepended with date and time
|
||||||
|
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
|
||||||
|
# for all available tokens
|
||||||
|
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# sys.path path, will be prepended to sys.path if present.
|
||||||
|
# defaults to the current working directory.
|
||||||
|
prepend_sys_path = .
|
||||||
|
|
||||||
|
# timezone to use when rendering the date within the migration file
|
||||||
|
# as well as the filename.
|
||||||
|
# If specified, requires the python-dateutil library that can be
|
||||||
|
# installed by adding `alembic[tz]` to the pip requirements
|
||||||
|
# string value is passed to dateutil.tz.gettz()
|
||||||
|
# leave blank for localtime
|
||||||
|
# timezone =
|
||||||
|
|
||||||
|
# max length of characters to apply to the
|
||||||
|
# "slug" field
|
||||||
|
# truncate_slug_length = 40
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
# set to 'true' to allow .pyc and .pyo files without
|
||||||
|
# a source .py file to be detected as revisions in the
|
||||||
|
# versions/ directory
|
||||||
|
# sourceless = false
|
||||||
|
|
||||||
|
# version location specification; This defaults
|
||||||
|
# to migrations/versions. When using multiple version
|
||||||
|
# directories, initial revisions must be specified with --version-path.
|
||||||
|
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||||
|
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
|
||||||
|
|
||||||
|
# version path separator; As mentioned above, this is the character used to split
|
||||||
|
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||||
|
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||||
|
# Valid values for version_path_separator are:
|
||||||
|
#
|
||||||
|
# version_path_separator = :
|
||||||
|
# version_path_separator = ;
|
||||||
|
# version_path_separator = space
|
||||||
|
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||||
|
|
||||||
|
# set to 'true' to search source files recursively
|
||||||
|
# in each "version_locations" directory
|
||||||
|
# new in Alembic version 1.10
|
||||||
|
# recursive_version_locations = false
|
||||||
|
|
||||||
|
# the output encoding used when revision files
|
||||||
|
# are written from script.py.mako
|
||||||
|
# output_encoding = utf-8
|
||||||
|
|
||||||
|
sqlalchemy.url = sqlite:////app/storage/db/db.sqlite
|
||||||
|
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
# post_write_hooks defines scripts or Python functions that are run
|
||||||
|
# on newly generated revision scripts. See the documentation for further
|
||||||
|
# detail and examples
|
||||||
|
|
||||||
|
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||||
|
# hooks = black
|
||||||
|
# black.type = console_scripts
|
||||||
|
# black.entrypoint = black
|
||||||
|
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||||
|
|
||||||
|
# Logging configuration
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/__init__.py
Normal file
0
app/api/v1/__init__.py
Normal file
0
app/api/v1/__init__.py
Normal file
12
app/api/v1/api.py
Normal file
12
app/api/v1/api.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
from fastapi import APIRouter
|
||||||
|
|
||||||
|
from app.api.v1.endpoints import login, users, roles, students, teachers, courses, enrollments
|
||||||
|
|
||||||
|
api_router = APIRouter()
|
||||||
|
api_router.include_router(login.router, tags=["login"])
|
||||||
|
api_router.include_router(users.router, prefix="/users", tags=["users"])
|
||||||
|
api_router.include_router(roles.router, prefix="/roles", tags=["roles"])
|
||||||
|
api_router.include_router(students.router, prefix="/students", tags=["students"])
|
||||||
|
api_router.include_router(teachers.router, prefix="/teachers", tags=["teachers"])
|
||||||
|
api_router.include_router(courses.router, prefix="/courses", tags=["courses"])
|
||||||
|
api_router.include_router(enrollments.router, prefix="/enrollments", tags=["enrollments"])
|
62
app/api/v1/deps.py
Normal file
62
app/api/v1/deps.py
Normal file
@ -0,0 +1,62 @@
|
|||||||
|
from typing import List
|
||||||
|
|
||||||
|
from fastapi import Depends, HTTPException, status
|
||||||
|
from fastapi.security import OAuth2PasswordBearer
|
||||||
|
from jose import jwt
|
||||||
|
from pydantic import ValidationError
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import crud, models, schemas
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.db.session import get_db
|
||||||
|
|
||||||
|
oauth2_scheme = OAuth2PasswordBearer(
|
||||||
|
tokenUrl=f"{settings.API_V1_STR}/login/access-token"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_user(
|
||||||
|
db: Session = Depends(get_db), token: str = Depends(oauth2_scheme)
|
||||||
|
) -> models.User:
|
||||||
|
try:
|
||||||
|
payload = jwt.decode(
|
||||||
|
token, settings.JWT_SECRET_KEY, algorithms=[settings.JWT_ALGORITHM]
|
||||||
|
)
|
||||||
|
token_data = schemas.token.TokenPayload(**payload)
|
||||||
|
except (jwt.JWTError, ValidationError):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Could not validate credentials",
|
||||||
|
)
|
||||||
|
user = crud.user.get(db, id=token_data.sub)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(status_code=404, detail="User not found")
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def get_current_active_user(
|
||||||
|
current_user: models.User = Depends(get_current_user),
|
||||||
|
) -> models.User:
|
||||||
|
if not crud.user.is_active(current_user):
|
||||||
|
raise HTTPException(status_code=400, detail="Inactive user")
|
||||||
|
return current_user
|
||||||
|
|
||||||
|
|
||||||
|
def check_role(
|
||||||
|
allowed_roles: List[str], user: models.User = Depends(get_current_active_user), db: Session = Depends(get_db)
|
||||||
|
) -> models.User:
|
||||||
|
role = db.query(models.Role).filter(models.Role.id == user.role_id).first()
|
||||||
|
if not role or role.name not in allowed_roles:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail=f"Operation not permitted. Required roles: {', '.join(allowed_roles)}",
|
||||||
|
)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
def get_admin_user(db: Session = Depends(get_db), user: models.User = Depends(get_current_active_user)) -> models.User:
|
||||||
|
return check_role(["admin"], user, db)
|
||||||
|
|
||||||
|
|
||||||
|
def get_teacher_user(db: Session = Depends(get_db), user: models.User = Depends(get_current_active_user)) -> models.User:
|
||||||
|
return check_role(["admin", "teacher"], user, db)
|
0
app/api/v1/endpoints/__init__.py
Normal file
0
app/api/v1/endpoints/__init__.py
Normal file
41
app/api/v1/endpoints/login.py
Normal file
41
app/api/v1/endpoints/login.py
Normal file
@ -0,0 +1,41 @@
|
|||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from fastapi.security import OAuth2PasswordRequestForm
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import crud
|
||||||
|
from app.api.v1.deps import get_db
|
||||||
|
from app.core.security import create_access_token
|
||||||
|
from app.models.role import Role
|
||||||
|
from app.schemas.token import Token
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/login/access-token", response_model=Token)
|
||||||
|
def login_access_token(
|
||||||
|
db: Session = Depends(get_db), form_data: OAuth2PasswordRequestForm = Depends()
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
OAuth2 compatible token login, get an access token for future requests
|
||||||
|
"""
|
||||||
|
user = crud.user.authenticate(
|
||||||
|
db, username=form_data.username, password=form_data.password
|
||||||
|
)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||||
|
detail="Incorrect username or password",
|
||||||
|
)
|
||||||
|
if not crud.user.is_active(user):
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_401_UNAUTHORIZED, detail="Inactive user"
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get the role name for the user
|
||||||
|
role_obj = db.query(Role).filter(Role.id == user.role_id).first()
|
||||||
|
role_name = role_obj.name if role_obj else "user"
|
||||||
|
|
||||||
|
access_token = create_access_token(user.id, role=role_name)
|
||||||
|
return {"access_token": access_token, "token_type": "bearer"}
|
122
app/api/v1/endpoints/roles.py
Normal file
122
app/api/v1/endpoints/roles.py
Normal file
@ -0,0 +1,122 @@
|
|||||||
|
from typing import Any, List
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, status
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import crud, models, schemas
|
||||||
|
from app.api.v1 import deps
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[schemas.Role])
|
||||||
|
def read_roles(
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Retrieve roles.
|
||||||
|
"""
|
||||||
|
roles = crud.role.get_multi(db, skip=skip, limit=limit)
|
||||||
|
return roles
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=schemas.Role)
|
||||||
|
def create_role(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
role_in: schemas.RoleCreate,
|
||||||
|
current_user: models.User = Depends(deps.get_admin_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Create new role.
|
||||||
|
"""
|
||||||
|
role = crud.role.get_by_name(db, name=role_in.name)
|
||||||
|
if role:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="The role with this name already exists in the system.",
|
||||||
|
)
|
||||||
|
role = crud.role.create(db, obj_in=role_in)
|
||||||
|
return role
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{role_id}", response_model=schemas.Role)
|
||||||
|
def read_role(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
role_id: int,
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Get role by ID.
|
||||||
|
"""
|
||||||
|
role = crud.role.get(db, id=role_id)
|
||||||
|
if not role:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="The role with this ID does not exist in the system",
|
||||||
|
)
|
||||||
|
return role
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{role_id}", response_model=schemas.Role)
|
||||||
|
def update_role(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
role_id: int,
|
||||||
|
role_in: schemas.RoleUpdate,
|
||||||
|
current_user: models.User = Depends(deps.get_admin_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update a role.
|
||||||
|
"""
|
||||||
|
role = crud.role.get(db, id=role_id)
|
||||||
|
if not role:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="The role with this ID does not exist in the system",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check if trying to update to an existing name
|
||||||
|
if role_in.name and role_in.name != role.name:
|
||||||
|
existing_role = crud.role.get_by_name(db, name=role_in.name)
|
||||||
|
if existing_role:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="The role with this name already exists in the system.",
|
||||||
|
)
|
||||||
|
|
||||||
|
role = crud.role.update(db, db_obj=role, obj_in=role_in)
|
||||||
|
return role
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{role_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||||
|
def delete_role(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
role_id: int,
|
||||||
|
current_user: models.User = Depends(deps.get_admin_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Delete a role.
|
||||||
|
"""
|
||||||
|
role = crud.role.get(db, id=role_id)
|
||||||
|
if not role:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="The role with this ID does not exist in the system",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Check if there are users with this role
|
||||||
|
users_with_role = db.query(models.User).filter(models.User.role_id == role_id).count()
|
||||||
|
if users_with_role > 0:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Cannot delete role with ID {role_id}. There are {users_with_role} users with this role.",
|
||||||
|
)
|
||||||
|
|
||||||
|
crud.role.remove(db, id=role_id)
|
||||||
|
return None
|
166
app/api/v1/endpoints/users.py
Normal file
166
app/api/v1/endpoints/users.py
Normal file
@ -0,0 +1,166 @@
|
|||||||
|
from typing import Any, List
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Body, Depends, HTTPException, status
|
||||||
|
from fastapi.encoders import jsonable_encoder
|
||||||
|
from pydantic import EmailStr
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import crud, models, schemas
|
||||||
|
from app.api.v1 import deps
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/", response_model=List[schemas.User])
|
||||||
|
def read_users(
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
skip: int = 0,
|
||||||
|
limit: int = 100,
|
||||||
|
current_user: models.User = Depends(deps.get_admin_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Retrieve users.
|
||||||
|
"""
|
||||||
|
users = crud.user.get_multi(db, skip=skip, limit=limit)
|
||||||
|
return users
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/", response_model=schemas.User)
|
||||||
|
def create_user(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
user_in: schemas.UserCreate,
|
||||||
|
current_user: models.User = Depends(deps.get_admin_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Create new user.
|
||||||
|
"""
|
||||||
|
user = crud.user.get_by_email(db, email=user_in.email)
|
||||||
|
if user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="The user with this email already exists in the system.",
|
||||||
|
)
|
||||||
|
|
||||||
|
user = crud.user.get_by_username(db, username=user_in.username)
|
||||||
|
if user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="The user with this username already exists in the system.",
|
||||||
|
)
|
||||||
|
|
||||||
|
user = crud.user.create(db, obj_in=user_in)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/me", response_model=schemas.User)
|
||||||
|
def update_user_me(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
password: str = Body(None),
|
||||||
|
first_name: str = Body(None),
|
||||||
|
last_name: str = Body(None),
|
||||||
|
email: EmailStr = Body(None),
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update own user.
|
||||||
|
"""
|
||||||
|
current_user_data = jsonable_encoder(current_user)
|
||||||
|
user_in = schemas.UserUpdate(**current_user_data)
|
||||||
|
if password is not None:
|
||||||
|
user_in.password = password
|
||||||
|
if first_name is not None:
|
||||||
|
user_in.first_name = first_name
|
||||||
|
if last_name is not None:
|
||||||
|
user_in.last_name = last_name
|
||||||
|
if email is not None:
|
||||||
|
user_in.email = email
|
||||||
|
user = crud.user.update(db, db_obj=current_user, obj_in=user_in)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/me", response_model=schemas.User)
|
||||||
|
def read_user_me(
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Get current user.
|
||||||
|
"""
|
||||||
|
return current_user
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{user_id}", response_model=schemas.User)
|
||||||
|
def read_user_by_id(
|
||||||
|
user_id: int,
|
||||||
|
current_user: models.User = Depends(deps.get_current_active_user),
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Get a specific user by id.
|
||||||
|
"""
|
||||||
|
# Only admins can get user details except their own
|
||||||
|
role = db.query(models.Role).filter(models.Role.id == current_user.role_id).first()
|
||||||
|
if role.name != "admin" and current_user.id != user_id:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="The user doesn't have enough privileges",
|
||||||
|
)
|
||||||
|
|
||||||
|
user = crud.user.get(db, id=user_id)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="The user with this id does not exist in the system",
|
||||||
|
)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@router.put("/{user_id}", response_model=schemas.User)
|
||||||
|
def update_user(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
user_id: int,
|
||||||
|
user_in: schemas.UserUpdate,
|
||||||
|
current_user: models.User = Depends(deps.get_admin_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Update a user.
|
||||||
|
"""
|
||||||
|
user = crud.user.get(db, id=user_id)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="The user with this id does not exist in the system",
|
||||||
|
)
|
||||||
|
user = crud.user.update(db, db_obj=user, obj_in=user_in)
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT, response_model=None)
|
||||||
|
def delete_user(
|
||||||
|
*,
|
||||||
|
db: Session = Depends(deps.get_db),
|
||||||
|
user_id: int,
|
||||||
|
current_user: models.User = Depends(deps.get_admin_user),
|
||||||
|
) -> Any:
|
||||||
|
"""
|
||||||
|
Delete a user.
|
||||||
|
"""
|
||||||
|
user = crud.user.get(db, id=user_id)
|
||||||
|
if not user:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=404,
|
||||||
|
detail="The user with this id does not exist in the system",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Prevent deletion of the current user
|
||||||
|
if user.id == current_user.id:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Users cannot delete themselves",
|
||||||
|
)
|
||||||
|
|
||||||
|
crud.user.remove(db, id=user_id)
|
||||||
|
return None
|
0
app/core/__init__.py
Normal file
0
app/core/__init__.py
Normal file
37
app/core/config.py
Normal file
37
app/core/config.py
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
import os
|
||||||
|
import secrets
|
||||||
|
from typing import List, Union
|
||||||
|
|
||||||
|
from pydantic import AnyHttpUrl, field_validator
|
||||||
|
from pydantic_settings import BaseSettings
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
API_V1_STR: str = "/api/v1"
|
||||||
|
SECRET_KEY: str = os.environ.get("SECRET_KEY", secrets.token_urlsafe(32))
|
||||||
|
# 60 minutes * 24 hours * 8 days = 8 days
|
||||||
|
ACCESS_TOKEN_EXPIRE_MINUTES: int = 60 * 24 * 8
|
||||||
|
|
||||||
|
# CORS configuration
|
||||||
|
BACKEND_CORS_ORIGINS: List[AnyHttpUrl] = []
|
||||||
|
|
||||||
|
@field_validator("BACKEND_CORS_ORIGINS", mode="before")
|
||||||
|
def assemble_cors_origins(cls, v: Union[str, List[str]]) -> Union[List[str], str]:
|
||||||
|
if isinstance(v, str) and not v.startswith("["):
|
||||||
|
return [i.strip() for i in v.split(",")]
|
||||||
|
elif isinstance(v, (list, str)):
|
||||||
|
return v
|
||||||
|
raise ValueError(v)
|
||||||
|
|
||||||
|
PROJECT_NAME: str = "Role-Based School Management System"
|
||||||
|
|
||||||
|
# Database configuration
|
||||||
|
SQLALCHEMY_DATABASE_URL: str = os.environ.get(
|
||||||
|
"DATABASE_URL", "sqlite:////app/storage/db/db.sqlite"
|
||||||
|
)
|
||||||
|
|
||||||
|
# JWT token configuration
|
||||||
|
JWT_SECRET_KEY: str = os.environ.get("JWT_SECRET_KEY", SECRET_KEY)
|
||||||
|
JWT_ALGORITHM: str = "HS256"
|
||||||
|
|
||||||
|
settings = Settings()
|
31
app/core/security.py
Normal file
31
app/core/security.py
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
from datetime import datetime, timedelta
|
||||||
|
from typing import Any, Union
|
||||||
|
|
||||||
|
from jose import jwt
|
||||||
|
from passlib.context import CryptContext
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||||
|
|
||||||
|
|
||||||
|
def create_access_token(
|
||||||
|
subject: Union[str, Any], role: str, expires_delta: timedelta = None
|
||||||
|
) -> str:
|
||||||
|
if expires_delta:
|
||||||
|
expire = datetime.utcnow() + expires_delta
|
||||||
|
else:
|
||||||
|
expire = datetime.utcnow() + timedelta(
|
||||||
|
minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES
|
||||||
|
)
|
||||||
|
to_encode = {"exp": expire, "sub": str(subject), "role": role}
|
||||||
|
encoded_jwt = jwt.encode(to_encode, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||||
|
return encoded_jwt
|
||||||
|
|
||||||
|
|
||||||
|
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)
|
5
app/crud/__init__.py
Normal file
5
app/crud/__init__.py
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
from app.crud.crud_user import user
|
||||||
|
from app.crud.crud_role import role
|
||||||
|
from app.crud.crud_student import student
|
||||||
|
|
||||||
|
__all__ = ["user", "role", "student"]
|
66
app/crud/base.py
Normal file
66
app/crud/base.py
Normal file
@ -0,0 +1,66 @@
|
|||||||
|
from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union
|
||||||
|
|
||||||
|
from fastapi.encoders import jsonable_encoder
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
ModelType = TypeVar("ModelType", bound=Base)
|
||||||
|
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
|
||||||
|
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
|
||||||
|
|
||||||
|
|
||||||
|
class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
|
||||||
|
def __init__(self, model: Type[ModelType]):
|
||||||
|
"""
|
||||||
|
CRUD object with default methods to Create, Read, Update, Delete (CRUD).
|
||||||
|
|
||||||
|
**Parameters**
|
||||||
|
|
||||||
|
* `model`: A SQLAlchemy model class
|
||||||
|
* `schema`: A Pydantic model (schema) class
|
||||||
|
"""
|
||||||
|
self.model = model
|
||||||
|
|
||||||
|
def get(self, db: Session, id: Any) -> Optional[ModelType]:
|
||||||
|
return db.query(self.model).filter(self.model.id == id).first()
|
||||||
|
|
||||||
|
def get_multi(
|
||||||
|
self, db: Session, *, skip: int = 0, limit: int = 100
|
||||||
|
) -> List[ModelType]:
|
||||||
|
return db.query(self.model).offset(skip).limit(limit).all()
|
||||||
|
|
||||||
|
def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType:
|
||||||
|
obj_in_data = jsonable_encoder(obj_in)
|
||||||
|
db_obj = self.model(**obj_in_data)
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
def update(
|
||||||
|
self,
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
db_obj: ModelType,
|
||||||
|
obj_in: Union[UpdateSchemaType, Dict[str, Any]]
|
||||||
|
) -> ModelType:
|
||||||
|
obj_data = jsonable_encoder(db_obj)
|
||||||
|
if isinstance(obj_in, dict):
|
||||||
|
update_data = obj_in
|
||||||
|
else:
|
||||||
|
update_data = obj_in.dict(exclude_unset=True)
|
||||||
|
for field in obj_data:
|
||||||
|
if field in update_data:
|
||||||
|
setattr(db_obj, field, update_data[field])
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
def remove(self, db: Session, *, id: int) -> ModelType:
|
||||||
|
obj = db.query(self.model).get(id)
|
||||||
|
db.delete(obj)
|
||||||
|
db.commit()
|
||||||
|
return obj
|
15
app/crud/crud_role.py
Normal file
15
app/crud/crud_role.py
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
from typing import Optional
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.crud.base import CRUDBase
|
||||||
|
from app.models.role import Role
|
||||||
|
from app.schemas.role import RoleCreate, RoleUpdate
|
||||||
|
|
||||||
|
|
||||||
|
class CRUDRole(CRUDBase[Role, RoleCreate, RoleUpdate]):
|
||||||
|
def get_by_name(self, db: Session, *, name: str) -> Optional[Role]:
|
||||||
|
return db.query(Role).filter(Role.name == name).first()
|
||||||
|
|
||||||
|
|
||||||
|
role = CRUDRole(Role)
|
21
app/crud/crud_student.py
Normal file
21
app/crud/crud_student.py
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
from typing import List, Optional
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.crud.base import CRUDBase
|
||||||
|
from app.models.student import Student
|
||||||
|
from app.schemas.student import StudentCreate, StudentUpdate
|
||||||
|
|
||||||
|
|
||||||
|
class CRUDStudent(CRUDBase[Student, StudentCreate, StudentUpdate]):
|
||||||
|
def get_by_student_id(self, db: Session, *, student_id: str) -> Optional[Student]:
|
||||||
|
return db.query(Student).filter(Student.student_id == student_id).first()
|
||||||
|
|
||||||
|
def get_by_user_id(self, db: Session, *, user_id: int) -> Optional[Student]:
|
||||||
|
return db.query(Student).filter(Student.user_id == user_id).first()
|
||||||
|
|
||||||
|
def get_by_grade_level(self, db: Session, *, grade_level: str) -> List[Student]:
|
||||||
|
return db.query(Student).filter(Student.grade_level == grade_level).all()
|
||||||
|
|
||||||
|
|
||||||
|
student = CRUDStudent(Student)
|
58
app/crud/crud_user.py
Normal file
58
app/crud/crud_user.py
Normal file
@ -0,0 +1,58 @@
|
|||||||
|
from typing import Any, Dict, Optional, Union
|
||||||
|
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app.core.security import get_password_hash, verify_password
|
||||||
|
from app.crud.base import CRUDBase
|
||||||
|
from app.models.user import User
|
||||||
|
from app.schemas.user import UserCreate, UserUpdate
|
||||||
|
|
||||||
|
|
||||||
|
class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
|
||||||
|
def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
|
||||||
|
return db.query(User).filter(User.email == email).first()
|
||||||
|
|
||||||
|
def get_by_username(self, db: Session, *, username: str) -> Optional[User]:
|
||||||
|
return db.query(User).filter(User.username == username).first()
|
||||||
|
|
||||||
|
def create(self, db: Session, *, obj_in: UserCreate) -> User:
|
||||||
|
db_obj = User(
|
||||||
|
email=obj_in.email,
|
||||||
|
username=obj_in.username,
|
||||||
|
hashed_password=get_password_hash(obj_in.password),
|
||||||
|
first_name=obj_in.first_name,
|
||||||
|
last_name=obj_in.last_name,
|
||||||
|
is_active=True,
|
||||||
|
role_id=obj_in.role_id,
|
||||||
|
)
|
||||||
|
db.add(db_obj)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(db_obj)
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
def update(
|
||||||
|
self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]
|
||||||
|
) -> User:
|
||||||
|
if isinstance(obj_in, dict):
|
||||||
|
update_data = obj_in
|
||||||
|
else:
|
||||||
|
update_data = obj_in.dict(exclude_unset=True)
|
||||||
|
if update_data.get("password"):
|
||||||
|
hashed_password = get_password_hash(update_data["password"])
|
||||||
|
del update_data["password"]
|
||||||
|
update_data["hashed_password"] = hashed_password
|
||||||
|
return super().update(db, db_obj=db_obj, obj_in=update_data)
|
||||||
|
|
||||||
|
def authenticate(self, db: Session, *, username: str, password: str) -> Optional[User]:
|
||||||
|
user = self.get_by_username(db, username=username)
|
||||||
|
if not user:
|
||||||
|
return None
|
||||||
|
if not verify_password(password, user.hashed_password):
|
||||||
|
return None
|
||||||
|
return user
|
||||||
|
|
||||||
|
def is_active(self, user: User) -> bool:
|
||||||
|
return user.is_active
|
||||||
|
|
||||||
|
|
||||||
|
user = CRUDUser(User)
|
0
app/db/__init__.py
Normal file
0
app/db/__init__.py
Normal file
1
app/db/base.py
Normal file
1
app/db/base.py
Normal file
@ -0,0 +1 @@
|
|||||||
|
# Import all models here to ensure they are registered with SQLAlchemy
|
13
app/db/base_class.py
Normal file
13
app/db/base_class.py
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
from typing import Any
|
||||||
|
from sqlalchemy.ext.declarative import declared_attr
|
||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
id: Any
|
||||||
|
__name__: str
|
||||||
|
|
||||||
|
# Generate __tablename__ automatically
|
||||||
|
@declared_attr
|
||||||
|
def __tablename__(cls) -> str:
|
||||||
|
return cls.__name__.lower()
|
25
app/db/session.py
Normal file
25
app/db/session.py
Normal file
@ -0,0 +1,25 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import sessionmaker
|
||||||
|
|
||||||
|
|
||||||
|
# Ensure the database directory exists
|
||||||
|
DB_DIR = Path("/app") / "storage" / "db"
|
||||||
|
DB_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
SQLALCHEMY_DATABASE_URL = f"sqlite:///{DB_DIR}/db.sqlite"
|
||||||
|
|
||||||
|
engine = create_engine(
|
||||||
|
SQLALCHEMY_DATABASE_URL,
|
||||||
|
connect_args={"check_same_thread": False}
|
||||||
|
)
|
||||||
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
|
||||||
|
|
||||||
|
# Dependency to get DB session
|
||||||
|
def get_db():
|
||||||
|
db = SessionLocal()
|
||||||
|
try:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
0
app/models/__init__.py
Normal file
0
app/models/__init__.py
Normal file
24
app/models/class_enrollment.py
Normal file
24
app/models/class_enrollment.py
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Float
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class ClassEnrollment(Base):
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
enrollment_date = Column(DateTime, default=datetime.utcnow)
|
||||||
|
grade = Column(Float, nullable=True)
|
||||||
|
semester = Column(String(20), nullable=False)
|
||||||
|
academic_year = Column(String(10), nullable=False)
|
||||||
|
|
||||||
|
# Foreign keys
|
||||||
|
student_id = Column(Integer, ForeignKey("student.id"), nullable=False)
|
||||||
|
course_id = Column(Integer, ForeignKey("course.id"), nullable=False)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
student = relationship("Student", back_populates="enrollments")
|
||||||
|
course = relationship("Course", back_populates="enrollments")
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"<ClassEnrollment {self.student_id}_{self.course_id}>"
|
23
app/models/course.py
Normal file
23
app/models/course.py
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Text, ForeignKey, Boolean
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Course(Base):
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
course_code = Column(String(20), unique=True, index=True, nullable=False)
|
||||||
|
title = Column(String(100), nullable=False)
|
||||||
|
description = Column(Text, nullable=True)
|
||||||
|
credits = Column(Integer, default=0)
|
||||||
|
is_active = Column(Boolean, default=True)
|
||||||
|
|
||||||
|
# Foreign keys
|
||||||
|
teacher_id = Column(Integer, ForeignKey("teacher.id"), nullable=True)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
teacher = relationship("Teacher", back_populates="courses")
|
||||||
|
enrollments = relationship("ClassEnrollment", back_populates="course")
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"<Course {self.course_code}>"
|
16
app/models/role.py
Normal file
16
app/models/role.py
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Text
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Role(Base):
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
name = Column(String(50), unique=True, index=True, nullable=False)
|
||||||
|
description = Column(Text, nullable=True)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
users = relationship("User", back_populates="role")
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"<Role {self.name}>"
|
23
app/models/student.py
Normal file
23
app/models/student.py
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Date, ForeignKey
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Student(Base):
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
student_id = Column(String(20), unique=True, index=True, nullable=False)
|
||||||
|
date_of_birth = Column(Date, nullable=True)
|
||||||
|
address = Column(String(255), nullable=True)
|
||||||
|
phone_number = Column(String(20), nullable=True)
|
||||||
|
grade_level = Column(String(20), nullable=True)
|
||||||
|
|
||||||
|
# Foreign keys
|
||||||
|
user_id = Column(Integer, ForeignKey("user.id"), unique=True, nullable=False)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
user = relationship("User", back_populates="student")
|
||||||
|
enrollments = relationship("ClassEnrollment", back_populates="student")
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"<Student {self.student_id}>"
|
24
app/models/teacher.py
Normal file
24
app/models/teacher.py
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
from sqlalchemy import Column, Integer, String, Date, ForeignKey
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class Teacher(Base):
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
teacher_id = Column(String(20), unique=True, index=True, nullable=False)
|
||||||
|
date_of_birth = Column(Date, nullable=True)
|
||||||
|
address = Column(String(255), nullable=True)
|
||||||
|
phone_number = Column(String(20), nullable=True)
|
||||||
|
department = Column(String(50), nullable=True)
|
||||||
|
hire_date = Column(Date, nullable=True)
|
||||||
|
|
||||||
|
# Foreign keys
|
||||||
|
user_id = Column(Integer, ForeignKey("user.id"), unique=True, nullable=False)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
user = relationship("User", back_populates="teacher")
|
||||||
|
courses = relationship("Course", back_populates="teacher")
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"<Teacher {self.teacher_id}>"
|
28
app/models/user.py
Normal file
28
app/models/user.py
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from sqlalchemy import Boolean, Column, Integer, String, DateTime, ForeignKey
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from app.db.base_class import Base
|
||||||
|
|
||||||
|
|
||||||
|
class User(Base):
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
email = Column(String(100), unique=True, index=True, nullable=False)
|
||||||
|
username = Column(String(50), unique=True, index=True, nullable=False)
|
||||||
|
first_name = Column(String(50), nullable=True)
|
||||||
|
last_name = Column(String(50), nullable=True)
|
||||||
|
hashed_password = Column(String(255), nullable=False)
|
||||||
|
is_active = Column(Boolean, default=True)
|
||||||
|
created_at = Column(DateTime, default=datetime.utcnow)
|
||||||
|
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||||
|
|
||||||
|
# Foreign keys
|
||||||
|
role_id = Column(Integer, ForeignKey("role.id"), nullable=False)
|
||||||
|
|
||||||
|
# Relationships
|
||||||
|
role = relationship("Role", back_populates="users")
|
||||||
|
student = relationship("Student", back_populates="user", uselist=False)
|
||||||
|
teacher = relationship("Teacher", back_populates="user", uselist=False)
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"<User {self.username}>"
|
0
app/schemas/__init__.py
Normal file
0
app/schemas/__init__.py
Normal file
30
app/schemas/role.py
Normal file
30
app/schemas/role.py
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
# Shared properties
|
||||||
|
class RoleBase(BaseModel):
|
||||||
|
name: Optional[str] = None
|
||||||
|
description: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive via API on creation
|
||||||
|
class RoleCreate(RoleBase):
|
||||||
|
name: str
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive via API on update
|
||||||
|
class RoleUpdate(RoleBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class RoleInDBBase(RoleBase):
|
||||||
|
id: Optional[int] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# Additional properties to return via API
|
||||||
|
class Role(RoleInDBBase):
|
||||||
|
pass
|
47
app/schemas/student.py
Normal file
47
app/schemas/student.py
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
from typing import Optional
|
||||||
|
from datetime import date
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
# Import at the top to avoid circular imports
|
||||||
|
from app.schemas.user import User as UserOut
|
||||||
|
|
||||||
|
|
||||||
|
# Shared properties
|
||||||
|
class StudentBase(BaseModel):
|
||||||
|
student_id: Optional[str] = None
|
||||||
|
date_of_birth: Optional[date] = None
|
||||||
|
address: Optional[str] = None
|
||||||
|
phone_number: Optional[str] = None
|
||||||
|
grade_level: Optional[str] = None
|
||||||
|
user_id: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive via API on creation
|
||||||
|
class StudentCreate(StudentBase):
|
||||||
|
student_id: str
|
||||||
|
user_id: int
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive via API on update
|
||||||
|
class StudentUpdate(StudentBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class StudentInDBBase(StudentBase):
|
||||||
|
id: Optional[int] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# Additional properties to return via API
|
||||||
|
class Student(StudentInDBBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Student with User details
|
||||||
|
class StudentWithUser(Student):
|
||||||
|
user: Optional[UserOut] = None
|
||||||
|
|
||||||
|
# Update forward refs
|
||||||
|
StudentWithUser.model_rebuild()
|
12
app/schemas/token.py
Normal file
12
app/schemas/token.py
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
||||||
|
class Token(BaseModel):
|
||||||
|
access_token: str
|
||||||
|
token_type: str
|
||||||
|
|
||||||
|
|
||||||
|
class TokenPayload(BaseModel):
|
||||||
|
sub: Optional[int] = None
|
||||||
|
role: Optional[str] = None
|
42
app/schemas/user.py
Normal file
42
app/schemas/user.py
Normal file
@ -0,0 +1,42 @@
|
|||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel, EmailStr
|
||||||
|
|
||||||
|
|
||||||
|
# Shared properties
|
||||||
|
class UserBase(BaseModel):
|
||||||
|
email: Optional[EmailStr] = None
|
||||||
|
username: Optional[str] = None
|
||||||
|
is_active: Optional[bool] = True
|
||||||
|
first_name: Optional[str] = None
|
||||||
|
last_name: Optional[str] = None
|
||||||
|
role_id: Optional[int] = None
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive via API on creation
|
||||||
|
class UserCreate(UserBase):
|
||||||
|
email: EmailStr
|
||||||
|
username: str
|
||||||
|
password: str
|
||||||
|
role_id: int
|
||||||
|
|
||||||
|
|
||||||
|
# Properties to receive via API on update
|
||||||
|
class UserUpdate(UserBase):
|
||||||
|
password: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class UserInDBBase(UserBase):
|
||||||
|
id: Optional[int] = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
from_attributes = True
|
||||||
|
|
||||||
|
|
||||||
|
# Additional properties to return via API
|
||||||
|
class User(UserInDBBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
# Additional properties stored in DB
|
||||||
|
class UserInDB(UserInDBBase):
|
||||||
|
hashed_password: str
|
0
app/utils/__init__.py
Normal file
0
app/utils/__init__.py
Normal file
36
main.py
Normal file
36
main.py
Normal file
@ -0,0 +1,36 @@
|
|||||||
|
from fastapi import FastAPI
|
||||||
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
from app.api.v1.api import api_router
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
app = FastAPI(
|
||||||
|
title=settings.PROJECT_NAME,
|
||||||
|
openapi_url="/openapi.json",
|
||||||
|
docs_url="/docs",
|
||||||
|
redoc_url="/redoc",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Set all CORS enabled origins
|
||||||
|
app.add_middleware(
|
||||||
|
CORSMiddleware,
|
||||||
|
allow_origins=["*"],
|
||||||
|
allow_credentials=True,
|
||||||
|
allow_methods=["*"],
|
||||||
|
allow_headers=["*"],
|
||||||
|
)
|
||||||
|
|
||||||
|
app.include_router(api_router, prefix=settings.API_V1_STR)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/health", tags=["Health"])
|
||||||
|
async def health_check():
|
||||||
|
"""
|
||||||
|
Health check endpoint
|
||||||
|
"""
|
||||||
|
return {"status": "healthy"}
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
|
1
migrations/README
Normal file
1
migrations/README
Normal file
@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration with SQLite.
|
87
migrations/env.py
Normal file
87
migrations/env.py
Normal file
@ -0,0 +1,87 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from sqlalchemy import engine_from_config
|
||||||
|
from sqlalchemy import pool
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
from app.db.base import Base
|
||||||
|
from app.core.config import settings
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# Set the SQLAlchemy URL from our app config
|
||||||
|
config.set_main_option("sqlalchemy.url", settings.SQLALCHEMY_DATABASE_URL)
|
||||||
|
|
||||||
|
# Interpret the config file for Python logging.
|
||||||
|
# This line sets up loggers basically.
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
# add your model's MetaData object here
|
||||||
|
# for 'autogenerate' support
|
||||||
|
# from myapp import mymodel
|
||||||
|
# target_metadata = mymodel.Base.metadata
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
# other values from the config, defined by the needs of env.py,
|
||||||
|
# can be acquired:
|
||||||
|
# my_important_option = config.get_main_option("my_important_option")
|
||||||
|
# ... etc.
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
|
This configures the context with just a URL
|
||||||
|
and not an Engine, though an Engine is acceptable
|
||||||
|
here as well. By skipping the Engine creation
|
||||||
|
we don't even need a DBAPI to be available.
|
||||||
|
|
||||||
|
Calls to context.execute() here emit the given string to the
|
||||||
|
script output.
|
||||||
|
|
||||||
|
"""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
"""Run migrations in 'online' mode.
|
||||||
|
|
||||||
|
In this scenario we need to create an Engine
|
||||||
|
and associate a connection with the context.
|
||||||
|
|
||||||
|
"""
|
||||||
|
connectable = engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
is_sqlite = connection.dialect.name == 'sqlite'
|
||||||
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
render_as_batch=is_sqlite # Key configuration for SQLite
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
26
migrations/script.py.mako
Normal file
26
migrations/script.py.mako
Normal file
@ -0,0 +1,26 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: Union[str, None] = ${repr(down_revision)}
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
|
||||||
|
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
145
migrations/versions/001_initial_migration.py
Normal file
145
migrations/versions/001_initial_migration.py
Normal file
@ -0,0 +1,145 @@
|
|||||||
|
"""Initial migration
|
||||||
|
|
||||||
|
Revision ID: 001
|
||||||
|
Revises:
|
||||||
|
Create Date: 2023-10-01
|
||||||
|
|
||||||
|
"""
|
||||||
|
from typing import Sequence, Union
|
||||||
|
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision: str = '001'
|
||||||
|
down_revision: Union[str, None] = None
|
||||||
|
branch_labels: Union[str, Sequence[str], None] = None
|
||||||
|
depends_on: Union[str, Sequence[str], None] = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# Create role table
|
||||||
|
op.create_table(
|
||||||
|
'role',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('name', sa.String(length=50), nullable=False),
|
||||||
|
sa.Column('description', sa.Text(), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_role_id'), 'role', ['id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_role_name'), 'role', ['name'], unique=True)
|
||||||
|
|
||||||
|
# Create user table
|
||||||
|
op.create_table(
|
||||||
|
'user',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('email', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('username', sa.String(length=50), nullable=False),
|
||||||
|
sa.Column('first_name', sa.String(length=50), nullable=True),
|
||||||
|
sa.Column('last_name', sa.String(length=50), nullable=True),
|
||||||
|
sa.Column('hashed_password', sa.String(length=255), nullable=False),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||||
|
sa.Column('created_at', sa.DateTime(), nullable=True),
|
||||||
|
sa.Column('updated_at', sa.DateTime(), nullable=True),
|
||||||
|
sa.Column('role_id', sa.Integer(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['role_id'], ['role.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=True)
|
||||||
|
op.create_index(op.f('ix_user_id'), 'user', ['id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_user_username'), 'user', ['username'], unique=True)
|
||||||
|
|
||||||
|
# Create teacher table
|
||||||
|
op.create_table(
|
||||||
|
'teacher',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('teacher_id', sa.String(length=20), nullable=False),
|
||||||
|
sa.Column('date_of_birth', sa.Date(), nullable=True),
|
||||||
|
sa.Column('address', sa.String(length=255), nullable=True),
|
||||||
|
sa.Column('phone_number', sa.String(length=20), nullable=True),
|
||||||
|
sa.Column('department', sa.String(length=50), nullable=True),
|
||||||
|
sa.Column('hire_date', sa.Date(), nullable=True),
|
||||||
|
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('user_id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_teacher_id'), 'teacher', ['id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_teacher_teacher_id'), 'teacher', ['teacher_id'], unique=True)
|
||||||
|
|
||||||
|
# Create student table
|
||||||
|
op.create_table(
|
||||||
|
'student',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('student_id', sa.String(length=20), nullable=False),
|
||||||
|
sa.Column('date_of_birth', sa.Date(), nullable=True),
|
||||||
|
sa.Column('address', sa.String(length=255), nullable=True),
|
||||||
|
sa.Column('phone_number', sa.String(length=20), nullable=True),
|
||||||
|
sa.Column('grade_level', sa.String(length=20), nullable=True),
|
||||||
|
sa.Column('user_id', sa.Integer(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['user_id'], ['user.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id'),
|
||||||
|
sa.UniqueConstraint('user_id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_student_id'), 'student', ['id'], unique=False)
|
||||||
|
op.create_index(op.f('ix_student_student_id'), 'student', ['student_id'], unique=True)
|
||||||
|
|
||||||
|
# Create course table
|
||||||
|
op.create_table(
|
||||||
|
'course',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('course_code', sa.String(length=20), nullable=False),
|
||||||
|
sa.Column('title', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('description', sa.Text(), nullable=True),
|
||||||
|
sa.Column('credits', sa.Integer(), nullable=True),
|
||||||
|
sa.Column('is_active', sa.Boolean(), nullable=True),
|
||||||
|
sa.Column('teacher_id', sa.Integer(), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(['teacher_id'], ['teacher.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_course_course_code'), 'course', ['course_code'], unique=True)
|
||||||
|
op.create_index(op.f('ix_course_id'), 'course', ['id'], unique=False)
|
||||||
|
|
||||||
|
# Create class_enrollment table
|
||||||
|
op.create_table(
|
||||||
|
'classenrollment',
|
||||||
|
sa.Column('id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('enrollment_date', sa.DateTime(), nullable=True),
|
||||||
|
sa.Column('grade', sa.Float(), nullable=True),
|
||||||
|
sa.Column('semester', sa.String(length=20), nullable=False),
|
||||||
|
sa.Column('academic_year', sa.String(length=10), nullable=False),
|
||||||
|
sa.Column('student_id', sa.Integer(), nullable=False),
|
||||||
|
sa.Column('course_id', sa.Integer(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['course_id'], ['course.id'], ),
|
||||||
|
sa.ForeignKeyConstraint(['student_id'], ['student.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_classenrollment_id'), 'classenrollment', ['id'], unique=False)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# Drop tables in reverse order of creation
|
||||||
|
op.drop_index(op.f('ix_classenrollment_id'), table_name='classenrollment')
|
||||||
|
op.drop_table('classenrollment')
|
||||||
|
|
||||||
|
op.drop_index(op.f('ix_course_id'), table_name='course')
|
||||||
|
op.drop_index(op.f('ix_course_course_code'), table_name='course')
|
||||||
|
op.drop_table('course')
|
||||||
|
|
||||||
|
op.drop_index(op.f('ix_student_student_id'), table_name='student')
|
||||||
|
op.drop_index(op.f('ix_student_id'), table_name='student')
|
||||||
|
op.drop_table('student')
|
||||||
|
|
||||||
|
op.drop_index(op.f('ix_teacher_teacher_id'), table_name='teacher')
|
||||||
|
op.drop_index(op.f('ix_teacher_id'), table_name='teacher')
|
||||||
|
op.drop_table('teacher')
|
||||||
|
|
||||||
|
op.drop_index(op.f('ix_user_username'), table_name='user')
|
||||||
|
op.drop_index(op.f('ix_user_id'), table_name='user')
|
||||||
|
op.drop_index(op.f('ix_user_email'), table_name='user')
|
||||||
|
op.drop_table('user')
|
||||||
|
|
||||||
|
op.drop_index(op.f('ix_role_name'), table_name='role')
|
||||||
|
op.drop_index(op.f('ix_role_id'), table_name='role')
|
||||||
|
op.drop_table('role')
|
13
requirements.txt
Normal file
13
requirements.txt
Normal file
@ -0,0 +1,13 @@
|
|||||||
|
fastapi>=0.101.0
|
||||||
|
uvicorn>=0.23.2
|
||||||
|
pydantic>=2.0.0
|
||||||
|
pydantic-settings>=2.0.0
|
||||||
|
sqlalchemy>=2.0.0
|
||||||
|
alembic>=1.12.0
|
||||||
|
python-jose[cryptography]>=3.3.0
|
||||||
|
passlib[bcrypt]>=1.7.4
|
||||||
|
python-multipart>=0.0.6
|
||||||
|
email-validator>=2.0.0
|
||||||
|
ruff>=0.1.0
|
||||||
|
pytest>=7.4.0
|
||||||
|
httpx>=0.24.1
|
Loading…
x
Reference in New Issue
Block a user