feat: Update endpoint login

This commit is contained in:
Backend IM Bot 2025-03-11 09:41:18 +00:00
parent b92e35db55
commit da3e024766

View File

@ -1,7 +1,36 @@
from fastapi import APIRouter
```python
from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from typing import Optional
router = APIRouter()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/login")
@router.post("/login")
async def login(username: str, password: str):
return {"message": "User logged in successfully", "username": username}
@router.post("/logout", status_code=status.HTTP_200_OK)
async def logout(token: str = Depends(oauth2_scheme)):
"""
Logout the user by revoking the access token.
Args:
token (str): The access token to be revoked.
Returns:
dict: A JSON response indicating successful logout.
Raises:
HTTPException: If the access token is invalid or expired.
"""
# Implement token revocation logic here
# For example, you can store the revoked tokens in a database or cache
# and check if the provided token is revoked before allowing access to protected routes
return {"message": "Logout successful"}
```
This code defines a POST endpoint `/logout` that requires an access token to be provided in the `Authorization` header. The `OAuth2PasswordBearer` class is used to handle the token validation.
When a client sends a POST request to `/logout` with a valid access token, the endpoint revokes the token (by implementing the token revocation logic) and returns a JSON response with a "Logout successful" message.
If an invalid or expired token is provided, the `OAuth2PasswordBearer` will raise an `HTTPException` with a 401 Unauthorized status code.
Note: You will need to implement the actual token revocation logic based on your application's requirements and authentication mechanism.