|
9 | 9 | from fastmcp.tools import Tool |
10 | 10 | from mcp import types as mt |
11 | 11 | from ex_app.lib.tools import get_tools |
| 12 | +import requests |
| 13 | + |
| 14 | +def get_user(authorization_header: str, nc: NextcloudApp) -> str: |
| 15 | + print(f"http://{nc.app_cfg.endpoint}/ocs/v2.php/cloud/user") |
| 16 | + response = requests.get( |
| 17 | + f"{nc.app_cfg.endpoint}/ocs/v2.php/cloud/user", |
| 18 | + headers={ |
| 19 | + "Accept": "application/json", |
| 20 | + "Ocs-Apirequest": "1", |
| 21 | + "Authorization": authorization_header, |
| 22 | + }, |
| 23 | + ) |
| 24 | + if response.status_code != 200: |
| 25 | + raise Exception("Failed to get user info") |
| 26 | + return response.json()["ocs"]["data"]["id"] |
| 27 | + |
12 | 28 |
|
13 | 29 | class UserAuthMiddleware(Middleware): |
14 | 30 | async def on_message(self, context: MiddlewareContext, call_next): |
15 | 31 | # Middleware stores user info in context state |
16 | | - user = context.fastmcp_context.request_context.request.headers.get("Authorization") |
17 | | - if user is None: |
| 32 | + authorization_header = context.fastmcp_context.request_context.request.headers.get("Authorization") |
| 33 | + if authorization_header is None: |
18 | 34 | raise Exception("Authorization header is missing/invalid") |
19 | | - if user.startswith("Bearer "): |
20 | | - user = user[len("Bearer "):] |
21 | 35 | nc = NextcloudApp() |
| 36 | + user = get_user(authorization_header, nc) |
| 37 | + print(user) |
22 | 38 | nc.set_user(user) |
23 | 39 | context.fastmcp_context.set_state("nextcloud", nc) |
24 | 40 | return await call_next(context) |
@@ -57,7 +73,8 @@ async def wrapper(*args, **kwargs): |
57 | 73 | ctx = get_context() |
58 | 74 | nc = ctx.get_state('nextcloud') |
59 | 75 | safe, dangerous = await get_tools(nc) |
60 | | - for t in safe + dangerous: |
| 76 | + tools = safe + dangerous |
| 77 | + for t in tools: |
61 | 78 | if hasattr(t, "func") and t.func and t.name == tool.__name__: |
62 | 79 | return t.func(*args, **kwargs) |
63 | 80 | raise RuntimeError("Tool not found") |
|
0 commit comments