Spaces:
Running

axeronis
fix: Duplicate keyword message in auth.py (update_me)
0c028d8
Raw History Blame Contribute Delete
28.5 kB
from fastapi import APIRouter, Depends, HTTPException, status, Request, BackgroundTasks
from sqlmodel import select
from sqlalchemy import func
from sqlmodel.ext.asyncio.session import AsyncSession
from pydantic import BaseModel, EmailStr
from typing import Optional
from uuid import UUID
import secrets
import httpx
from slowapi import Limiter
from slowapi.util import get_remote_address
from app.core.database import get_async_session
from app.core.config import settings
from app.core.security import create_access_token
from app.core.logging import get_logger
from app.api.deps import get_current_user
from app.models import User, Tenant, Partner
from app.models.partner import ReferredTenant
from app.models.user import UserRole
from app.services.email import get_email_service
from datetime import datetime, timedelta
import random
logger = get_logger(__name__)
router = APIRouter(prefix="/auth", tags=["Authentication"])
limiter = Limiter(key_func=get_remote_address)
# ============================================================================
# Schemas
# ============================================================================
class RegisterRequest(BaseModel):
email: EmailStr
password: str
company_name: str
full_name: Optional[str] = None
referral_code: Optional[str] = None # Partner referral code
class LoginRequest(BaseModel):
email: EmailStr
password: str
class TokenResponse(BaseModel):
access_token: str
token_type: str = "bearer"
user: dict
class UserResponse(BaseModel):
id: UUID
email: str
full_name: Optional[str]
avatar_url: Optional[str] = None
phone: Optional[str] = None
telegram_chat_id: Optional[str] = None
tenant_id: UUID
tenant_name: str
is_active: bool
is_superuser: bool = False
role: str # OWNER or MANAGER
class GoogleAuthRequest(BaseModel):
token: str # Google ID token
company_name: Optional[str] = None
referral_code: Optional[str] = None # Partner referral code
class VerifyRequest(BaseModel):
email: EmailStr
code: str
class ResendCodeRequest(BaseModel):
email: EmailStr
class ForgotPasswordRequest(BaseModel):
email: EmailStr
class ResetPasswordRequest(BaseModel):
email: EmailStr
code: str
new_password: str
class ChangePasswordRequest(BaseModel):
current_password: str
new_password: str
class UpdateProfileRequest(BaseModel):
full_name: Optional[str] = None
avatar_url: Optional[str] = None
phone: Optional[str] = None
telegram_chat_id: Optional[str] = None
# ============================================================================
# Auth Endpoints
# ============================================================================
@router.post("/register", response_model=TokenResponse)
@limiter.limit("5/minute")
async def register(
request: Request,
body: RegisterRequest,
background_tasks: BackgroundTasks,
session: AsyncSession = Depends(get_async_session)
):
"""
Register a new user and automatically create:
1. User account
2. New Tenant (Company)
3. Partner record with unique referral code
4. Link to referring partner (if referral_code provided)
Rate limit: 5 requests per minute per IP
"""
# Validate password strength
if len(body.password) < 8:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Password must be at least 8 characters long"
)
# Validate company name
if not body.company_name or len(body.company_name.strip()) < 2:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Company name must be at least 2 characters long"
)
# Check if user already exists
result = await session.execute(
select(User).where(User.email == body.email)
)
existing_user = result.scalar_one_or_none()
if existing_user:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="User already exists"
)
# TASK 2: Lookup Referring Partner (if referral code provided)
referring_partner_id = None
if body.referral_code:
logger.info("Referral code provided", referral_code=body.referral_code)
result = await session.execute(
select(Partner).where(Partner.referral_code == body.referral_code)
)
referring_partner = result.scalar_one_or_none()
if referring_partner:
referring_partner_id = referring_partner.id
logger.info(
"Found referring partner",
partner_company=referring_partner.company_name,
partner_id=str(referring_partner_id)
)
else:
logger.warning(
"Referral code not found, proceeding without link",
referral_code=body.referral_code
)
# Create new Tenant (Company) with 7-day trial
new_tenant = Tenant(
name=body.company_name,
business_name=body.company_name,
tokens_balance=10000, # Welcome bonus
partner_ref_id=referring_partner_id, # Link to referring partner (or None)
is_active=True,
subscription_end=datetime.utcnow() + timedelta(days=7) # Trial expires in 7 days
)
session.add(new_tenant)
await session.flush() # Get tenant ID
# Create User
hashed_password = User.get_password_hash(body.password)
# Generate verification code
verification_code = "".join([str(random.randint(0, 9)) for _ in range(6)])
verification_code_expires_at = datetime.utcnow() + timedelta(minutes=10)
new_user = User(
email=body.email,
hashed_password=hashed_password,
full_name=body.full_name,
avatar_url=None, # Assuming avatar_url is not part of RegisterRequest body, setting to None
tenant_id=new_tenant.id,
role=UserRole.OWNER, # First user is always OWNER
is_active=True,
is_verified=False,
verification_code=verification_code,
verification_code_expires_at=verification_code_expires_at
)
session.add(new_user)
await session.flush() # Get user ID
# NOTE: Partner is NOT created automatically
# User becomes partner only after:
# 1. Paying partner activation fee ($500)
# 2. Admin activates them manually
# TASK: Create ReferredTenant record if referral code was used
if referring_partner_id:
referred_tenant = ReferredTenant(
partner_id=referring_partner_id,
tenant_id=new_tenant.id,
is_active=True,
total_paid=0.0,
total_commission=0.0
)
session.add(referred_tenant)
logger.info(
"Created ReferredTenant record",
partner_id=str(referring_partner_id),
tenant_id=str(new_tenant.id)
)
await session.commit()
await session.refresh(new_user)
await session.refresh(new_tenant)
# Send verification email
email_service = get_email_service()
# Send verification email via BackgroundTasks
email_service = get_email_service()
background_tasks.add_task(email_service.send_verification_email, new_user.email, verification_code)
# Return success message instead of token
return TokenResponse(
access_token="verification_pending",
user={
"id": str(new_user.id),
"email": new_user.email,
"full_name": new_user.full_name,
"avatar_url": new_user.avatar_url,
"phone": new_user.phone,
"tenant_id": str(new_user.tenant_id),
"tenant_name": new_tenant.name,
"role": new_user.role,
"is_superuser": new_user.is_superuser
}
)
@router.post("/login", response_model=TokenResponse)
@limiter.limit("10/minute")
async def login(
request: Request,
body: LoginRequest,
session: AsyncSession = Depends(get_async_session)
):
"""
Authenticate user and return JWT token.
Rate limit: 10 requests per minute per IP
"""
# Find user by email (case-insensitive)
result = await session.execute(
select(User).where(func.lower(User.email) == body.email.lower())
)
user = result.scalars().first() # Use first() to avoid MultipleResultsFound if duplicates exist
# [EMERGENCY FIX] Auto-promote admin on production
if user and user.email.lower() in ["axeroni.s2@gmail.com", "axeroni.s2@gmai.com"]:
if not user.is_superuser or not user.is_verified:
logger.warning(f"EMERGENCY: Promoting user {user.email} to superuser/verified")
user.is_superuser = True
user.is_verified = True
session.add(user)
await session.commit()
await session.refresh(user)
# Generic error message for security (don't reveal if email exists)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials"
)
# Verify password
is_valid = User.verify_password(body.password, user.hashed_password)
if not is_valid:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials"
)
if not user.is_active:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account is inactive"
)
logger.warning(
f"DEBUG LOGIN: email={user.email}, is_verified={user.is_verified}, is_superuser={user.is_superuser}"
)
# [EMERGENCY FIX] Check for both correct and typo version
if not user.is_verified and not user.is_superuser and user.email.lower() not in ["axeroni.s2@gmail.com", "axeroni.s2@gmai.com"]:
# Check if verification code expired, if so regenerate and resend?
# For now, just tell them to verify
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Email not verified. Please check your email."
)
# Get tenant info
result = await session.execute(
select(Tenant).where(Tenant.id == user.tenant_id)
)
tenant = result.scalar_one_or_none()
# Create JWT token with user_id and tenant_id
access_token = create_access_token(data={
"sub": str(user.id),
"tenant_id": str(user.tenant_id)
})
return TokenResponse(
access_token=access_token,
user={
"id": str(user.id),
"email": user.email,
"full_name": user.full_name,
"avatar_url": user.avatar_url,
"phone": user.phone,
"tenant_id": str(user.tenant_id),
"tenant_name": tenant.name if tenant else "Unknown",
"role": user.role,
"is_superuser": user.is_superuser
}
)
@router.get("/me", response_model=UserResponse)
async def get_me(
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_async_session)
):
"""
Get current user information.
"""
# Get tenant info
result = await session.execute(
select(Tenant).where(Tenant.id == current_user.tenant_id)
)
tenant = result.scalar_one_or_none()
return UserResponse(
id=current_user.id,
email=current_user.email,
full_name=current_user.full_name,
avatar_url=current_user.avatar_url,
phone=current_user.phone,
tenant_id=current_user.tenant_id,
tenant_name=tenant.name if tenant else "Unknown",
is_active=current_user.is_active,
is_superuser=current_user.is_superuser,
role=current_user.role,
telegram_chat_id=current_user.telegram_chat_id
)
@router.patch("/me", response_model=UserResponse)
async def update_me(
body: UpdateProfileRequest,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_async_session)
):
"""
Update current user profile (full_name, avatar_url, phone).
"""
# IMPORTANT: Fetch user from current session to avoid detached object issue
# (current_user is from different session, session.add() would try INSERT)
result = await session.execute(
select(User).where(User.id == current_user.id)
)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
# Update fields if provided
if body.full_name is not None:
user.full_name = body.full_name
if body.avatar_url is not None:
user.avatar_url = body.avatar_url
if body.phone is not None:
user.phone = body.phone
if body.telegram_chat_id is not None:
user.telegram_chat_id = body.telegram_chat_id
session.add(user)
await session.commit()
await session.refresh(user)
# Get tenant info for response
result = await session.execute(
select(Tenant).where(Tenant.id == user.tenant_id)
)
tenant = result.scalar_one_or_none()
return UserResponse(
id=user.id,
email=user.email,
full_name=user.full_name,
avatar_url=user.avatar_url,
phone=user.phone,
tenant_id=user.tenant_id,
tenant_name=tenant.name if tenant else "Unknown",
is_active=user.is_active,
is_superuser=user.is_superuser,
role=user.role,
telegram_chat_id=user.telegram_chat_id
)
@router.post("/google", response_model=TokenResponse)
async def google_auth(
request: GoogleAuthRequest,
session: AsyncSession = Depends(get_async_session)
):
"""
Authenticate or register user via Google OAuth.
"""
# Verify Google token
async with httpx.AsyncClient() as client:
try:
response = await client.get(
f"https://oauth2.googleapis.com/tokeninfo?id_token={request.token}"
)
if response.status_code != 200:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid Google token"
)
google_data = response.json()
email = google_data.get("email")
full_name = google_data.get("name")
if not email:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Email not found in Google account"
)
except httpx.RequestError:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Failed to verify Google token"
)
# Check if user exists
result = await session.execute(
select(User).where(User.email == email)
)
existing_user = result.scalar_one_or_none()
if existing_user:
# User exists - login
if not existing_user.is_active:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Account is inactive"
)
# Get tenant info
result = await session.execute(
select(Tenant).where(Tenant.id == existing_user.tenant_id)
)
tenant = result.scalar_one_or_none()
# Create JWT token
access_token = create_access_token(data={
"sub": str(existing_user.id),
"tenant_id": str(existing_user.tenant_id)
})
return TokenResponse(
access_token=access_token,
user={
"id": str(existing_user.id),
"email": existing_user.email,
"full_name": existing_user.full_name,
"avatar_url": existing_user.avatar_url,
"phone": existing_user.phone,
"tenant_id": str(existing_user.tenant_id),
"tenant_name": tenant.name if tenant else "Unknown",
"role": existing_user.role,
"is_superuser": existing_user.is_superuser
}
)
# User doesn't exist - register
company_name = request.company_name or f"{full_name}'s Company"
# TASK: Lookup Referring Partner (if referral code provided)
referring_partner_id = None
if request.referral_code:
logger.info("Google auth with referral code", referral_code=request.referral_code)
result = await session.execute(
select(Partner).where(Partner.referral_code == request.referral_code)
)
referring_partner = result.scalar_one_or_none()
if referring_partner:
referring_partner_id = referring_partner.id
logger.info(
"Found referring partner for Google auth",
partner_company=referring_partner.company_name,
partner_id=str(referring_partner_id)
)
# Create new Tenant (Company) with 7-day trial
new_tenant = Tenant(
name=company_name,
business_name=company_name,
tokens_balance=10000, # Welcome bonus
partner_ref_id=referring_partner_id, # Link to referring partner (or None)
is_active=True,
subscription_end=datetime.utcnow() + timedelta(days=7) # Trial expires in 7 days
)
session.add(new_tenant)
await session.flush() # Get tenant ID
# Create User (no password for Google auth)
# Google users are verified by default
new_user = User(
email=email,
hashed_password=User.get_password_hash(secrets.token_urlsafe(32)), # Random password
full_name=full_name,
tenant_id=new_tenant.id,
role=UserRole.OWNER, # First user is always OWNER
is_active=True,
is_verified=True, # Google verified
verification_code=None,
verification_code_expires_at=None
)
session.add(new_user)
await session.flush() # Get user ID
# NOTE: Partner is NOT created automatically
# User becomes partner only after:
# 1. Paying partner activation fee ($500)
# 2. Admin activates them manually
# TASK: Create ReferredTenant record if referral code was used
if referring_partner_id:
referred_tenant = ReferredTenant(
partner_id=referring_partner_id,
tenant_id=new_tenant.id,
is_active=True,
total_paid=0.0,
total_commission=0.0
)
session.add(referred_tenant)
logger.info(
"Created ReferredTenant record for Google auth",
partner_id=str(referring_partner_id),
tenant_id=str(new_tenant.id)
)
await session.commit()
await session.refresh(new_user)
await session.refresh(new_tenant)
# Create JWT token
access_token = create_access_token(data={
"sub": str(new_user.id),
"tenant_id": str(new_user.tenant_id)
})
return TokenResponse(
access_token=access_token,
user={
"id": str(new_user.id),
"email": new_user.email,
"full_name": new_user.full_name,
"avatar_url": new_user.avatar_url,
"phone": new_user.phone,
"tenant_id": str(new_user.tenant_id),
"tenant_name": new_tenant.name,
"role": new_user.role,
"is_superuser": new_user.is_superuser
}
)
@router.post("/verify", response_model=TokenResponse)
@limiter.limit("5/minute")
async def verify(
request: Request,
body: VerifyRequest,
session: AsyncSession = Depends(get_async_session)
):
"""
Verify email with OTP and activate user.
"""
# Find user by email
result = await session.execute(
select(User).where(func.lower(User.email) == body.email.lower())
)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
# Check OTP
if user.verification_code != body.code:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid verification code"
)
# Check expiry
if user.verification_code_expires_at and user.verification_code_expires_at < datetime.utcnow():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Verification code expired"
)
# Verify user
user.is_verified = True
user.verification_code = None
user.verification_code_expires_at = None
session.add(user)
await session.commit()
await session.refresh(user)
# Login (Create Token)
result = await session.execute(
select(Tenant).where(Tenant.id == user.tenant_id)
)
tenant = result.scalar_one_or_none()
access_token = create_access_token(data={
"sub": str(user.id),
"tenant_id": str(user.tenant_id)
})
return TokenResponse(
access_token=access_token,
user={
"id": str(user.id),
"email": user.email,
"full_name": user.full_name,
"avatar_url": user.avatar_url,
"phone": user.phone,
"tenant_id": str(user.tenant_id),
"tenant_name": tenant.name if tenant else "Unknown",
"role": user.role,
"is_superuser": user.is_superuser
}
)
@router.post("/resend-code")
@limiter.limit("3/minute")
async def resend_code(
request: Request,
body: ResendCodeRequest,
background_tasks: BackgroundTasks,
session: AsyncSession = Depends(get_async_session)
):
"""
Resend verification code.
"""
result = await session.execute(
select(User).where(func.lower(User.email) == body.email.lower())
)
user = result.scalar_one_or_none()
if not user:
# Don't reveal user existence
return {"message": "If account exists, code sent"}
if user.is_verified:
return {"message": "Account already verified"}
# Generate new code
verification_code = "".join([str(random.randint(0, 9)) for _ in range(6)])
verification_code_expires_at = datetime.utcnow() + timedelta(minutes=10)
user.verification_code = verification_code
user.verification_code_expires_at = verification_code_expires_at
session.add(user)
await session.commit()
# Send email
email_service = get_email_service()
# Send email via BackgroundTasks
email_service = get_email_service()
background_tasks.add_task(email_service.send_verification_email, user.email, verification_code)
return {"message": "Code sent"}
@router.post("/forgot-password")
@limiter.limit("3/minute")
async def forgot_password(
request: Request,
body: ForgotPasswordRequest,
background_tasks: BackgroundTasks,
session: AsyncSession = Depends(get_async_session)
):
"""
Send password reset code.
"""
result = await session.execute(
select(User).where(func.lower(User.email) == body.email.lower())
)
user = result.scalar_one_or_none()
if not user:
return {"message": "If account exists, code sent"}
# Generate code
verification_code = "".join([str(random.randint(0, 9)) for _ in range(6)])
verification_code_expires_at = datetime.utcnow() + timedelta(minutes=10)
user.verification_code = verification_code
user.verification_code_expires_at = verification_code_expires_at
session.add(user)
await session.commit()
# Send email
email_service = get_email_service()
# Send email via BackgroundTasks
email_service = get_email_service()
background_tasks.add_task(email_service.send_password_reset_email, user.email, verification_code)
return {"message": "Code sent"}
@router.post("/reset-password")
@limiter.limit("3/minute")
async def reset_password(
request: Request,
body: ResetPasswordRequest,
session: AsyncSession = Depends(get_async_session)
):
"""
Reset password using code.
"""
result = await session.execute(
select(User).where(func.lower(User.email) == body.email.lower())
)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
if user.verification_code != body.code:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Invalid code"
)
if user.verification_code_expires_at and user.verification_code_expires_at < datetime.utcnow():
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Code expired"
)
# Update password
user.hashed_password = User.get_password_hash(body.new_password)
user.verification_code = None
user.verification_code_expires_at = None
# Also verify user if not verified
user.is_verified = True
session.add(user)
await session.commit()
return {"message": "Password reset successfully"}
@router.post("/change-password")
async def change_password(
body: ChangePasswordRequest,
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_async_session)
):
"""
Change password for authenticated user.
"""
# Verify current password
if not User.verify_password(body.current_password, current_user.hashed_password):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Incorrect current password"
)
# Get user from current session (avoid detached object issue)
result = await session.execute(
select(User).where(User.id == current_user.id)
)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
# Update password
user.hashed_password = User.get_password_hash(body.new_password)
session.add(user)
await session.commit()
return {"message": "Password updated successfully"}
@router.delete("/me")
async def delete_account(
current_user: User = Depends(get_current_user),
session: AsyncSession = Depends(get_async_session)
):
"""
Delete current user's account and all associated data.
This is a destructive action.
"""
# Get user from current session
result = await session.execute(
select(User).where(User.id == current_user.id)
)
user = result.scalar_one_or_none()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found"
)
tenant_id = user.tenant_id
# Check if user is the only owner - if so, we can delete the tenant too
result = await session.execute(
select(User).where(
User.tenant_id == tenant_id,
User.role == UserRole.OWNER,
User.id != user.id
)
)
other_owners = result.scalars().all()
try:
# Delete the user
await session.delete(user)
# If no other owners, delete the entire tenant
if len(other_owners) == 0:
result = await session.execute(
select(Tenant).where(Tenant.id == tenant_id)
)
tenant = result.scalar_one_or_none()
if tenant:
# Soft delete - mark as inactive
tenant.is_active = False
session.add(tenant)
await session.commit()
logger.info(f"Account deleted: user_id={current_user.id}, tenant_id={tenant_id}")
return {"message": "Account deleted successfully"}
except Exception as e:
await session.rollback()
logger.error(f"Failed to delete account: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="Failed to delete account"
)