Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions backend/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,18 @@ $ alembic upgrade head

If you don't want to start with the default models and want to remove them / modify them, from the beginning, without having any previous revision, you can remove the revision files (`.py` Python files) under `./backend/app/alembic/versions/`. And then create a first migration as described above.

## Demo Users

Each user has one role: `admin`, `manager`, or `member`. Admins manage users. Managers can view users and metrics but not change them. Members only see their own items.

To create one demo user per role in a local database, run this from the `backend` directory with `FASTAPI_ENV=development`:

```console
$ uv run python -m app.seed_demo_users
```

It creates `demo-admin@example.com`, `demo-manager@example.com`, and `demo-member@example.com` with the password from `DEMO_USER_PASSWORD` (default `DemoPass123!`). Running it again resets those three users to their demo role, active state, and password.

## Email Templates

The email templates are written with [React Email](https://react.email) in `./packages/react-email/`. The `emails` directory holds one component per email and the `ui` directory holds the shared components (layout, heading, button, link, callout).
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
"""Replace is_superuser with role

Revision ID: b7c3d9e1f2a4
Revises: fe56fa70289e
Create Date: 2026-11-28 20:30:00.000000

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = 'b7c3d9e1f2a4'
down_revision = 'fe56fa70289e'
branch_labels = None
depends_on = None


def upgrade():
op.add_column('user', sa.Column('role', sa.String(length=32), nullable=True))
op.execute(
"UPDATE \"user\" SET role = CASE WHEN is_superuser THEN 'admin' ELSE 'member' END"
)
op.alter_column('user', 'role', nullable=False)
op.create_check_constraint(
'ck_user_role', 'user', "role IN ('admin', 'manager', 'member')"
)
op.drop_column('user', 'is_superuser')


def downgrade():
op.add_column(
'user',
sa.Column('is_superuser', sa.Boolean(), nullable=False, server_default=sa.false()),
)
op.execute("UPDATE \"user\" SET is_superuser = (role = 'admin')")
op.alter_column('user', 'is_superuser', server_default=None)
op.drop_constraint('ck_user_role', 'user', type_='check')
op.drop_column('user', 'role')
23 changes: 15 additions & 8 deletions backend/app/api/deps.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from collections.abc import Generator
from collections.abc import Callable, Generator
from typing import Annotated

import jwt
Expand All @@ -11,7 +11,7 @@
from app.core import security
from app.core.config import settings
from app.core.db import engine
from app.models import TokenPayload, User
from app.models import TokenPayload, User, UserRole

reusable_oauth2 = OAuth2PasswordBearer(
tokenUrl=f"{settings.API_V1_STR}/login/access-token"
Expand Down Expand Up @@ -49,9 +49,16 @@ def get_current_user(session: SessionDep, token: TokenDep) -> User:
CurrentUser = Annotated[User, Depends(get_current_user)]


def get_current_active_superuser(current_user: CurrentUser) -> User:
if not current_user.is_superuser:
raise HTTPException(
status_code=403, detail="The user doesn't have enough privileges"
)
return current_user
def require_roles(*allowed_roles: UserRole) -> Callable[[User], User]:
def check_role(current_user: CurrentUser) -> User:
if current_user.role not in allowed_roles:
raise HTTPException(
status_code=403, detail="The user doesn't have enough privileges"
)
return current_user

return check_role


AdminUser = Annotated[User, Depends(require_roles(UserRole.ADMIN))]
StaffUser = Annotated[User, Depends(require_roles(UserRole.ADMIN, UserRole.MANAGER))]
3 changes: 2 additions & 1 deletion backend/app/api/main.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
from fastapi import APIRouter

from app.api.routes import items, login, private, users, utils
from app.api.routes import items, login, metrics, private, users, utils
from app.core.config import settings

api_router = APIRouter()
api_router.include_router(login.router)
api_router.include_router(users.router)
api_router.include_router(utils.router)
api_router.include_router(items.router)
api_router.include_router(metrics.router)


if settings.FASTAPI_ENV == "development":
Expand Down
18 changes: 13 additions & 5 deletions backend/app/api/routes/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,15 @@
from sqlmodel import col, func, select

from app.api.deps import CurrentUser, SessionDep
from app.models import Item, ItemCreate, ItemPublic, ItemsPublic, ItemUpdate, Message
from app.models import (
Item,
ItemCreate,
ItemPublic,
ItemsPublic,
ItemUpdate,
Message,
UserRole,
)

router = APIRouter(prefix="/items", tags=["items"])

Expand All @@ -18,7 +26,7 @@ def read_items(
Retrieve items.
"""

if current_user.is_superuser:
if current_user.role == UserRole.ADMIN:
count_statement = select(func.count()).select_from(Item)
count = session.exec(count_statement).one()
statement = (
Expand Down Expand Up @@ -53,7 +61,7 @@ def read_item(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) ->
item = session.get(Item, id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not current_user.is_superuser and (item.owner_id != current_user.id):
if current_user.role != UserRole.ADMIN and (item.owner_id != current_user.id):
raise HTTPException(status_code=403, detail="Not enough permissions")
return item

Expand Down Expand Up @@ -86,7 +94,7 @@ def update_item(
item = session.get(Item, id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not current_user.is_superuser and (item.owner_id != current_user.id):
if current_user.role != UserRole.ADMIN and (item.owner_id != current_user.id):
raise HTTPException(status_code=403, detail="Not enough permissions")
update_dict = item_in.model_dump(exclude_unset=True)
item.sqlmodel_update(update_dict)
Expand All @@ -106,7 +114,7 @@ def delete_item(
item = session.get(Item, id)
if not item:
raise HTTPException(status_code=404, detail="Item not found")
if not current_user.is_superuser and (item.owner_id != current_user.id):
if current_user.role != UserRole.ADMIN and (item.owner_id != current_user.id):
raise HTTPException(status_code=403, detail="Not enough permissions")
session.delete(item)
session.commit()
Expand Down
5 changes: 2 additions & 3 deletions backend/app/api/routes/login.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from fastapi.security import OAuth2PasswordRequestForm

from app import crud
from app.api.deps import CurrentUser, SessionDep, get_current_active_superuser
from app.api.deps import AdminUser, CurrentUser, SessionDep
from app.core import security
from app.core.config import settings
from app.models import Message, NewPassword, Token, UserPublic, UserUpdate
Expand Down Expand Up @@ -99,10 +99,9 @@ def reset_password(session: SessionDep, body: NewPassword) -> Message:

@router.post(
"/password-recovery-html-content/{email}",
dependencies=[Depends(get_current_active_superuser)],
response_class=HTMLResponse,
)
def recover_password_html_content(email: str, session: SessionDep) -> Any:
def recover_password_html_content(email: str, session: SessionDep, _: AdminUser) -> Any:
"""
HTML Content for Password Recovery
"""
Expand Down
22 changes: 22 additions & 0 deletions backend/app/api/routes/metrics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
from fastapi import APIRouter
from sqlmodel import col, func, select

from app.api.deps import SessionDep, StaffUser
from app.models import Item, MetricsPublic, User

router = APIRouter(prefix="/metrics", tags=["metrics"])


@router.get("/", response_model=MetricsPublic)
def read_metrics(session: SessionDep, _: StaffUser) -> MetricsPublic:
"""
Retrieve user and item counts.
"""
total_users = session.exec(select(func.count()).select_from(User)).one()
active_users = session.exec(
select(func.count()).select_from(User).where(col(User.is_active))
).one()
total_items = session.exec(select(func.count()).select_from(Item)).one()
return MetricsPublic(
total_users=total_users, active_users=active_users, total_items=total_items
)
51 changes: 24 additions & 27 deletions backend/app/api/routes/users.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import uuid
from typing import Any

from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, HTTPException
from sqlmodel import col, delete, func, select

from app import crud
from app.api.deps import (
CurrentUser,
SessionDep,
get_current_active_superuser,
)
from app.api.deps import AdminUser, CurrentUser, SessionDep, StaffUser
from app.core.config import settings
from app.core.security import get_password_hash, verify_password
from app.models import (
Expand All @@ -20,6 +16,7 @@
UserCreate,
UserPublic,
UserRegister,
UserRole,
UsersPublic,
UserUpdate,
UserUpdateMe,
Expand All @@ -29,12 +26,10 @@
router = APIRouter(prefix="/users", tags=["users"])


@router.get(
"/",
dependencies=[Depends(get_current_active_superuser)],
response_model=UsersPublic,
)
def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
@router.get("/", response_model=UsersPublic)
def read_users(
session: SessionDep, _: StaffUser, skip: int = 0, limit: int = 100
) -> Any:
"""
Retrieve users.
"""
Expand All @@ -51,10 +46,8 @@ def read_users(session: SessionDep, skip: int = 0, limit: int = 100) -> Any:
return UsersPublic(data=users_public, count=count)


@router.post(
"/", dependencies=[Depends(get_current_active_superuser)], response_model=UserPublic
)
def create_user(*, session: SessionDep, user_in: UserCreate) -> Any:
@router.post("/", response_model=UserPublic)
def create_user(*, session: SessionDep, _: AdminUser, user_in: UserCreate) -> Any:
"""
Create new user.
"""
Expand Down Expand Up @@ -134,9 +127,9 @@ def delete_user_me(session: SessionDep, current_user: CurrentUser) -> Any:
"""
Delete own user.
"""
if current_user.is_superuser:
if current_user.role == UserRole.ADMIN:
raise HTTPException(
status_code=403, detail="Super users are not allowed to delete themselves"
status_code=403, detail="Admins are not allowed to delete themselves"
)
session.delete(current_user)
session.commit()
Expand Down Expand Up @@ -169,7 +162,7 @@ def read_user_by_id(
user = session.get(User, user_id)
if user == current_user:
return user
if not current_user.is_superuser:
if current_user.role not in (UserRole.ADMIN, UserRole.MANAGER):
raise HTTPException(
status_code=403,
detail="The user doesn't have enough privileges",
Expand All @@ -179,14 +172,11 @@ def read_user_by_id(
return user


@router.patch(
"/{user_id}",
dependencies=[Depends(get_current_active_superuser)],
response_model=UserPublic,
)
@router.patch("/{user_id}", response_model=UserPublic)
def update_user(
*,
session: SessionDep,
current_user: AdminUser,
user_id: uuid.UUID,
user_in: UserUpdate,
) -> Any:
Expand All @@ -200,6 +190,13 @@ def update_user(
status_code=404,
detail="The user with this id does not exist in the system",
)
if db_user.id == current_user.id and (
user_in.role not in (None, UserRole.ADMIN) or user_in.is_active is False
):
raise HTTPException(
status_code=403,
detail="Admins are not allowed to demote or deactivate themselves",
)
if user_in.email:
existing_user = crud.get_user_by_email(session=session, email=user_in.email)
if existing_user and existing_user.id != user_id:
Expand All @@ -211,9 +208,9 @@ def update_user(
return db_user


@router.delete("/{user_id}", dependencies=[Depends(get_current_active_superuser)])
@router.delete("/{user_id}")
def delete_user(
session: SessionDep, current_user: CurrentUser, user_id: uuid.UUID
session: SessionDep, current_user: AdminUser, user_id: uuid.UUID
) -> Message:
"""
Delete a user.
Expand All @@ -223,7 +220,7 @@ def delete_user(
raise HTTPException(status_code=404, detail="User not found")
if user == current_user:
raise HTTPException(
status_code=403, detail="Super users are not allowed to delete themselves"
status_code=403, detail="Admins are not allowed to delete themselves"
)
statement = delete(Item).where(col(Item.owner_id) == user_id)
session.exec(statement)
Expand Down
12 changes: 4 additions & 8 deletions backend/app/api/routes/utils.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,15 @@
from fastapi import APIRouter, Depends
from fastapi import APIRouter
from pydantic.networks import EmailStr

from app.api.deps import get_current_active_superuser
from app.api.deps import AdminUser
from app.models import Message
from app.utils import generate_test_email, send_email

router = APIRouter(prefix="/utils", tags=["utils"])


@router.post(
"/test-email/",
dependencies=[Depends(get_current_active_superuser)],
status_code=201,
)
def test_email(email_to: EmailStr) -> Message:
@router.post("/test-email/", status_code=201)
def test_email(email_to: EmailStr, _: AdminUser) -> Message:
"""
Test emails.
"""
Expand Down
4 changes: 2 additions & 2 deletions backend/app/core/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

from app import crud
from app.core.config import settings
from app.models import User, UserCreate
from app.models import User, UserCreate, UserRole

engine = create_engine(str(settings.DATABASE_URL), pool_pre_ping=True)

Expand All @@ -28,6 +28,6 @@ def init_db(session: Session) -> None:
user_in = UserCreate(
email=settings.FIRST_SUPERUSER,
password=settings.FIRST_SUPERUSER_PASSWORD,
is_superuser=True,
role=UserRole.ADMIN,
)
user = crud.create_user(session=session, user_create=user_in)
Loading