feat: initial commit — HermesMessages SaaS platform
Backend (FastAPI + Python 3.12): - Multi-tenant auth with JWT: login, register, refresh, Meta OAuth - Business & BusinessConfig management - WhatsApp webhook with HMAC signature verification - Bot engine powered by Claude AI - Calendar availability with Redis caching - Reservations CRUD with status management - Dashboard analytics (stats, agenda, peak hours) - Billing & plan management - Admin panel with platform-wide stats - Async bcrypt via asyncio.to_thread - IntegrityError handling for concurrent registration race conditions Frontend (React 18 + Vite + Tailwind CSS): - Multi-step guided registration form with helper text on every field - Login page with show/hide password toggle - Protected routes with AuthContext - Dashboard with stats cards, bar chart, and daily agenda - Reservations list with search, filters, and inline status actions - Calendar with weekly view, slot availability, and date blocking - Config page: business info, schedules, bot personality - Billing page with plan comparison and usage bar Design system: - Bricolage Grotesque + DM Sans typography - Emerald primary palette with semantic color tokens - scale(0.97) button press feedback, ease-out animations - Skeleton loaders, stagger animations, prefers-reduced-motion support - Accessible: aria-labels, visible focus rings, 4.5:1 contrast Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
0
backend/app/modules/auth/__init__.py
Normal file
0
backend/app/modules/auth/__init__.py
Normal file
17
backend/app/modules/auth/models.py
Normal file
17
backend/app/modules/auth/models.py
Normal file
@ -0,0 +1,17 @@
|
||||
from sqlalchemy import Column, Enum, ForeignKey, Integer, String
|
||||
from sqlalchemy.orm import relationship
|
||||
|
||||
from app.core.database import Base
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
business_id = Column(Integer, ForeignKey("businesses.id", ondelete="CASCADE"), nullable=False)
|
||||
email = Column(String, unique=True, nullable=False, index=True)
|
||||
hashed_password = Column(String, nullable=True)
|
||||
meta_user_id = Column(String, nullable=True, unique=True)
|
||||
role = Column(Enum("owner", "admin", name="user_role"), nullable=False, default="owner")
|
||||
|
||||
business = relationship("Business", back_populates="users")
|
||||
55
backend/app/modules/auth/router.py
Normal file
55
backend/app/modules/auth/router.py
Normal file
@ -0,0 +1,55 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||
from jose import JWTError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import create_access_token, decode_token
|
||||
from app.modules.auth import schemas, service
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/register", response_model=schemas.RegisterResponse, status_code=201)
|
||||
async def register(body: schemas.RegisterRequest, db: AsyncSession = Depends(get_db)):
|
||||
token, business_id, user_id = await service.register_business(
|
||||
db,
|
||||
business_name=body.business_name,
|
||||
business_type=body.business_type,
|
||||
timezone=body.timezone,
|
||||
email=body.email,
|
||||
password=body.password,
|
||||
)
|
||||
return schemas.RegisterResponse(
|
||||
access_token=token,
|
||||
business_id=business_id,
|
||||
user_id=user_id,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/login", response_model=schemas.TokenResponse)
|
||||
async def login(body: schemas.LoginRequest, db: AsyncSession = Depends(get_db)):
|
||||
token = await service.authenticate_user(db, body.email, body.password)
|
||||
return schemas.TokenResponse(access_token=token)
|
||||
|
||||
|
||||
@router.post("/meta-callback", response_model=schemas.TokenResponse)
|
||||
async def meta_callback(body: schemas.MetaCallbackRequest, db: AsyncSession = Depends(get_db)):
|
||||
token = await service.meta_oauth_login(db, body.code, body.redirect_uri)
|
||||
return schemas.TokenResponse(access_token=token)
|
||||
|
||||
|
||||
@router.post("/refresh", response_model=schemas.TokenResponse)
|
||||
async def refresh(body: schemas.RefreshRequest):
|
||||
try:
|
||||
payload = decode_token(body.access_token)
|
||||
except JWTError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token inválido")
|
||||
new_token = create_access_token(
|
||||
{"sub": payload["sub"], "business_id": payload["business_id"]}
|
||||
)
|
||||
return schemas.TokenResponse(access_token=new_token)
|
||||
|
||||
|
||||
@router.post("/logout", status_code=204)
|
||||
async def logout():
|
||||
return Response(status_code=204)
|
||||
56
backend/app/modules/auth/schemas.py
Normal file
56
backend/app/modules/auth/schemas.py
Normal file
@ -0,0 +1,56 @@
|
||||
from pydantic import BaseModel, EmailStr, field_validator
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
business_name: str
|
||||
business_type: str
|
||||
timezone: str = "UTC"
|
||||
email: EmailStr
|
||||
password: str
|
||||
|
||||
@field_validator("password")
|
||||
@classmethod
|
||||
def password_strength(cls, v: str) -> str:
|
||||
if len(v) < 8:
|
||||
raise ValueError("La contraseña debe tener al menos 8 caracteres")
|
||||
return v
|
||||
|
||||
@field_validator("business_name")
|
||||
@classmethod
|
||||
def business_name_not_empty(cls, v: str) -> str:
|
||||
if not v.strip():
|
||||
raise ValueError("El nombre del negocio no puede estar vacío")
|
||||
return v.strip()
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
|
||||
|
||||
class RegisterResponse(TokenResponse):
|
||||
business_id: int
|
||||
user_id: int
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
|
||||
|
||||
class RefreshRequest(BaseModel):
|
||||
access_token: str
|
||||
|
||||
|
||||
class MetaCallbackRequest(BaseModel):
|
||||
code: str
|
||||
redirect_uri: str
|
||||
|
||||
|
||||
class UserRead(BaseModel):
|
||||
id: int
|
||||
business_id: int
|
||||
email: str
|
||||
role: str
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
153
backend/app/modules/auth/service.py
Normal file
153
backend/app/modules/auth/service.py
Normal file
@ -0,0 +1,153 @@
|
||||
import asyncio
|
||||
import httpx
|
||||
from datetime import time as dtime
|
||||
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.security import create_access_token, hash_password, verify_password
|
||||
from app.modules.auth.models import User
|
||||
from app.modules.business.models import Business, BusinessConfig
|
||||
|
||||
|
||||
def _token_for_user(user: User) -> str:
|
||||
return create_access_token({"sub": str(user.id), "business_id": user.business_id})
|
||||
|
||||
|
||||
async def register_business(
|
||||
db: AsyncSession,
|
||||
business_name: str,
|
||||
business_type: str,
|
||||
timezone: str,
|
||||
email: str,
|
||||
password: str,
|
||||
) -> tuple[str, int, int]:
|
||||
existing = await get_user_by_email(db, email)
|
||||
if existing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="El correo ya está registrado",
|
||||
)
|
||||
|
||||
business = Business(
|
||||
name=business_name,
|
||||
type=business_type,
|
||||
timezone=timezone,
|
||||
status="trial",
|
||||
plan="free",
|
||||
)
|
||||
db.add(business)
|
||||
await db.flush()
|
||||
|
||||
db.add(
|
||||
BusinessConfig(
|
||||
business_id=business.id,
|
||||
open_days=[0, 1, 2, 3, 4],
|
||||
open_time=dtime(9, 0),
|
||||
close_time=dtime(18, 0),
|
||||
slot_duration=60,
|
||||
max_per_slot=1,
|
||||
blocked_dates=[],
|
||||
assistant_name="Hermes",
|
||||
tone="formal",
|
||||
)
|
||||
)
|
||||
|
||||
hashed = await asyncio.to_thread(hash_password, password)
|
||||
user = User(
|
||||
business_id=business.id,
|
||||
email=email,
|
||||
hashed_password=hashed,
|
||||
role="owner",
|
||||
)
|
||||
db.add(user)
|
||||
await db.flush()
|
||||
|
||||
try:
|
||||
await db.commit()
|
||||
except IntegrityError:
|
||||
await db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="El correo ya está registrado",
|
||||
)
|
||||
|
||||
return _token_for_user(user), business.id, user.id
|
||||
|
||||
|
||||
async def get_user_by_id(db: AsyncSession, user_id: int) -> User | None:
|
||||
result = await db.execute(select(User).where(User.id == user_id))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def get_user_by_email(db: AsyncSession, email: str) -> User | None:
|
||||
result = await db.execute(select(User).where(User.email == email))
|
||||
return result.scalar_one_or_none()
|
||||
|
||||
|
||||
async def authenticate_user(db: AsyncSession, email: str, password: str) -> str:
|
||||
user = await get_user_by_email(db, email)
|
||||
if not user or not user.hashed_password:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Credenciales incorrectas",
|
||||
)
|
||||
if not await asyncio.to_thread(verify_password, password, user.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Credenciales incorrectas",
|
||||
)
|
||||
return _token_for_user(user)
|
||||
|
||||
|
||||
async def exchange_meta_code(code: str, redirect_uri: str) -> dict:
|
||||
"""Intercambia el código de autorización de Meta por un access token."""
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(
|
||||
"https://graph.facebook.com/v20.0/oauth/access_token",
|
||||
params={
|
||||
"client_id": settings.META_APP_ID,
|
||||
"client_secret": settings.META_APP_SECRET,
|
||||
"code": code,
|
||||
"redirect_uri": redirect_uri,
|
||||
},
|
||||
)
|
||||
if response.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Error al intercambiar código con Meta",
|
||||
)
|
||||
return response.json()
|
||||
|
||||
|
||||
async def get_meta_user_info(access_token: str) -> dict:
|
||||
async with httpx.AsyncClient() as client:
|
||||
response = await client.get(
|
||||
"https://graph.facebook.com/me",
|
||||
params={"fields": "id,email", "access_token": access_token},
|
||||
)
|
||||
if response.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Error al obtener información del usuario de Meta",
|
||||
)
|
||||
return response.json()
|
||||
|
||||
|
||||
async def meta_oauth_login(db: AsyncSession, code: str, redirect_uri: str) -> str:
|
||||
token_data = await exchange_meta_code(code, redirect_uri)
|
||||
meta_info = await get_meta_user_info(token_data["access_token"])
|
||||
|
||||
result = await db.execute(select(User).where(User.meta_user_id == meta_info["id"]))
|
||||
user = result.scalar_one_or_none()
|
||||
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Usuario no encontrado. Completa el registro primero.",
|
||||
)
|
||||
|
||||
return _token_for_user(user)
|
||||
Reference in New Issue
Block a user