aut flow
This commit is contained in:
134
app/api/auth.py
134
app/api/auth.py
@@ -225,6 +225,56 @@ async def telegram_binding_confirm(
|
||||
return TelegramBindingConfirmResponse(**result)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/telegram/store-token",
|
||||
response_model=dict,
|
||||
summary="Store JWT token for Telegram user (called after binding confirmation)",
|
||||
)
|
||||
async def telegram_store_token(
|
||||
chat_id: int,
|
||||
jwt_token: str,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Store JWT token in Redis after successful binding confirmation.
|
||||
|
||||
**Flow:**
|
||||
1. User confirms binding via /telegram/confirm
|
||||
2. Frontend receives jwt_token
|
||||
3. Frontend calls this endpoint to cache token in bot's Redis
|
||||
4. Bot can now use token for API calls
|
||||
|
||||
**Usage:**
|
||||
```
|
||||
POST /auth/telegram/store-token?chat_id=12345&jwt_token=eyJ...
|
||||
```
|
||||
"""
|
||||
|
||||
import redis
|
||||
|
||||
# Get Redis client from settings
|
||||
from app.core.config import settings
|
||||
redis_client = redis.from_url(settings.redis_url)
|
||||
|
||||
# Validate JWT token structure
|
||||
try:
|
||||
jwt_manager.verify_token(jwt_token)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid token: {e}")
|
||||
|
||||
# Store JWT in Redis with 30-day TTL
|
||||
cache_key = f"chat_id:{chat_id}:jwt"
|
||||
redis_client.setex(cache_key, 86400 * 30, jwt_token)
|
||||
|
||||
logger.info(f"JWT token stored for chat_id={chat_id}")
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"message": "Token stored successfully",
|
||||
"chat_id": chat_id,
|
||||
}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/telegram/authenticate",
|
||||
response_model=dict,
|
||||
@@ -235,11 +285,11 @@ async def telegram_authenticate(
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Get JWT token for Telegram user.
|
||||
Get JWT token for Telegram user (bot authentication).
|
||||
|
||||
**Usage in Bot:**
|
||||
```python
|
||||
# After user binding is confirmed
|
||||
# Get token for authenticated user
|
||||
response = api.post("/auth/telegram/authenticate?chat_id=12345")
|
||||
jwt_token = response["jwt_token"]
|
||||
```
|
||||
@@ -254,6 +304,86 @@ async def telegram_authenticate(
|
||||
return result
|
||||
|
||||
|
||||
@router.post(
|
||||
"/telegram/register",
|
||||
response_model=dict,
|
||||
summary="Create new user with Telegram binding",
|
||||
)
|
||||
async def telegram_register(
|
||||
chat_id: int,
|
||||
username: Optional[str] = None,
|
||||
first_name: Optional[str] = None,
|
||||
last_name: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""
|
||||
Quick registration for new Telegram user.
|
||||
|
||||
**Flow:**
|
||||
1. Bot calls this endpoint on /start
|
||||
2. Creates new User with telegram_id
|
||||
3. Returns JWT for immediate API access
|
||||
4. User can update email/password later
|
||||
|
||||
**Usage in Bot:**
|
||||
```python
|
||||
result = api.post(
|
||||
"/auth/telegram/register",
|
||||
params={
|
||||
"chat_id": 12345,
|
||||
"username": "john_doe",
|
||||
"first_name": "John",
|
||||
"last_name": "Doe",
|
||||
}
|
||||
)
|
||||
jwt_token = result["jwt_token"]
|
||||
```
|
||||
"""
|
||||
|
||||
from app.db.models.user import User
|
||||
|
||||
# Check if user already exists
|
||||
existing = db.query(User).filter_by(telegram_id=chat_id).first()
|
||||
if existing:
|
||||
service = AuthService(db)
|
||||
result = await service.authenticate_telegram_user(chat_id=chat_id)
|
||||
return {
|
||||
**result,
|
||||
"created": False,
|
||||
"message": "User already exists",
|
||||
}
|
||||
|
||||
# Create new user
|
||||
new_user = User(
|
||||
telegram_id=chat_id,
|
||||
username=username,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
is_active=True,
|
||||
)
|
||||
|
||||
try:
|
||||
db.add(new_user)
|
||||
db.commit()
|
||||
db.refresh(new_user)
|
||||
except Exception as e:
|
||||
db.rollback()
|
||||
logger.error(f"Failed to create user: {e}")
|
||||
raise HTTPException(status_code=400, detail="Failed to create user")
|
||||
|
||||
# Create JWT
|
||||
service = AuthService(db)
|
||||
result = await service.authenticate_telegram_user(chat_id=chat_id)
|
||||
|
||||
if result:
|
||||
result["created"] = True
|
||||
result["message"] = f"User created successfully (user_id={new_user.id})"
|
||||
|
||||
logger.info(f"New Telegram user registered: chat_id={chat_id}, user_id={new_user.id}")
|
||||
|
||||
return result or {"success": False, "error": "Failed to create user"}
|
||||
|
||||
|
||||
@router.post(
|
||||
"/logout",
|
||||
summary="Logout user",
|
||||
|
||||
Reference in New Issue
Block a user