Update syntax highlighting

This commit is contained in:
William Fu-Hinthorn
2024-12-18 17:51:07 -08:00
parent ce239c784a
commit 1c1772f7ec
3 changed files with 33 additions and 30 deletions
+9 -9
View File
@@ -96,7 +96,7 @@ And we'll keep our existing resource authorization logic unchanged
Let's update `src/security/auth.py` to implement this:
```python
```python hl_lines="8-9 20-30" title="src/security/auth.py"
import os
import httpx
from langgraph_sdk import Auth
@@ -135,6 +135,7 @@ async def get_current_user(authorization: str | None):
except Exception as e:
raise Auth.exceptions.HTTPException(status_code=401, detail=str(e))
# ... the rest is the same as before
# Keep our resource authorization from the previous tutorial
@auth.on
@@ -230,10 +231,8 @@ async def login(email: str, password: str):
"Content-Type": "application/json"
},
)
if response.status_code == 200:
return response.json()["access_token"]
else:
raise ValueError(f"Login failed: {response.status_code} - {response.text}")
assert response.status_code == 200
return response.json()["access_token"]
# Log in as user 1
@@ -268,10 +267,11 @@ except Exception as e:
```
The output should look like this:
> ➜ custom-auth SUPABASE_ANON_KEY=eyJh... python test_oauth.py CHANGEME@example.com
> ✅ User 1 created thread: d6af3754-95df-4176-aa10-dbd8dca40f1a
> ✅ Unauthenticated access blocked: Client error '403 Forbidden' for url 'http://localhost:2024/threads'
> ✅ User 2 blocked from User 1's thread: Client error '404 Not Found' for url 'http://localhost:2024/threads/d6af3754-95df-4176-aa10-dbd8dca40f1a'
```shell
✅ User 1 created thread: d6af3754-95df-4176-aa10-dbd8dca40f1a
✅ Unauthenticated access blocked: Client error '403 Forbidden' for url 'http://localhost:2024/threads'
✅ User 2 blocked from User 1's thread: Client error '404 Not Found' for url 'http://localhost:2024/threads/d6af3754-95df-4176-aa10-dbd8dca40f1a'
```
Perfect! Our authentication and authorization are working together:
1. Users must log in to access the bot
+8 -3
View File
@@ -41,10 +41,10 @@ The [`Auth`](../../cloud/reference/sdk/python_sdk_ref.md#langgraph_sdk.auth.Auth
Create a new file `src/security/auth.py`. This is where our code will live to check if users are allowed to access our bot:
```python
```python hl_lines="10 15-16" title="src/security/auth.py"
from langgraph_sdk import Auth
# This is our toy user database
# This is our toy user database. Do not do this in production
VALID_TOKENS = {
"user1-token": {"id": "user1", "name": "Alice"},
"user2-token": {"id": "user2", "name": "Bob"},
@@ -80,8 +80,13 @@ Notice that our [authentication](../../cloud/reference/sdk/python_sdk_ref.md#lan
Now tell LangGraph to use our authentication by adding the following to the [`langgraph.json`](../../cloud/reference/cli.md#configuration-file) configuration:
```json
```json hl_lines="7-9" title="langgraph.json"
{
"dependencies": ["."],
"graphs": {
"agent": "./src/agent/graph.py:graph"
},
"env": ".env",
"auth": {
"path": "src/security/auth.py:auth"
}
+16 -18
View File
@@ -32,7 +32,7 @@ Authorization handlers are functions that run **after** authentication succeeds.
Let's update our `src/security/auth.py` and add one authorization handler that is run on every request:
```python hl_lines="29-39"
```python hl_lines="29-39" title="src/security/auth.py"
from langgraph_sdk import Auth
# Keep our test users from the previous tutorial
@@ -218,32 +218,30 @@ Notice that instead of one global handler, we now have specific handlers for:
3. Creating runs
4. Accessing assistants
The first three of these match specific **actions** on each resource (see [resource actions](../../concepts/auth.md#resource-actions)), while the last one (`@auth.on.assistants`) matches _any_ action on the `assistants` resource. For each request, LangGraph will run the most specific handler that matches the resource and action being accessed. This means that the four handlers above will run rather than the broad "@auth.on" handler.
The first three of these match specific **actions** on each resource (see [resource actions](../../concepts/auth.md#resource-actions)), while the last one (`@auth.on.assistants`) matches _any_ action on the `assistants` resource. For each request, LangGraph will run the most specific handler that matches the resource and action being accessed. This means that the four handlers above will run rather than the broadly scoped "`@auth.on`" handler.
Try adding the following test code to `test_private.py`:
Try adding the following test code to your test file:
```python
async def test_private():
# ... Same as before
# Try creating an assistant. This should fail
try:
await alice.assistants.create("agent")
print("❌ Alice shouldn't be able to create assistants!")
except Exception as e:
print("✅ Alice correctly denied access:", e)
# ... Same as before
# Try creating an assistant. This should fail
try:
await alice.assistants.create("agent")
print("❌ Alice shouldn't be able to create assistants!")
except Exception as e:
print("✅ Alice correctly denied access:", e)
# Try searching for assistants. This also should fail
try:
await alice.assistants.search()
print("❌ Alice shouldn't be able to search assistants!")
except Exception as e:
print("✅ Alice correctly denied access to searching assistants:", e)
# Try searching for assistants. This also should fail
try:
await alice.assistants.search()
print("❌ Alice shouldn't be able to search assistants!")
except Exception as e:
print("✅ Alice correctly denied access to searching assistants:", e)
```
And then run the test code again:
```bash
> python test_private.py
✅ Alice created thread: dcea5cd8-eb70-4a01-a4b6-643b14e8f754
✅ Bob correctly denied access: Client error '404 Not Found' for url 'http://localhost:2024/threads/dcea5cd8-eb70-4a01-a4b6-643b14e8f754'
For more information check: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404