Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
c8ead80
chore(pyproject): update install steps and change to using uv
jbriones1 Dec 17, 2025
e6f1072
fix: python version pinned to 3.11
jbriones1 Dec 17, 2025
0d4ce6c
chore(gitignore): update gitignore with uv items
jbriones1 Dec 17, 2025
b7c305f
chore(pyright): update pyright config to use version 3.11
jbriones1 Dec 17, 2025
c94aa06
chore(format): ignore alembic migrations
jbriones1 Dec 17, 2025
a721e4f
chore(format): ran the formatter over the entire project
jbriones1 Dec 17, 2025
df0f490
fix(ci): fix script to not rely on requirements.txt
jbriones1 Dec 17, 2025
01cb9f4
fix(ci): split test and dev dependencies again, update action script
jbriones1 Dec 17, 2025
8fe4e74
fix(ci): removed requirements.txt requirement
jbriones1 Dec 17, 2025
5ab91f4
fix(uv): update uv.lock to current state
jbriones1 Dec 17, 2025
f571eb3
refactor(permissions): rewrote permissions to integrate admin types
jbriones1 Dec 18, 2025
74bc701
fix: type errors in officers crud
jbriones1 Dec 18, 2025
4873317
refactor(permissions): restructured most endpoints to use Depends
jbriones1 Dec 18, 2025
6c880e1
fix(tests): whole test suite can now be run
jbriones1 Dec 18, 2025
268fd97
fix: missing awaits on permission check calls
jbriones1 Dec 19, 2025
69469e1
fix(officers): tests now all work
jbriones1 Dec 19, 2025
6e39610
fix: move `conftest.py` to only work on integrations tests
jbriones1 Dec 19, 2025
3eeaebc
wip: add GET all registrations
jbriones1 Sep 27, 2025
150f08c
wip(nominee): add create endpoint
jbriones1 Sep 27, 2025
32a3ee0
wip: add GET all nominees
jbriones1 Sep 27, 2025
8492ff0
wip: add DELETE nominee_info
jbriones1 Sep 27, 2025
3fa406a
fix(Elections): duplicate operation id in nominees URLs
jbriones1 Sep 28, 2025
95ad68e
fix: patch to put
jbriones1 Sep 28, 2025
a751e67
fix: election tests now work
jbriones1 Dec 19, 2025
56f3585
fix(tests): add missing param types
jbriones1 Dec 20, 2025
f8824f7
refactor: split election tests into multiple functions
jbriones1 Dec 20, 2025
96ca71c
fix(tests): split admin elections tests
jbriones1 Dec 20, 2025
a34a3c4
fix(permissions): fixed some permission tests to be more efficient
jbriones1 Dec 20, 2025
e95efd9
refactor: update Nominee model names
jbriones1 Dec 20, 2025
0f2a339
fix(elections): fix all elections tests
jbriones1 Dec 21, 2025
af31465
fix(registrations): change return type to list
jbriones1 Dec 21, 2025
a1dc6b3
fix(registration): fix list being sent as a JSON response
jbriones1 Dec 21, 2025
812185e
fix(registratio): removed enum check
jbriones1 Dec 21, 2025
efa5042
fix(registration): changed search to a single registration
jbriones1 Dec 21, 2025
512bc66
refactor(officers): response for current officers changed to list
jbriones1 Dec 27, 2025
1d7a4c9
fix(officers): tests that expect a dict response for current officers
jbriones1 Dec 27, 2025
908e6ad
fix(Officers): merged the public and private models
jbriones1 Dec 27, 2025
316c1b6
chore(OfficerInfoDB): remove unused methods
jbriones1 Dec 27, 2025
2e4ce2c
fix(test): user client is now module scoped
jbriones1 Dec 27, 2025
6b4fc15
fix(officers): model fields use OfficerPositionEnum
jbriones1 Dec 27, 2025
bd9e3ad
refactor: made a computed field
jbriones1 Dec 27, 2025
6f7d55a
fix(officers): term_id added to Officer response, id is now an int
jbriones1 Dec 27, 2025
6293336
refactor: rename OfficerUpdate to OfficerInfoUpdate
jbriones1 Dec 27, 2025
91941f9
refactor: change csss_email to a computed field
jbriones1 Dec 27, 2025
846446c
chore(officers): delete old types
jbriones1 Dec 27, 2025
49a3c9b
fix: remove csss_email
jbriones1 Dec 27, 2025
68a5eba
fix: check that end_date is null for current officers
jbriones1 Dec 27, 2025
2b44419
fix: tests failed after the check for current admin changed
jbriones1 Dec 27, 2025
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
2 changes: 1 addition & 1 deletion .github/workflows/alembic.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ jobs:
python3.11 -m pip install --upgrade pip
python3.11 -m venv venv
source ./venv/bin/activate
pip install -r requirements.txt
pip install .

# This will fail if there are divergent heads and alembic gets confused;
# e.g., un-sanitarily merging main into a dev branch.
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pytest_unit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ jobs:
python -m pip install --upgrade pip
python -m venv venv
source ./venv/bin/activate
pip install -r requirements.txt
pip install ".[test]"

- name: Run unit tests
run: PYTHONPATH=src ./venv/bin/python -m pytest ./tests/unit -v
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ google_key.json
# Python - Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
build/
dist/
wheels
*.egg-info/
*$py.class

.venv
Expand Down
32 changes: 31 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,35 @@ See [the csss-backend wiki](https://github.com/CSSS/csss-site-backend/wiki/1.-Lo

If you're planning to read through the source code, please check out this project's [naming conventions](https://github.com/CSSS/csss-site-backend/wiki/Style-Guide#naming-conventions).

### Quickstart

1. Install [Python 3.11](https://www.python.org/downloads/), [git](https://git-scm.com/install/), and (optionally) [Docker](https://www.docker.com/get-started/)
Note: This may fail if you're using Python 3.12+
2. Clone this repository
3. Create and activate a virtual environment for this project. This has been tested with `pip` and `uv`
4. Install developer dependencies
```bash
# Install main dependencies
pip install . # or: uv pip install .

# Install with dev dependencies
pip install ".[dev]" # or: uv pip install ".[dev]"

# Install with test dependencies
pip install ".[test]" # or: uv pip install ".[test]"

# Install with all dependencies
pip install ".[dev, test]" # or: uv pip install ".[dev, test]"
```

5. Follow the database setup instructions on the [wiki](https://github.com/CSSS/csss-site-backend/wiki/1.-Local-Setup#database-setup). The recommended way is to do it through Docker, but both should work.
6. You will need to set the following environment variables
```bash
export DB_PORT=5444 # The port your database is listening at
export LOCAL=true # Should be true if you're running this locally
```


## Important Directories

- `config/` configuration files for the server machine
Expand All @@ -26,6 +55,7 @@ If you're planning to read through the source code, please check out this projec
- `officers/` for officer contact information + photos
- `test/` for html pages which interact with the backend's local api

## Linter
## Developer Tools

We use `ruff 0.6.9` as our linter, which you can run with `ruff check --fix`. If you use a different version, it may be inconsistent with our CI checks.
We use `pyright/basedpyright` for typechecking. Language services have been left enabled and will be changed if it becomes an issue.
44 changes: 41 additions & 3 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,26 +1,58 @@
[project]
name = "csss-site-backend"
version = "0.1"
requires-python = ">= 3.11" # older versions untested, but we use new features often
requires-python = "~=3.11.0" # older versions untested, but we use new features often

dependencies = [
# major
"fastapi==0.115.6",
"gunicorn==21.2.0",
"uvicorn[standard]==0.27.1",
"sqlalchemy[asyncio]==2.0.27",
"asyncpg==0.29.0",
"alembic==1.13.1",
"google-api-python-client==2.143.0",

# minor
"pyOpenSSL==24.0.0", # for generating cryptographically secure random numbers
"xmltodict==0.13.0",
"requests==2.31.0",
]

[project.optional-dependencies]
dev = [
"ruff==0.6.9", # linting and formatter
]

test = [
"pytest", # test framework
"pytest-asyncio",
"httpx",
]

[project.urls]
Homepage = "https://api.sfucsss.org/"

# Pytest: Test framework
[tool.pytest.ini_options]
pythonpath = ["src"]
log_cli = true
log_cli_level = "INFO"
testpaths = [
"tests",
]
]
norecursedirs = "tests/wip"
asyncio_mode = "auto"
asyncio_default_fixture_loop_scope = "function"

# Ruff: Formatter and linter
[tool.ruff]
line-length = 120
indent-width = 4
target-version = "py311"
exclude = [
"src/alembic/*"
]

[tool.ruff.format]
quote-style = "double"
Expand All @@ -31,6 +63,12 @@ line-ending = "lf"
select = ["E", "F", "B", "I", "N", "UP", "A", "PTH", "W", "RUF", "C4", "PIE", "Q", "FLY"] # "ANN"
ignore = ["E501", "F401", "N806"]

# [Based]Pyright: Type checker/LSP
[tool.pyright]
executionEnvironments = [{ root = "src" }]
executionEnvironments = [
{ root = "src", pythonVersion = "3.11" },
{ root = "tests", extraPaths=["src"], pythonVersion = "3.11" }
]
typeCheckingMode = "standard"
reportAny = "none" # Allow the use of `Any` type
reportExplicitAny = "none" # Allow the declaration of `Any` type
22 changes: 0 additions & 22 deletions requirements.txt

This file was deleted.

1 change: 1 addition & 0 deletions src/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from . import dependencies
2 changes: 1 addition & 1 deletion src/admin/email.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
GMAIL_ADDRESS = "csss-site@gmail.com"
GMAIL_USERNAME = ""


# TODO: look into sending emails from an sfu maillist (this might be painful)
def send_email(
recipient_address: str,
Expand All @@ -22,4 +23,3 @@ def send_email(

mail.sendmail(GMAIL_ADDRESS, recipient_address, content)
mail.quit()

1 change: 1 addition & 0 deletions src/auth/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from auth import crud
71 changes: 24 additions & 47 deletions src/auth/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,22 @@
import sqlalchemy
from sqlalchemy.ext.asyncio import AsyncSession

from auth.tables import SiteUser, UserSession
from auth.tables import SiteUserDB, UserSession

_logger = logging.getLogger(__name__)


async def create_user_session(db_session: AsyncSession, session_id: str, computing_id: str):
"""
Updates the past user session if one exists, so no duplicate sessions can ever occur.

Also, adds the new user to the SiteUser table if it's their first time logging in.
"""
existing_user_session = await db_session.scalar(
sqlalchemy
.select(UserSession)
.where(UserSession.computing_id == computing_id)
sqlalchemy.select(UserSession).where(UserSession.computing_id == computing_id)
)
existing_user = await db_session.scalar(
sqlalchemy
.select(SiteUser)
.where(SiteUser.computing_id == computing_id)
sqlalchemy.select(SiteUserDB).where(SiteUserDB.computing_id == computing_id)
)

if existing_user is None:
Expand All @@ -31,11 +28,9 @@ async def create_user_session(db_session: AsyncSession, session_id: str, computi
_logger.warning(f"User session {session_id} exists for non-existent user {computing_id} ... !")

# add new user to User table if it's their first time logging in
db_session.add(SiteUser(
computing_id=computing_id,
first_logged_in=datetime.now(),
last_logged_in=datetime.now()
))
db_session.add(
SiteUserDB(computing_id=computing_id, first_logged_in=datetime.now(), last_logged_in=datetime.now())
)

if existing_user_session is not None:
existing_user_session.issue_time = datetime.now()
Expand All @@ -44,11 +39,13 @@ async def create_user_session(db_session: AsyncSession, session_id: str, computi
# update the last time the user logged in to now
existing_user.last_logged_in = datetime.now()
else:
db_session.add(UserSession(
session_id=session_id,
computing_id=computing_id,
issue_time=datetime.now(),
))
db_session.add(
UserSession(
session_id=session_id,
computing_id=computing_id,
issue_time=datetime.now(),
)
)


async def remove_user_session(db_session: AsyncSession, session_id: str):
Expand All @@ -73,52 +70,32 @@ async def task_clean_expired_user_sessions(db_session: AsyncSession):


# get the site user given a session ID; returns None when session is invalid
async def get_site_user(db_session: AsyncSession, session_id: str) -> SiteUser | None:
query = (
sqlalchemy
.select(UserSession)
.where(UserSession.session_id == session_id)
)
async def get_site_user(db_session: AsyncSession, session_id: str) -> SiteUserDB | None:
query = sqlalchemy.select(UserSession).where(UserSession.session_id == session_id)
user_session = await db_session.scalar(query)
if user_session is None:
return None

query = (
sqlalchemy
.select(SiteUser)
.where(SiteUser.computing_id == user_session.computing_id)
)
query = sqlalchemy.select(SiteUserDB).where(SiteUserDB.computing_id == user_session.computing_id)
return await db_session.scalar(query)


async def site_user_exists(db_session: AsyncSession, computing_id: str) -> bool:
user = await db_session.scalar(
sqlalchemy
.select(SiteUser)
.where(SiteUser.computing_id == computing_id)
)
user = await db_session.scalar(sqlalchemy.select(SiteUserDB).where(SiteUserDB.computing_id == computing_id))
return user is not None


# update the optional user info for a given site user (e.g., display name, profile picture, ...)
async def update_site_user(
db_session: AsyncSession,
session_id: str,
profile_picture_url: str
) -> bool:
query = (
sqlalchemy
.select(UserSession)
.where(UserSession.session_id == session_id)
)
async def update_site_user(db_session: AsyncSession, session_id: str, profile_picture_url: str) -> bool:
query = sqlalchemy.select(UserSession).where(UserSession.session_id == session_id)
user_session = await db_session.scalar(query)
if user_session is None:
return False

query = (
sqlalchemy
.update(SiteUser)
.where(SiteUser.computing_id == user_session.computing_id)
.values(profile_picture_url = profile_picture_url)
sqlalchemy.update(SiteUserDB)
.where(SiteUserDB.computing_id == user_session.computing_id)
.values(profile_picture_url=profile_picture_url)
)
await db_session.execute(query)

Expand Down
3 changes: 3 additions & 0 deletions src/auth/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,17 @@ class LoginBodyParams(BaseModel):
ticket: str = Field(description="Ticket return from SFU's CAS system")
redirect_url: str | None = Field(None, description="Optional redirect URL")


class UpdateUserParams(BaseModel):
profile_picture_url: str


class UserSessionModel(BaseModel):
computing_id: str
issue_time: datetime
session_id: str


class SiteUserModel(BaseModel):
computing_id: str
first_logged_in: datetime
Expand Down
8 changes: 2 additions & 6 deletions src/auth/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class UserSession(Base):
) # the space needed to store 256 bytes in base64


class SiteUser(Base):
class SiteUserDB(Base):
# user is a reserved word in postgres
# see: https://stackoverflow.com/questions/22256124/cannot-create-a-database-table-named-user-in-postgresql
__tablename__ = "site_user"
Expand All @@ -44,11 +44,7 @@ class SiteUser(Base):
profile_picture_url: Mapped[str | None] = mapped_column(Text, nullable=True)

def serialize(self) -> dict[str, str | int | bool | None]:

res = {
"computing_id": self.computing_id,
"profile_picture_url": self.profile_picture_url
}
res = {"computing_id": self.computing_id, "profile_picture_url": self.profile_picture_url}
if self.first_logged_in is not None:
res["first_logged_in"] = self.first_logged_in.isoformat()
if self.last_logged_in is not None:
Expand Down
2 changes: 1 addition & 1 deletion src/auth/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,5 @@ def serializable_dict(self):
"computing_id": self.computing_id,
"first_logged_in": self.first_logged_in,
"last_logged_in": self.last_logged_in,
"profile_picture_url": self.profile_picture_url
"profile_picture_url": self.profile_picture_url,
}
Loading