Skip to content
Merged
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
5 changes: 0 additions & 5 deletions .flake8

This file was deleted.

2 changes: 1 addition & 1 deletion .github/workflows/pytest.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9", "3.10", "3.11"]
python-version: ["3.11", "3.12"]

steps:
- uses: actions/checkout@v2
Expand Down
17 changes: 9 additions & 8 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
repos:
- repo: https://github.com/ambv/black
rev: 24.1.1
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.9.9
hooks:
- id: black
- repo: https://github.com/pycqa/flake8
rev: 7.0.0
hooks:
- id: flake8
# Run the linter.
- id: ruff
# Run the formatter.
- id: ruff-format

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.8.0
rev: v1.15.0
hooks:
- id: mypy
additional_dependencies:
Expand Down
21 changes: 21 additions & 0 deletions app/_vendor/LICENSE.fastapi_versioning
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Dean Way

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Empty file added app/_vendor/__init__.py
Empty file.
8 changes: 8 additions & 0 deletions app/_vendor/fastapi_versioning/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from .routing import versioned_api_route
from .versioning import VersionedFastAPI, version

__all__ = [
"VersionedFastAPI",
"versioned_api_route",
"version",
]
18 changes: 18 additions & 0 deletions app/_vendor/fastapi_versioning/routing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
from typing import Any, Type

from fastapi.routing import APIRoute


def versioned_api_route(
major: int = 1, minor: int = 0, route_class: Type[APIRoute] = APIRoute
) -> Type[APIRoute]:
class VersionedAPIRoute(route_class): # type: ignore
def __init__(self, *args: Any, **kwargs: Any) -> None:
super().__init__(*args, **kwargs)
try:
self.endpoint._api_version = (major, minor)
except AttributeError:
# Support bound methods
self.endpoint.__func__._api_version = (major, minor)

return VersionedAPIRoute
83 changes: 83 additions & 0 deletions app/_vendor/fastapi_versioning/versioning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
from collections import defaultdict
from typing import Any, Callable, Dict, List, Tuple, TypeVar, cast

from fastapi import FastAPI
from fastapi.routing import APIRoute
from starlette.routing import BaseRoute

CallableT = TypeVar("CallableT", bound=Callable[..., Any])


def version(major: int, minor: int = 0) -> Callable[[CallableT], CallableT]:
def decorator(func: CallableT) -> CallableT:
func._api_version = (major, minor) # type: ignore
return func

return decorator


def version_to_route(
route: BaseRoute,
default_version: Tuple[int, int],
) -> Tuple[Tuple[int, int], APIRoute]:
api_route = cast(APIRoute, route)
version = getattr(api_route.endpoint, "_api_version", default_version)
return version, api_route


def VersionedFastAPI(
app: FastAPI,
version_format: str = "{major}.{minor}",
prefix_format: str = "/v{major}_{minor}",
default_version: Tuple[int, int] = (1, 0),
enable_latest: bool = False,
**kwargs: Any,
) -> FastAPI:
parent_app = FastAPI(
title=app.title,
**kwargs,
)
version_route_mapping: Dict[Tuple[int, int], List[APIRoute]] = defaultdict(list)
version_routes = [version_to_route(route, default_version) for route in app.routes]

for version, route in version_routes:
version_route_mapping[version].append(route)

unique_routes = {}
versions = sorted(version_route_mapping.keys())
for version in versions:
major, minor = version
prefix = prefix_format.format(major=major, minor=minor)
semver = version_format.format(major=major, minor=minor)
versioned_app = FastAPI(
title=app.title,
description=app.description,
version=semver,
docs_url=None,
redoc_url=None,
)
for route in version_route_mapping[version]:
for method in route.methods:
unique_routes[route.path + "|" + method] = route
for route in unique_routes.values():
versioned_app.router.routes.append(route)
parent_app.mount(prefix, versioned_app)

@parent_app.get(f"{prefix}/openapi.json", name=semver, tags=["Versions"])
@parent_app.get(f"{prefix}/docs", name=semver, tags=["Documentations"])
def noop() -> None: ...

if enable_latest:
prefix = "/latest"
major, minor = version
semver = version_format.format(major=major, minor=minor)
versioned_app = FastAPI(
title=app.title,
description=app.description,
version=semver,
)
for route in unique_routes.values():
versioned_app.router.routes.append(route)
parent_app.mount(prefix, versioned_app)

return parent_app
129 changes: 115 additions & 14 deletions app/api/login.py
Original file line number Diff line number Diff line change
@@ -1,32 +1,133 @@
import httpx
from datetime import datetime, timedelta, timezone
from fastapi import APIRouter, Depends, HTTPException, Response, status
from fastapi import APIRouter, Depends, HTTPException, Response, Request, status
from fastapi.security import OAuth2PasswordRequestForm
from fastapi.logger import logger
from sqlalchemy.orm import Session
from .. import deps, crud, utils, auth
from ..settings import ACCESS_TOKEN_EXPIRE_MINUTES
from .. import deps, crud, utils, auth, schemas
from ..settings import (
ACCESS_TOKEN_EXPIRE_MINUTES,
OIDC_CLIENT_SECRET,
OIDC_SCOPE,
)

router = APIRouter()


def create_access_token(db, username, response) -> dict[str, str]:
db_user = crud.get_user_by_username(db, username)
if db_user is None:
db_user = crud.create_user(db, username)
response.status_code = status.HTTP_201_CREATED
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = utils.create_access_token(db_user.username, expire=expire)
crud.update_user_login_token_expire_date(db, db_user, expire)
logger.info(f"User {username} successfully logged in")
return {"access_token": access_token, "token_type": "bearer"}


@router.post("/login", status_code=status.HTTP_200_OK)
def login(
response: Response,
db: Session = Depends(deps.get_db),
form_data: OAuth2PasswordRequestForm = Depends(),
):
if not auth.authenticate_user(form_data.username.lower(), form_data.password):
logger.warning(f"Authentication failed for {form_data.username.lower()}")
"""Login using username/password"""
username = form_data.username.lower()
if not auth.authenticate_user(username, form_data.password):
logger.warning(f"Authentication failed for {username}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
)
logger.info(f"User {form_data.username.lower()} successfully logged in")
db_user = crud.get_user_by_username(db, form_data.username.lower())
if db_user is None:
db_user = crud.create_user(db, form_data.username.lower())
response.status_code = status.HTTP_201_CREATED
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = utils.create_access_token(db_user.username, expire=expire)
crud.update_user_login_token_expire_date(db, db_user, expire)
return {"access_token": access_token, "token_type": "bearer"}
return create_access_token(db, username, response)


@router.post("/open_id_connect", status_code=status.HTTP_200_OK)
async def open_id_connect(
oidc_auth: schemas.OpenIdConnectAuth,
response: Response,
request: Request,
db: Session = Depends(deps.get_db),
):
"""Login using OpenID Connect Authentication Code flow from mobile client"""
oidc_config = request.state.oidc_config
data = {
"client_id": oidc_auth.client_id,
"client_secret": OIDC_CLIENT_SECRET,
"code": oidc_auth.code,
"code_verifier": oidc_auth.code_verifier,
"grant_type": "authorization_code",
"redirect_uri": oidc_auth.redirect_uri,
}
logger.info(
"Login via OIDC Authentication Code flow. "
f"Sending {data} to {oidc_config['token_endpoint']} to retrieve token."
)
async with httpx.AsyncClient() as client:
try:
response = await client.post(
oidc_config["token_endpoint"],
data=data,
)
response.raise_for_status()
except httpx.RequestError as exc:
logger.error(
f"An error occurred while requesting {exc.request.url!r}: {exc}."
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"An error occurred while requesting {exc.request.url!r}",
)
except httpx.HTTPStatusError as exc:
logger.error(f"Failed to get OIDC token: {response.content}")
raise HTTPException(
status_code=exc.response.status_code, detail="Failed to get OIDC token"
)
result = response.json()
access_token = result["access_token"]
id_token = result["id_token"]
logger.debug("Retrieved access and id tokens. Validating id_token.")
try:
utils.validate_id_token(
id_token,
access_token,
request.state.jwks_client,
request.state.oidc_config["id_token_signing_alg_values_supported"],
oidc_auth.client_id,
)
except Exception as e:
logger.warning(f"id_token validation failed: {e}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="id_token validation failed",
)
headers = {"Authorization": f"Bearer {access_token}"}
data = {
"client_id": oidc_auth.client_id,
"client_secret": OIDC_CLIENT_SECRET,
"scope": OIDC_SCOPE,
}
logger.info("Retrieving user info.")
try:
response = await client.post(
oidc_config["userinfo_endpoint"],
headers=headers,
data=data,
)
response.raise_for_status()
except httpx.RequestError as exc:
logger.error(
f"An error occurred while requesting {exc.request.url!r}: {exc}."
)
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=f"An error occurred while requesting {exc.request.url!r}",
)
except httpx.HTTPStatusError as exc:
logger.error(f"Failed to get user info: {response.content}")
raise HTTPException(
status_code=exc.response.status_code, detail="Failed to get user info"
)
username = response.json()["preferred_username"].lower()
return create_access_token(db, username, response)
2 changes: 1 addition & 1 deletion app/api/users.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from fastapi import APIRouter, Depends, Response, HTTPException, status
from fastapi_versioning import version
from .._vendor.fastapi_versioning import version
from sqlalchemy.orm import Session
from typing import List
from .. import deps, crud, models, schemas
Expand Down
5 changes: 1 addition & 4 deletions app/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,7 @@ def ldap_authenticate_user(username: str, password: str) -> bool:
validate=ssl.CERT_REQUIRED, version=ssl.PROTOCOL_TLSv1_2, ciphers="ALL"
)
server = ldap3.Server(LDAP_HOST, port=LDAP_PORT, use_ssl=LDAP_USE_SSL, tls=tls)
if LDAP_USER_DN:
user_search_dn = f"{LDAP_USER_DN},{LDAP_BASE_DN}"
else:
user_search_dn = LDAP_BASE_DN
user_search_dn = f"{LDAP_USER_DN},{LDAP_BASE_DN}" if LDAP_USER_DN else LDAP_BASE_DN
bind_user = f"{LDAP_USER_RDN_ATTR}={username},{user_search_dn}"
connection = ldap3.Connection(
server=server,
Expand Down
21 changes: 0 additions & 21 deletions app/cookie_auth.py

This file was deleted.

5 changes: 1 addition & 4 deletions app/crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,10 +215,7 @@ def get_user_notifications(
if filter_services_id is not None:
query = query.filter(models.Notification.service_id.in_(filter_services_id))
query = query.order_by(desc(models.Notification.timestamp))
if limit > 0:
query = query.limit(limit)
else:
query = query.all()
query = query.limit(limit) if limit > 0 else query.all()
notifications = [un.to_user_notification() for un in query]
# Sorting in ascending order is mostly for backward compatibility
if sort == schemas.SortOrder.asc:
Expand Down
Loading