Skip to content
Open
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
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.
43 changes: 40 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,11 @@ 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" }
]
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.

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()

67 changes: 21 additions & 46 deletions src/auth/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,27 @@

_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)
)
existing_user = await db_session.scalar(
sqlalchemy
.select(SiteUser)
.where(SiteUser.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))

if existing_user is None:
if existing_user_session is not None:
# log this strange case that shouldn't be possible
_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(
SiteUser(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 +37,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 @@ -74,51 +69,31 @@ 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)
)
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(SiteUser).where(SiteUser.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(SiteUser).where(SiteUser.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)
sqlalchemy.update(SiteUser)
.where(SiteUser.computing_id == user_session.computing_id)
.values(profile_picture_url = profile_picture_url)
.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
6 changes: 1 addition & 5 deletions src/auth/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -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