|
1 | 1 | import logging
|
2 | 2 |
|
3 |
| -from fastapi import APIRouter, Request |
| 3 | +from fastapi import APIRouter, status |
| 4 | +from fastapi.responses import JSONResponse, Response |
| 5 | +from pydantic import BaseModel |
4 | 6 |
|
5 | 7 | router = APIRouter(prefix="/user_registered")
|
6 | 8 |
|
7 | 9 |
|
| 10 | +class UserRegisteredWebhook(BaseModel): |
| 11 | + user_id: str |
| 12 | + email: str |
| 13 | + |
| 14 | + |
8 | 15 | @router.post("/")
|
9 |
| -async def user_registered(request: Request): # pragma: no cover |
10 |
| - # Here we could check the email and add staff metadata to the identity |
11 |
| - logging.info("User registered", extra={"body": await request.json()}) |
12 |
| - return {"user_registered": "OK"} |
| 16 | +async def user_registered(user: UserRegisteredWebhook): # pragma: no cover |
| 17 | + """ |
| 18 | + Handles the user registration webhook. |
| 19 | +
|
| 20 | + This function is triggered when a user registration webhook is received. |
| 21 | + It logs the event details, evaluates the email validity, and returns an |
| 22 | + appropriate HTTP response based on the validation. If the user's email |
| 23 | + is invalid, it returns an error response along with a structured error |
| 24 | + message. Otherwise, it confirms successful processing with no additional |
| 25 | + content. |
| 26 | +
|
| 27 | + Args: |
| 28 | + user (UserRegisteredWebhook): The webhook payload received when a user |
| 29 | + registers, containing user details such as email and traits. |
| 30 | +
|
| 31 | + Returns: |
| 32 | + Response: An HTTP response with a 403 Forbidden status and structured |
| 33 | + error message if the user email is invalid. |
| 34 | + Otherwise, an HTTP 204 No Content response to confirm successful |
| 35 | + processing. |
| 36 | + """ |
| 37 | + logging.info("User registered", extra={"user": user.model_dump()}) |
| 38 | + |
| 39 | + error_message = { |
| 40 | + "messages": [ |
| 41 | + { |
| 42 | + "instance_ptr": "#/traits/email", |
| 43 | + "messages": [ |
| 44 | + { |
| 45 | + "id": 123, # Error id to be evaluated in frontend |
| 46 | + "text": "You are not allowed to register.", |
| 47 | + "type": "error", |
| 48 | + "context": { # Additional context we can send to the Frontend |
| 49 | + "value": "short value", |
| 50 | + "any": "additional information", |
| 51 | + }, |
| 52 | + } |
| 53 | + ], |
| 54 | + } |
| 55 | + ] |
| 56 | + } |
| 57 | + |
| 58 | + if user. email == "[email protected]": |
| 59 | + return JSONResponse( |
| 60 | + error_message, |
| 61 | + status.HTTP_403_FORBIDDEN, |
| 62 | + ) |
| 63 | + else: |
| 64 | + return Response(status_code=status.HTTP_204_NO_CONTENT) |
0 commit comments