Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Matomo #769

Draft
wants to merge 7 commits into
base: develop
Choose a base branch
from
Draft
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
71 changes: 53 additions & 18 deletions backend/src/xfd_django/xfd_api/api_methods/proxy.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,11 @@
from typing import Optional

# Third-Party Libraries
from fastapi import Request
from fastapi.responses import Response
from fastapi import HTTPException, Request
from fastapi.responses import RedirectResponse, Response
import httpx


# Helper function to handle cookie manipulation
def manipulate_cookie(request: Request, cookie_name: str):
"""Manipulate cookie."""
cookies = request.cookies.get(cookie_name)
if cookies:
return {cookie_name: cookies}
return {}
from xfd_api.auth import get_current_active_user
from xfd_api.schema_models.user import User as UserSchema


# Helper function to proxy requests
Expand All @@ -25,17 +18,17 @@ async def proxy_request(
path: Optional[str] = None,
cookie_name: Optional[str] = None,
):
"""Proxy the request to the target URL."""
"""Proxy requests to the specified target URL with optional cookie handling."""
headers = dict(request.headers)

# Cookie manipulation for specific cookie names
# Include specified cookie in the headers if present
if cookie_name:
cookies = manipulate_cookie(request, cookie_name)
cookies = request.cookies.get(cookie_name)
if cookies:
headers["Cookie"] = "{}={}".format(cookie_name, cookies[cookie_name])

# Make the request to the target URL
async with httpx.AsyncClient() as client:
# Send the request to the target
async with httpx.AsyncClient(timeout=httpx.Timeout(30.0)) as client:
proxy_response = await client.request(
method=request.method,
url="{}/{}".format(target_url, path),
Expand All @@ -44,12 +37,54 @@ async def proxy_request(
content=await request.body(),
)

# Remove chunked encoding for API Gateway compatibility
# Adjust response headers
proxy_response_headers = dict(proxy_response.headers)
proxy_response_headers.pop("transfer-encoding", None)
for header in ["content-encoding", "transfer-encoding", "content-length"]:
proxy_response_headers.pop(header, None)

return Response(
content=proxy_response.content,
status_code=proxy_response.status_code,
headers=proxy_response_headers,
)


async def matomo_proxy_handler(
request: Request,
path: str,
current_user: Optional[UserSchema],
MATOMO_URL: str,
):
"""
Handle Matomo-specific proxy logic.

Includes public paths, font redirects, and authentication for private paths.
"""
# Redirect font requests to CDN
font_paths = {
"/plugins/Morpheus/fonts/matomo.woff2": "https://cdn.jsdelivr.net/gh/matomo-org/[email protected]/plugins/Morpheus/fonts/matomo.woff2",
"/plugins/Morpheus/fonts/matomo.woff": "https://cdn.jsdelivr.net/gh/matomo-org/[email protected]/plugins/Morpheus/fonts/matomo.woff",
"/plugins/Morpheus/fonts/matomo.ttf": "https://cdn.jsdelivr.net/gh/matomo-org/[email protected]/plugins/Morpheus/fonts/matomo.ttf",
}
if path in font_paths:
return RedirectResponse(url=font_paths[path])

# Public paths allowed without authentication
public_paths = ["matomo.php", "matomo.js", "index.php"]
if path in public_paths:
print("THIS IS A PUBLIC PATH")
return await proxy_request(request, MATOMO_URL, path)

# Authenticate private paths
if not current_user:
current_user = await get_current_active_user(request)
if current_user is None or current_user.userType != "globalAdmin":
raise HTTPException(status_code=403, detail="Unauthorized")

# Proxy private paths
return await proxy_request(
request=request,
target_url=MATOMO_URL,
path=path,
cookie_name="MATOMO_SESSID",
)
46 changes: 13 additions & 33 deletions backend/src/xfd_django/xfd_api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@

# Third-Party Libraries
from fastapi import APIRouter, Body, Depends, HTTPException, Query, Request, status
from fastapi.responses import RedirectResponse
from redis import asyncio as aioredis

# from .schemas import Cpe
Expand Down Expand Up @@ -108,40 +107,17 @@ async def get_redis_client(request: Request):
# Matomo Proxy
@api_router.api_route(
"/matomo/{path:path}",
dependencies=[Depends(get_current_active_user)],
methods=["GET", "POST", "PUT", "DELETE"],
tags=["Analytics"],
)
async def matomo_proxy(
path: str, request: Request, current_user: User = Depends(get_current_active_user)
path: str,
request: Request,
current_user: Optional[UserSchema] = None, # Optional for public paths
):
"""Proxy requests to the Matomo analytics instance."""
# Public paths -- directly allowed
allowed_paths = ["/matomo.php", "/matomo.js"]
if any(
[request.url.path.startswith(allowed_path) for allowed_path in allowed_paths]
):
return await proxy.proxy_request(path, request, os.getenv("MATOMO_URL"))

# Redirects for specific font files
if request.url.path in [
"/plugins/Morpheus/fonts/matomo.woff2",
"/plugins/Morpheus/fonts/matomo.woff",
"/plugins/Morpheus/fonts/matomo.ttf",
]:
return RedirectResponse(
url="https://cdn.jsdelivr.net/gh/matomo-org/[email protected]{}".format(
request.url.path
)
)

# Ensure only global admin can access other paths
if current_user.userType != "globalAdmin":
raise HTTPException(status_code=403, detail="Unauthorized")

# Handle the proxy request to Matomo
return await proxy.proxy_request(
request, os.getenv("MATOMO_URL", ""), path, cookie_name="MATOMO_SESSID"
)
MATOMO_URL = os.getenv("MATOMO_URL", "")
return await proxy.matomo_proxy_handler(request, path, current_user, MATOMO_URL)


# P&E Proxy
Expand All @@ -152,15 +128,19 @@ async def matomo_proxy(
tags=["Analytics"],
)
async def pe_proxy(
path: str, request: Request, current_user: User = Depends(get_current_active_user)
path: str,
request: Request,
current_user: UserSchema = Depends(get_current_active_user),
):
"""Proxy requests to the P&E Django application."""
PE_API_URL = os.getenv("PE_API_URL", "")

# Ensure only Global Admin and Global View users can access
if current_user.userType not in ["globalView", "globalAdmin"]:
raise HTTPException(status_code=403, detail="Unauthorized")

# Handle the proxy request to the P&E Django application
return await proxy.proxy_request(request, os.getenv("PE_API_URL", ""), path)
# Proxy the request to the P&E Django application
return await proxy.proxy_request(request, PE_API_URL, path)


# ========================================
Expand Down
4 changes: 2 additions & 2 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ services:
environment:
- MYSQL_ROOT_PASSWORD=password
logging:
driver: none
driver: json-file
ports:
- 3306:3306

Expand All @@ -142,7 +142,7 @@ services:
- MATOMO_GENERAL_PROXY_URI_HEADER=1
- MATOMO_GENERAL_ASSUME_SECURE_PROTOCOL=1
logging:
driver: none
driver: json-file
ports:
- "8080:80"

Expand Down
9 changes: 9 additions & 0 deletions frontend/src/pages/Settings/Settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,15 @@ const Settings: React.FC = () => {
.join(', ')}
</h2>
<h2>Region: {user && user.regionId ? user.regionId : 'None'} </h2>
{user?.userType === 'globalAdmin' && (
<>
<a href={`${process.env.REACT_APP_API_URL}/matomo/index.php`}>
<Button type="button">Matomo</Button>
</a>
<br />
<br />
</>
)}
<Button type="button" onClick={logout}>
Logout
</Button>
Expand Down