Initial commit

This commit is contained in:
Atharv1705
2026-07-15 12:30:28 +05:30
commit 611d00bda1
100 changed files with 8740 additions and 0 deletions
View File
View File
+675
View File
@@ -0,0 +1,675 @@
import os
import logging
from datetime import datetime, timedelta
from jose import jwt, JWTError
from fastapi import APIRouter, Depends, HTTPException, status, Request, Query, BackgroundTasks
from fastapi.security import OAuth2PasswordBearer
from sqlalchemy.orm import Session
from app.db import get_db
import app.crud as crud
from app.schemas import SignupRequest, LoginRequest, TokenResponse, ForgotPasswordRequest, ResetPasswordRequest, ResendVerificationRequest, RoleChangeRequest
from app.models import UserRole, User as UserModel, PersonalDocument, BusinessDocument
logger = logging.getLogger(__name__)
# =========================
# Router
# =========================
router = APIRouter(prefix="/api/auth", tags=["auth"])
# =========================
# Config
# =========================
SECRET_KEY = os.getenv("SECRET_KEY")
if not SECRET_KEY:
raise RuntimeError(
"SECRET_KEY environment variable is not set. "
"Generate one with: openssl rand -hex 32"
)
ALGORITHM = os.getenv("ALGORITHM", "HS256")
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.getenv("ACCESS_TOKEN_EXPIRE_MINUTES", "1440"))
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login")
# =========================
# JWT helpers
# =========================
def create_access_token(
subject: str,
role: str = "user",
expires_minutes: int | None = None,
) -> str:
expire = datetime.utcnow() + timedelta(
minutes=expires_minutes or ACCESS_TOKEN_EXPIRE_MINUTES
)
payload = {
"sub": subject,
"role": role.lower(),
"exp": expire,
}
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
RESET_TOKEN_EXPIRE_MINUTES = 15
def create_password_reset_token(email: str) -> str:
expire = datetime.utcnow() + timedelta(minutes=RESET_TOKEN_EXPIRE_MINUTES)
payload = {
"sub": email,
"type": "password_reset",
"exp": expire,
}
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
VERIFY_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours
def create_email_verification_token(email: str) -> str:
expire = datetime.utcnow() + timedelta(minutes=VERIFY_TOKEN_EXPIRE_MINUTES)
payload = {
"sub": email,
"type": "email_verification",
"exp": expire,
}
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
from app.utils.emailer import send_email
from app.limiter import limiter
@router.post("/forgot-password")
@limiter.limit("3/hour")
async def forgot_password(
request: Request,
payload: ForgotPasswordRequest,
background: BackgroundTasks,
db: Session = Depends(get_db),
):
user = crud.get_user_by_email(db, payload.email)
# Anti-enumeration
if not user:
return {"message": "If the email exists, a reset link has been sent"}
reset_token = create_password_reset_token(user.email)
frontend_url = os.getenv("FRONTEND_URL", "https://bookkeepro.net")
reset_link = f"{frontend_url}/reset-password?token={reset_token}"
# Add email task with error handling
async def send_reset_email_safely():
try:
await send_email(
to=user.email,
subject="Reset your BookKeepro password",
body=f"""
Hi {user.name},<br><br>
Click the button below to reset your password:<br><br>
<a href="{reset_link}"
style="padding:12px 18px;
background:#FF7F11;
color:#fff;
text-decoration:none;
border-radius:6px;">
Reset Password
</a>
<br><br>
This link expires in 15 minutes.<br><br>
BookKeepro Team
"""
)
except Exception as e:
import logging
logger = logging.getLogger(__name__)
logger.error(f"Failed to send reset email to {user.email}: {e}")
background.add_task(send_reset_email_safely)
return {"message": "If the email exists, a reset link has been sent"}
@router.post("/reset-password")
def reset_password(
payload: ResetPasswordRequest,
db: Session = Depends(get_db),
):
try:
decoded = jwt.decode(payload.token, SECRET_KEY, algorithms=[ALGORITHM])
email = decoded.get("sub")
token_type = decoded.get("type")
if token_type != "password_reset":
logger.warning(f"Invalid password reset token type for email: {email}")
raise HTTPException(status_code=400, detail="Invalid token")
except JWTError:
logger.warning(f"Invalid or expired password reset token")
raise HTTPException(status_code=400, detail="Invalid or expired token")
user = crud.get_user_by_email(db, email)
if not user:
logger.warning(f"Password reset attempt for non-existent user: {email}")
raise HTTPException(status_code=404, detail="User not found")
hashed_password = crud.hash_password(payload.new_password)
crud.update_user_password(db, user, hashed_password)
logger.info(f"Password reset successful for user: {email}")
return {"message": "Password reset successful"}
def get_current_user(
token: str = Depends(oauth2_scheme),
db: Session = Depends(get_db),
):
"""Get current user from JWT token and verify role from database (not JWT).
CRITICAL: Role is always read from database, not from JWT token.
This prevents JWT role spoofing attacks.
"""
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email: str | None = payload.get("sub")
if not email:
raise credentials_exception
except JWTError:
raise credentials_exception
user = crud.get_user_by_email(db, email)
if not user:
raise credentials_exception
# CRITICAL: Always use role from database, never trust JWT role
# This prevents attackers from forging JWT with elevated privileges
return user
def require_admin(current_user=Depends(get_current_user)):
if current_user.role not in [UserRole.admin, UserRole.super_admin]:
logger.warning(f"Unauthorized admin access attempt by user {current_user.id} ({current_user.email})")
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Admin access required"
)
logger.info(f"Admin action by user {current_user.id} ({current_user.email})")
return current_user
def require_super_admin(current_user=Depends(get_current_user)):
"""Dependency to enforce super_admin-only access (role management, etc.)."""
if current_user.role != UserRole.super_admin:
logger.warning(f"Unauthorized super_admin access attempt by user {current_user.id} ({current_user.email})")
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Super admin access required"
)
return current_user
# =========================
# Auth Routes
# =========================
@router.post("/signup", response_model=TokenResponse)
@limiter.limit("10/hour")
async def signup(request: Request, payload: SignupRequest, background: BackgroundTasks, db: Session = Depends(get_db)):
if crud.get_user_by_email(db, payload.email):
logger.warning(f"Signup attempt with already registered email: {payload.email}")
raise HTTPException(status_code=400, detail="Email already registered")
role_value = "user" # all public signups are always regular users
# Admins created via DB are pre-verified; new signups are always "user" and unverified
is_admin = False
user = crud.create_user(
db=db,
name=payload.name,
email=payload.email,
phone=payload.phone or "",
password=payload.password,
role=role_value,
is_verified=1 if is_admin else 0,
)
logger.info(f"New user registered: {user.email} with role {user.role}")
crud.log_action(db, "signup", user_id=user.id, ip_address=request.client.host if hasattr(request, 'client') and request.client else None)
# Send verification email in background (non-blocking)
if not is_admin:
verify_token = create_email_verification_token(user.email)
frontend_url = os.getenv("FRONTEND_URL", "https://bookkeepro.net")
verify_link = f"{frontend_url}/verify-email?token={verify_token}"
async def send_verify_email():
try:
await send_email(
to=user.email,
subject="Verify your BookKeepro email",
body=f"""
Hi {user.name},<br><br>
Welcome to BookKeepro! Please verify your email address to activate your account.<br><br>
<a href="{verify_link}"
style="padding:12px 24px;background:#FF7F11;color:#fff;
text-decoration:none;border-radius:6px;font-weight:600;">
Verify My Email
</a>
<br><br>
This link expires in 24 hours. If you did not sign up, ignore this email.<br><br>
BookKeepro Team
"""
)
except Exception as e:
logger.error(f"Verification email failed for {user.email}: {e}")
background.add_task(send_verify_email)
return {
"access_token": "", # no token until verified
"token_type": "bearer",
"role": role_value,
"user_id": user.id,
"email_verification_required": not is_admin,
}
@router.post("/login", response_model=TokenResponse)
@limiter.limit("5/minute")
def login(request: Request, payload: LoginRequest, db: Session = Depends(get_db)):
user = crud.get_user_by_email(db, payload.email)
if not user or not crud.verify_password(payload.password, user.hashed_password):
logger.warning(f"Failed login attempt for email: {payload.email}")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
)
# Block unverified users
if not user.is_verified:
logger.warning(f"Login attempt by unverified user: {user.email}")
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="EMAIL_NOT_VERIFIED",
)
user_role = (
user.role.value if hasattr(user.role, "value") else str(user.role)
).lower()
logger.info(f"User logged in: {user.email} with role {user_role}")
crud.log_action(db, "login", user_id=user.id, ip_address=request.client.host if request.client else None)
token = create_access_token(subject=user.email, role=user_role)
return {
"access_token": token,
"token_type": "bearer",
"role": user_role,
"user_id": user.id,
}
@router.get("/verify-email")
def verify_email(token: str, db: Session = Depends(get_db)):
"""Verify a user's email using the token sent during signup."""
try:
decoded = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
email = decoded.get("sub")
token_type = decoded.get("type")
if token_type != "email_verification":
raise HTTPException(status_code=400, detail="Invalid token")
except JWTError:
raise HTTPException(status_code=400, detail="Invalid or expired verification link")
user = crud.get_user_by_email(db, email)
if not user:
raise HTTPException(status_code=404, detail="User not found")
if user.is_verified:
return {"message": "already_verified"}
user.is_verified = 1
db.commit()
logger.info(f"Email verified for user: {email}")
return {"message": "verified"}
@router.post("/resend-verification")
async def resend_verification(
payload: ResendVerificationRequest,
background: BackgroundTasks,
db: Session = Depends(get_db),
):
"""Resend the email verification link."""
user = crud.get_user_by_email(db, payload.email)
if not user or user.is_verified:
return {"message": "If the email exists and is unverified, a new link has been sent"}
verify_token = create_email_verification_token(user.email)
frontend_url = os.getenv("FRONTEND_URL", "https://bookkeepro.net")
verify_link = f"{frontend_url}/verify-email?token={verify_token}"
async def send_resend_email():
try:
await send_email(
to=user.email,
subject="Verify your BookKeepro email",
body=f"""
Hi {user.name},<br><br>
Here is your new verification link:<br><br>
<a href="{verify_link}"
style="padding:12px 24px;background:#FF7F11;color:#fff;
text-decoration:none;border-radius:6px;font-weight:600;">
Verify My Email
</a>
<br><br>
This link expires in 24 hours.<br><br>
BookKeepro Team
"""
)
except Exception as e:
logger.error(f"Resend verification email failed for {user.email}: {e}")
background.add_task(send_resend_email)
return {"message": "If the email exists and is unverified, a new link has been sent"}
@router.get("/me")
def me(current_user=Depends(get_current_user)):
role = (
current_user.role.value
if hasattr(current_user.role, "value")
else str(current_user.role)
)
return {
"id": current_user.id,
"name": current_user.name,
"email": current_user.email,
"phone": current_user.phone,
"role": role,
"engagement_acknowledged_at": (
current_user.engagement_acknowledged_at.isoformat()
if current_user.engagement_acknowledged_at else None
),
}
# ─────────────────────────────────────────────
# Engagement letter acknowledgement
# ─────────────────────────────────────────────
@router.post("/acknowledge-engagement")
def acknowledge_engagement(
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
"""User confirms they have read the engagement letter. Idempotent."""
if not current_user.engagement_acknowledged_at:
current_user.engagement_acknowledged_at = datetime.utcnow()
db.commit()
crud.log_action(db, "engagement_acknowledged", user_id=current_user.id)
return {
"acknowledged": True,
"acknowledged_at": current_user.engagement_acknowledged_at.isoformat(),
}
@router.patch("/me")
def update_me(
payload: dict,
request: Request,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
"""Update own profile (name, phone, password). Any authenticated user."""
name = payload.get("name", "").strip()
phone = payload.get("phone", "").strip()
current_pw = payload.get("current_password", "")
new_pw = payload.get("new_password", "")
changed = []
if name and name != current_user.name:
current_user.name = name
changed.append("name")
if phone != current_user.phone:
current_user.phone = phone
changed.append("phone")
if new_pw:
if len(new_pw) < 8:
raise HTTPException(status_code=400, detail="New password must be at least 8 characters")
if not current_pw:
raise HTTPException(status_code=400, detail="Current password is required to set a new password")
if not crud.verify_password(current_pw, current_user.hashed_password):
raise HTTPException(status_code=400, detail="Current password is incorrect")
current_user.hashed_password = crud.hash_password(new_pw)
changed.append("password")
if changed:
db.commit()
crud.log_action(
db, "profile_update",
user_id=current_user.id,
detail=", ".join(changed),
ip_address=request.client.host if request.client else None,
)
return {
"id": current_user.id,
"name": current_user.name,
"email": current_user.email,
"phone": current_user.phone,
"updated": changed,
}
# =========================
# Admin Routes
# =========================
@router.get("/admin/users")
def list_users_for_admin(
skip: int = Query(0, ge=0),
limit: int = Query(100, ge=1, le=500),
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""
List users:
- super_admin → sees all users (user + admin + super_admin)
- admin → sees only role=user accounts
Supports skip/limit pagination. Returns pending_docs count per user.
"""
from sqlalchemy import func as sqlfunc
def _pending_count(uid: int) -> int:
p = db.query(sqlfunc.count(PersonalDocument.id)).filter(
PersonalDocument.user_id == uid,
PersonalDocument.review_status == "pending",
PersonalDocument.deleted_at == None,
).scalar() or 0
b = db.query(sqlfunc.count(BusinessDocument.id)).filter(
BusinessDocument.user_id == uid,
BusinessDocument.review_status == "pending",
BusinessDocument.deleted_at == None,
).scalar() or 0
return p + b
if current_user.role == UserRole.super_admin:
q = db.query(UserModel)
else:
q = db.query(UserModel).filter(UserModel.role == UserRole.user)
total = q.count()
users = q.offset(skip).limit(limit).all()
return {
"users": [
{
"id": u.id,
"name": u.name,
"email": u.email,
"phone": u.phone,
"role": u.role.value if hasattr(u.role, "value") else str(u.role),
"pending_docs": _pending_count(u.id),
}
for u in users
],
"total": total,
"skip": skip,
"limit": limit,
}
@router.get("/admin/audit-logs")
def get_audit_logs(
user_id: int | None = None,
limit: int = 50,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
from app.models import AuditLog
query = db.query(AuditLog).order_by(AuditLog.created_at.desc())
if user_id:
query = query.filter(AuditLog.user_id == user_id)
logs = query.limit(min(limit, 200)).all()
return [
{
"id": l.id,
"user_id": l.user_id,
"action": l.action,
"target": l.target,
"detail": l.detail,
"ip_address": l.ip_address,
"created_at": l.created_at.isoformat() if l.created_at else None,
}
for l in logs
]
@router.get("/admin/users/{user_id}/documents")
def get_user_documents(
user_id: int,
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""
Removed: this endpoint queried the legacy uploaded_files table which is empty.
All document data is now at GET /api/upload/admin/users/{user_id}/documents.
Returns 410 Gone so callers know to update their URLs.
"""
raise HTTPException(
status_code=410,
detail=f"This endpoint is removed. Use /api/upload/admin/users/{user_id}/documents instead.",
)
# ─────────────────────────────────────────────
# Role management — super_admin only
# ─────────────────────────────────────────────
@router.patch("/admin/users/{user_id}/role")
def change_user_role(
user_id: int,
payload: RoleChangeRequest,
request: Request,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_super_admin),
):
"""
Change a user's role. Super admin only.
Rules:
- Cannot change your own role (prevents self-demotion)
- Cannot assign super_admin via API (super_admin is DB-only)
- Cannot demote the last remaining super_admin
"""
# Rule 1 — no self-modification
if user_id == current_user.id:
raise HTTPException(
status_code=400,
detail="You cannot change your own role"
)
target = crud.get_user_by_id(db, user_id)
if not target:
raise HTTPException(status_code=404, detail="User not found")
old_role = target.role.value if hasattr(target.role, "value") else str(target.role)
new_role = payload.role # already validated as "user" or "admin" by schema
# Rule 2 — no change if already same role
if old_role == new_role:
return {
"id": target.id,
"email": target.email,
"role": old_role,
"message": "Role unchanged (already set to this value)"
}
# Rule 3 — cannot demote the last remaining super_admin
if old_role == "super_admin":
from app.models import User as UserModel
super_admin_count = (
db.query(UserModel)
.filter(UserModel.role == UserRole.super_admin)
.count()
)
if super_admin_count <= 1:
raise HTTPException(
status_code=400,
detail="Cannot demote the last super admin. Promote another user first."
)
# Apply the role change
target.role = UserRole(new_role)
db.commit()
# Audit log with full context
crud.log_action(
db,
action="role_change",
user_id=current_user.id,
target=f"user:{user_id}",
detail=f"{target.email}: {old_role} → {new_role}",
ip_address=request.client.host if request.client else None,
)
logger.info(
f"Super admin {current_user.email} changed user {target.email} role: {old_role} → {new_role}"
)
return {
"id": target.id,
"email": target.email,
"old_role": old_role,
"new_role": new_role,
"message": f"Role updated from {old_role} to {new_role}"
}
+92
View File
@@ -0,0 +1,92 @@
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from app.models import User, AuditLog
# Single shared password hashing context
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
# ─────────────────────────────────────────────
# User queries
# ─────────────────────────────────────────────
def get_user_by_email(db: Session, email: str) -> User | None:
return db.query(User).filter(User.email == email).first()
def get_user_by_id(db: Session, user_id: int) -> User | None:
return db.query(User).filter(User.id == user_id).first()
def create_user(
db: Session,
name: str,
email: str,
phone: str,
password: str,
role: str = "user",
is_verified: int = 0,
) -> User:
user = User(
name=name,
email=email,
phone=phone,
hashed_password=pwd_context.hash(password),
role=role,
is_verified=is_verified,
)
db.add(user)
db.commit()
db.refresh(user)
return user
def update_user_password(db: Session, user: User, hashed_password: str) -> None:
user.hashed_password = hashed_password
db.add(user)
db.commit()
db.refresh(user)
# ─────────────────────────────────────────────
# Password helpers
# ─────────────────────────────────────────────
def verify_password(plain_password: str, hashed_password: str) -> bool:
return pwd_context.verify(plain_password, hashed_password)
def hash_password(plain_password: str) -> str:
return pwd_context.hash(plain_password)
def authenticate_user(db: Session, email: str, password: str) -> User | None:
user = get_user_by_email(db, email)
if not user:
return None
if not verify_password(password, user.hashed_password):
return None
return user
# ─────────────────────────────────────────────
# Audit logging
# ─────────────────────────────────────────────
def log_action(
db: Session,
action: str,
user_id: int | None = None,
target: str | None = None,
detail: str | None = None,
ip_address: str | None = None,
) -> None:
entry = AuditLog(
user_id=user_id,
action=action,
target=target,
detail=detail,
ip_address=ip_address,
)
db.add(entry)
db.commit()
+39
View File
@@ -0,0 +1,39 @@
import os
from urllib.parse import quote_plus
from dotenv import load_dotenv
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, declarative_base
from typing import Generator
# load .env located at myapp/.env (three levels up from this file)
env_path = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..", "..", ".env"))
load_dotenv(env_path)
DB_USER = os.getenv("MYSQL_USER", "root")
DB_PASS = os.getenv("MYSQL_PASSWORD", "")
DB_HOST = os.getenv("MYSQL_HOST", "localhost")
DB_PORT = os.getenv("MYSQL_PORT", "3306")
DB_NAME = os.getenv("MYSQL_DATABASE", "bookkeepprodb")
# URL-encode password to handle special characters like @
DB_PASS_ENCODED = quote_plus(DB_PASS)
DATABASE_URL = os.getenv("DATABASE_URL") or f"mysql+pymysql://{DB_USER}:{DB_PASS_ENCODED}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
# Engine and session — explicit pool config for production stability
engine = create_engine(
DATABASE_URL,
pool_pre_ping=True, # detect stale connections before use
pool_size=10, # persistent connections in pool
max_overflow=20, # extra connections allowed under peak load
pool_recycle=3600, # recycle connections after 1 hour (avoids MySQL wait_timeout drops)
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def get_db() -> Generator:
db = SessionLocal()
try:
yield db
finally:
db.close()
+8
View File
@@ -0,0 +1,8 @@
"""
Centralised rate-limiter instance.
Lives in its own module to avoid circular imports between main.py and security.py.
"""
from slowapi import Limiter
from slowapi.util import get_remote_address
limiter = Limiter(key_func=get_remote_address)
+191
View File
@@ -0,0 +1,191 @@
import os
import logging
from fastapi import FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
from app.limiter import limiter
from app import models
from app.db import engine
log = logging.getLogger("uvicorn.error")
app = FastAPI(title="BookKeepPro API")
# Rate limiter — import from limiter.py to avoid circular imports
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
# Create DB tables on startup (new tables only — does not alter existing)
models.Base.metadata.create_all(bind=engine)
# ─────────────────────────────────────────────
# Routers — each isolated so one failure never kills the others
# ─────────────────────────────────────────────
try:
from app.routers import auth # type: ignore
app.include_router(auth.router)
except Exception as exc:
log.exception("Failed to load auth router: %s", exc)
try:
from app.routers import upload # type: ignore
app.include_router(upload.router)
except Exception as exc:
log.exception("Failed to load upload router: %s", exc)
try:
from app.routers import contact # type: ignore
app.include_router(contact.router)
except Exception as exc:
log.exception("Failed to load contact router: %s", exc)
try:
from app.routers import review # type: ignore
app.include_router(review.router)
except Exception as exc:
log.exception("Failed to load review router: %s", exc)
# ─────────────────────────────────────────────
# CORS
# ─────────────────────────────────────────────
_ALLOWED_ORIGINS = [
o.strip()
for o in os.getenv(
"ALLOWED_ORIGINS",
"https://bookkeepro.net,http://localhost:8000",
).split(",")
if o.strip()
]
app.add_middleware(
CORSMiddleware,
allow_origins=_ALLOWED_ORIGINS,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ─────────────────────────────────────────────
# Static file mounts
# ─────────────────────────────────────────────
FRONTEND_DIR = os.path.abspath(
os.path.join(os.path.dirname(__file__), "..", "..", "..", "frontend")
)
def mount_if_exists(route: str, subdir: str, name: str):
path = os.path.join(FRONTEND_DIR, subdir)
if os.path.isdir(path):
app.mount(route, StaticFiles(directory=path), name=name)
log.info("Mounted static %s -> %s", route, path)
else:
log.debug("Static directory not found, skipping: %s", path)
mount_if_exists("/js", "js", "js")
mount_if_exists("/images", "images", "images")
mount_if_exists("/css", "css", "css")
UPLOAD_DIR = os.path.abspath(os.path.join(FRONTEND_DIR, "..", "uploads"))
if not os.path.exists(UPLOAD_DIR):
os.makedirs(UPLOAD_DIR, exist_ok=True)
log.info("FRONTEND_DIR resolved to: %s", FRONTEND_DIR)
log.info("CSS dir exists: %s", os.path.isdir(os.path.join(FRONTEND_DIR, "css")))
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory=FRONTEND_DIR)
def serve_frontend_file(request: Request, filename: str):
full = os.path.join(FRONTEND_DIR, filename)
if os.path.isfile(full):
return templates.TemplateResponse(
name=filename,
context={"request": request},
headers={
"Cache-Control": "no-store, no-cache, must-revalidate",
"Pragma": "no-cache",
"Expires": "0",
},
)
log.warning("Frontend file not found: %s", full)
raise HTTPException(status_code=404, detail="Page not found")
# ─────────────────────────────────────────────
# Ops endpoints
# ─────────────────────────────────────────────
@app.get("/health", tags=["ops"])
def health():
"""Health check for monitoring and load balancers."""
return {"status": "ok"}
@app.post("/logout", tags=["auth"])
def logout():
# JWT is stateless — token is invalidated client-side by clearing localStorage
return {"message": "Logged out"}
# ─────────────────────────────────────────────
# Frontend page routes
# ─────────────────────────────────────────────
@app.get("/", tags=["frontend"])
def home(request: Request): return serve_frontend_file(request, "home.html")
@app.get("/home", tags=["frontend"])#route to home page
def home_page(request: Request): return serve_frontend_file(request, "home.html")
@app.get("/login", tags=["frontend"]) #route to login page
def login_page(request: Request): return serve_frontend_file(request, "login.html")
@app.get("/signup", tags=["frontend"]) #route to signup page
def signup_page(request: Request): return serve_frontend_file(request, "signup.html")
@app.get("/dashboard", tags=["frontend"])
def dashboard_page(request: Request): return serve_frontend_file(request, "dashboard.html") #route to dashboard page
@app.get("/admin-dashboard", tags=["frontend"])
def admin_dashboard_page(request: Request): return serve_frontend_file(request, "admin-dashboard.html") #route to admin dashboard page
@app.get("/admin-user-detail", tags=["frontend"])
def admin_user_detail(request: Request): return serve_frontend_file(request, "admin-user-detail.html") #route to admin-user-detail page
@app.get("/upload-personal", tags=["frontend"])
def upload_personal(request: Request): return serve_frontend_file(request, "upload-personal.html") #route to upload-personal
@app.get("/upload-business", tags=["frontend"])
def upload_business(request: Request): return serve_frontend_file(request, "upload-business.html") #route to upload-business
@app.get("/contact", tags=["frontend"])
def contact_page(request: Request): return serve_frontend_file(request, "contact.html") #route to contact page
@app.get("/services", tags=["frontend"])
def services_page(request: Request): return serve_frontend_file(request, "services.html") #route to service page
@app.get("/about-us", tags=["frontend"])
def about_us_page(request: Request): return serve_frontend_file(request, "about-us.html") # route to about-us page
@app.get("/forgot-password", tags=["frontend"])
def forgot_password_page(request: Request): return serve_frontend_file(request, "forgot-password.html")
@app.get("/profile", tags=["frontend"])
def profile_page(request: Request): return serve_frontend_file(request, "profile.html") #route to forgot-password page
@app.get("/reset-password", tags=["frontend"])
def reset_password_page(request: Request): return serve_frontend_file(request, "reset-password.html") #route to reset-password page
@app.get("/verify-email", tags=["frontend"])
def verify_email_page(request: Request): return serve_frontend_file(request, "verify-email.html")# route to verify-email page
@app.get("/resend-verification", tags=["frontend"]) # route to resend-verification page
def resend_verification_page(request: Request): return serve_frontend_file(request, "resend-verification.html")
+180
View File
@@ -0,0 +1,180 @@
from sqlalchemy import (
Boolean,
Column,
DateTime,
Enum,
ForeignKey,
Index,
Integer,
String,
UniqueConstraint,
func,
)
from sqlalchemy.orm import relationship
from app.db import Base
import enum
# ─────────────────────────────────────────────
# Enums
# ─────────────────────────────────────────────
class UserRole(str, enum.Enum):
user = "user"
admin = "admin"
super_admin = "super_admin"
# ─────────────────────────────────────────────
# Users
# ─────────────────────────────────────────────
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
name = Column(String(150), nullable=True)
email = Column(String(200), unique=True, index=True, nullable=False)
phone = Column(String(50), default="")
hashed_password = Column(String(300), nullable=False)
role = Column(Enum(UserRole), default=UserRole.user, nullable=False)
is_verified = Column(Integer, default=0, nullable=False) # 0 = unverified, 1 = verified
created_at = Column(DateTime(timezone=True), server_default=func.now())
engagement_acknowledged_at = Column(DateTime(timezone=True), nullable=True, default=None)
# ─────────────────────────────────────────────
# Documents — user-uploaded
# ─────────────────────────────────────────────
class PersonalDocument(Base):
__tablename__ = "personal_documents"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
doc_type = Column(String(200), nullable=False)
filename = Column(String(512), nullable=False)
storage_key = Column(String(500), nullable=False)
content_type = Column(String(100))
uploaded_at = Column(DateTime(timezone=True), server_default=func.now())
deleted_at = Column(DateTime(timezone=True), nullable=True, default=None)
review_status = Column(String(20), default="pending", nullable=False)
review_note = Column(String(500), nullable=True)
tax_year = Column(Integer, default=2025, nullable=False)
user = relationship("User")
__table_args__ = (
Index("ix_personal_documents_user_id", "user_id"),
UniqueConstraint(
"user_id", "doc_type", "tax_year",
name="uq_personal_doc_user_type_year"
),
)
class BusinessDocument(Base):
__tablename__ = "business_documents"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
business_type = Column(String(200), nullable=False)
filename = Column(String(512), nullable=False)
storage_key = Column(String(500), nullable=False)
content_type = Column(String(100))
uploaded_at = Column(DateTime(timezone=True), server_default=func.now())
deleted_at = Column(DateTime(timezone=True), nullable=True, default=None)
review_status = Column(String(20), default="pending", nullable=False)
review_note = Column(String(500), nullable=True)
tax_year = Column(Integer, default=2025, nullable=False)
user = relationship("User")
__table_args__ = (
Index("ix_business_documents_user_id", "user_id"),
UniqueConstraint(
"user_id", "business_type", "tax_year",
name="uq_business_doc_user_type_year"
),
)
# ─────────────────────────────────────────────
# Documents — admin-uploaded (tax returns for client review)
# ─────────────────────────────────────────────
class AdminDocument(Base):
__tablename__ = "admin_documents"
id = Column(Integer, primary_key=True, index=True)
doc_key = Column(String(100), nullable=False, index=True) # machine-readable slug
doc_label = Column(String(150), nullable=False) # display name
filename = Column(String(512), nullable=False)
storage_key = Column(String(500), nullable=False) # S3 object key
content_type = Column(String(100))
uploaded_at = Column(DateTime(timezone=True), server_default=func.now())
uploaded_by = Column(Integer, ForeignKey("users.id"), nullable=False) # admin user
user_id = Column(Integer, ForeignKey("users.id"), nullable=False) # target client
deleted_at = Column(DateTime(timezone=True), nullable=True, default=None)
admin = relationship("User", foreign_keys=[uploaded_by])
user = relationship("User", foreign_keys=[user_id])
__table_args__ = (
Index("ix_admin_documents_user_id", "user_id"),
Index("ix_admin_documents_uploaded_by", "uploaded_by"),
)
# ─────────────────────────────────────────────
# Legacy table — kept to avoid breaking existing DB
# Nothing writes here anymore; safe to drop after verifying
# uploaded_files has zero rows in production.
# ─────────────────────────────────────────────
class UploadedFile(Base):
__tablename__ = "uploaded_files"
id = Column(Integer, primary_key=True, index=True)
filename = Column(String(512), nullable=False)
drive_file_id = Column(String(200), nullable=False) # legacy column name
content_type = Column(String(100))
doc_type = Column(String(150))
uploaded_at = Column(DateTime(timezone=True), server_default=func.now())
owner_id = Column(Integer, ForeignKey("users.id"), nullable=False)
owner = relationship("User")
# ─────────────────────────────────────────────
# Audit Log
# ─────────────────────────────────────────────
class AuditLog(Base):
__tablename__ = "audit_logs"
id = Column(Integer, primary_key=True, index=True)
user_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
action = Column(String(100), nullable=False) # e.g. "upload", "delete", "login", "approve"
target = Column(String(200), nullable=True) # e.g. "personal_doc:42", "user:7"
detail = Column(String(500), nullable=True) # extra context
ip_address = Column(String(45), nullable=True)
created_at = Column(DateTime(timezone=True), server_default=func.now())
__table_args__ = (
Index("ix_audit_logs_user_id", "user_id"),
Index("ix_audit_logs_created_at", "created_at"),
)
class RequiredDocumentTemplate(Base):
__tablename__ = "required_document_templates"
id = Column(Integer, primary_key=True, index=True)
category = Column(String(50), nullable=False) # 'personal' or 'business'
tax_year = Column(Integer, nullable=False)
name = Column(String(200), nullable=False)
file_url = Column(String(500), nullable=True) # Null if there is no template file to download
created_at = Column(DateTime(timezone=True), server_default=func.now())
__table_args__ = (
UniqueConstraint("category", "tax_year", "name", name="uq_template_cat_year_name"),
)
+12
View File
@@ -0,0 +1,12 @@
# This module re-exports everything from app.auth.security.
# All routes and auth dependencies live there.
from app.auth.security import (
router,
get_current_user,
require_admin,
require_super_admin,
create_access_token,
)
# Alias kept for any legacy internal references
get_current_user_real = get_current_user
+58
View File
@@ -0,0 +1,58 @@
import os
from fastapi import APIRouter, BackgroundTasks, HTTPException, Request
from app.limiter import limiter
from pydantic import BaseModel, EmailStr
from app.utils.emailer import send_email
router = APIRouter(prefix="/api", tags=["contact"])
# Get admin email from environment, with fallback
ADMIN_EMAIL = os.getenv("ADMIN_EMAIL", "admin@bookkeepro.net")
class ContactForm(BaseModel):
first_name: str
last_name: str
email: EmailStr
phone: str
message: str = ""
@router.post("/contact")
@limiter.limit("5/minute")
async def contact_message(request: Request, form: ContactForm, background: BackgroundTasks):
if not ADMIN_EMAIL or "@" not in ADMIN_EMAIL:
raise HTTPException(status_code=500, detail="Admin email not configured")
background.add_task(
send_email,
to=ADMIN_EMAIL,
subject="New Contact Enquiry Received — Follow-Up Required - BookKeepro",
body=f"""
Dear Team,
<br><br>
A new contact enquiry has been received. Please find the details below:
<br><br>
<b>Name:</b> {form.first_name} {form.last_name}<br>
<b>Email:</b> {form.email}<br>
<b>Phone:</b> {form.phone}<br>
<b>Message:</b> {form.message or '(none)'}<br><br>
Kindly follow up with the user at the earliest convenience.
<br><br>
Thank you,<br>
BookKeepro Support Team
"""
)
# auto-reply to user
background.add_task(
send_email,
to=form.email,
subject="Thanks for contacting BookKeepro",
body=f"""
Hi {form.first_name},<br><br>
Thank you for reaching out to BookKeepro.<br>
We’ve received your enquiry, and our team will get back to you shortly.<br><br>
Best Regards,<br>
BookKeepro Team
"""
)
return {"status": "sent"}
+144
View File
@@ -0,0 +1,144 @@
import logging
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from app.models import AdminDocument, User, UserRole
from app.db import get_db
from app.utils.emailer import send_email
from app import crud
from app.auth.security import get_current_user, require_admin
from app.schemas import SubmitReviewRequest, NotifyUserRequest, AdminDocResponseRequest
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/review", tags=["review"])
DASHBOARD_LINK = "https://bookkeepro.net/dashboard"
# ─────────────────────────────────────────────
# Admin submits user documents for review
# ─────────────────────────────────────────────
@router.post("/submit")
async def submit_review(
payload: SubmitReviewRequest,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Notify the user their documents have been submitted for review. Admin only."""
user = crud.get_user_by_id(db, payload.user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
email_sent = await send_email(
to=user.email,
subject="Documents Ready for Review — BookKeepro",
body=f"""
<p>Dear {user.name or "Sir/Ma'am"},</p>
<p>Your documents have been successfully submitted and are pending review.</p>
<p>
<a href="{DASHBOARD_LINK}"
style="color:#0077c8;font-weight:600;text-decoration:none;">
👉 Go to Dashboard
</a>
</p>
<p style="margin-top:20px;">Kind regards,<br><strong>BookKeepro Team</strong></p>
"""
)
logger.info(f"Admin {current_user.id} submitted review for user {payload.user_id}")
return {"status": "submitted", "email_sent": email_sent}
# ─────────────────────────────────────────────
# Admin sends approval / rejection notification
# ─────────────────────────────────────────────
@router.post("/notify-user")
async def notify_user_review(
payload: NotifyUserRequest,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Send document review result (approved/rejected + timeline) to the user. Admin only."""
user = crud.get_user_by_id(db, payload.user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
approved_html = "".join(f"<li>{item}</li>" for item in payload.approved) or "<li>None</li>"
rejected_html = "".join(f"<li>{item}</li>" for item in payload.rejected) or "<li>None</li>"
body = f"""
<p>Dear {user.name or "Sir/Ma'am"},</p>
<p>Your uploaded documents have been reviewed.</p>
<p><strong>Approved Documents</strong></p>
<ul>{approved_html}</ul>
<p><strong>Rejected Documents</strong></p>
<ul>{rejected_html}</ul>
<p><strong>Estimated Filing Timeline:</strong></p>
<ul>
<li>Personal Documents: {payload.personal_timeline} days</li>
<li>Business Documents: {payload.business_timeline} days</li>
</ul>
<p>Kind regards,<br><strong>BookKeepro Team</strong></p>
"""
await send_email(to=user.email, subject="Document Review Update — BookKeepro", body=body)
logger.info(f"Admin {current_user.id} sent review notification to user {payload.user_id}")
return {"status": "notified"}
# ─────────────────────────────────────────────
# User responds to an admin-uploaded return
# ─────────────────────────────────────────────
@router.post("/admin-doc-response")
async def admin_doc_response(
payload: AdminDocResponseRequest,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
"""User approves or rejects an admin-uploaded document. Users only."""
if current_user.role != UserRole.user:
raise HTTPException(status_code=403, detail="Users only")
doc = db.query(AdminDocument).filter_by(id=payload.doc_id).first()
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
# Verify this doc belongs to the current user
if doc.user_id != current_user.id:
logger.warning(
f"User {current_user.id} tried to respond to doc {payload.doc_id} "
f"belonging to user {doc.user_id}"
)
raise HTTPException(status_code=403, detail="Not authorized")
admin = db.query(User).filter_by(id=doc.uploaded_by).first()
if not admin:
raise HTTPException(status_code=404, detail="Admin not found")
body = f"""
<p>Dear Admin,</p>
<p>User <b>{current_user.email}</b> has <b>{payload.status.upper()}</b> the document:</p>
<p><b>{doc.doc_label}</b></p>
"""
if payload.status == "rejected" and payload.reason:
body += f"<p><strong>Reason:</strong></p><p>{payload.reason}</p>"
body += "<p style='margin-top:20px;'>BookKeepro System</p>"
await send_email(
to=admin.email,
subject=f"Admin Return Status {payload.status.capitalize()} — BookKeepro",
body=body,
)
logger.info(f"User {current_user.id} {payload.status} admin doc {payload.doc_id}")
return {"status": "notified"}
+910
View File
@@ -0,0 +1,910 @@
import os
import io
import uuid
import logging
from datetime import datetime
import filetype
from fastapi import APIRouter, BackgroundTasks, UploadFile, File, HTTPException, Depends, Form, Query
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
import boto3
from botocore.client import Config
from botocore.exceptions import ClientError
from jose import jwt, JWTError
from datetime import timedelta
from app.models import AdminDocument, PersonalDocument, BusinessDocument, User, UserRole
from app.db import get_db
import app.crud as crud
from app.auth.security import get_current_user, require_admin, SECRET_KEY, ALGORITHM
from app.utils.emailer import send_email
from app.schemas import UploadCompleteNotify, ReviewStatusUpdate
logger = logging.getLogger(__name__)
router = APIRouter(prefix="/api/upload", tags=["upload"])
from pathlib import Path
# ─────────────────────────────────────────────
# Local File Storage (Contabo VPS Disk)
# ─────────────────────────────────────────────
BASE_DIR = Path(__file__).resolve().parents[4]
UPLOAD_DIR = BASE_DIR / "uploads"
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
async def upload_to_storage(file: UploadFile) -> str:
"""Upload to local disk. Returns the filename (storage_key)."""
await file.seek(0)
contents = await file.read()
# File size validation
MAX_SIZE = 10 * 1024 * 1024 # 10 MB
if len(contents) > MAX_SIZE:
raise HTTPException(status_code=413, detail="File too large. Maximum size is 10MB.")
# Content type validation
ALLOWED_TYPES = {
"application/pdf",
"image/jpeg",
"image/png",
"image/webp",
"application/msword",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
}
kind = filetype.guess(contents)
sniffed_mime = kind.mime if kind else None
ext = os.path.splitext(file.filename or "file")[1].lower()
# Fallback for legacy .doc and inconsistent .docx sniffing
if sniffed_mime is None or sniffed_mime == "application/zip":
if ext in [".doc", ".docx"] and file.content_type in ALLOWED_TYPES:
sniffed_mime = file.content_type
if sniffed_mime not in ALLOWED_TYPES:
raise HTTPException(
status_code=400,
detail=f"File type not allowed or could not be verified. Allowed: PDF, JPG, PNG, WEBP, DOC, DOCX."
)
ext = os.path.splitext(file.filename or "file")[1].lower()
object_key = f"{uuid.uuid4().hex}{ext}"
file_path = UPLOAD_DIR / object_key
try:
with open(file_path, "wb") as f:
f.write(contents)
logger.info(f"Uploaded {object_key} locally")
return object_key
except Exception as e:
logger.error(f"Local upload failed: {e}")
raise HTTPException(status_code=500, detail="File upload failed")
def delete_from_storage(storage_key: str):
"""Delete from local disk."""
try:
if storage_key.startswith("uploads/"):
storage_key = storage_key.split("uploads/")[1]
file_path = UPLOAD_DIR / storage_key
if file_path.exists():
file_path.unlink()
logger.info(f"Deleted {storage_key} locally")
except Exception as e:
logger.warning(f"Storage delete failed for {storage_key}: {e}")
def get_presigned_url(storage_key: str) -> str:
"""Return an authenticated URL containing a short-lived JWT for viewing the file."""
if storage_key.startswith("uploads/"):
storage_key = storage_key.split("uploads/")[1]
expire = datetime.utcnow() + timedelta(minutes=5)
payload = {
"sub": storage_key,
"type": "file_access",
"exp": expire,
}
token = jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
return f"/api/upload/file/{storage_key}?token={token}"
@router.get("/file/{storage_key}")
def stream_file(storage_key: str, token: str = Query(...)):
"""Stream file securely using short-lived JWT token."""
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
token_key = payload.get("sub")
if token_key != storage_key or payload.get("type") != "file_access":
raise HTTPException(status_code=403, detail="Token mismatch or invalid type")
except JWTError:
raise HTTPException(status_code=401, detail="Invalid or expired token")
file_path = (UPLOAD_DIR / storage_key).resolve()
# Path traversal protection
if not str(file_path).startswith(str(UPLOAD_DIR.resolve()) + os.sep):
raise HTTPException(status_code=400, detail="Invalid file key")
if not file_path.exists():
raise HTTPException(status_code=404, detail="File not found")
return FileResponse(file_path)
# ─────────────────────────────────────────────
# Presigned URL — frontend "View" button
# ─────────────────────────────────────────────
@router.get("/view-url")
def get_view_url(
key: str,
current_user=Depends(get_current_user),
db: Session = Depends(get_db),
):
"""Return a presigned URL. Verifies the requesting user owns the document."""
if not key:
raise HTTPException(status_code=400, detail="key is required")
# Existence check — ensure the document actually exists in the DB first
doc = (
db.query(PersonalDocument).filter(PersonalDocument.storage_key == key).first() or
db.query(BusinessDocument).filter(BusinessDocument.storage_key == key).first() or
db.query(AdminDocument).filter(AdminDocument.storage_key == key).first()
)
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
# Ownership check — ensure this key belongs to the requesting user or user is admin
if current_user.role not in [UserRole.admin, UserRole.super_admin] and doc.user_id != current_user.id:
logger.warning(
f"User {current_user.id} attempted to access storage key {key} — not owned"
)
raise HTTPException(status_code=403, detail="Access denied")
url = get_presigned_url(key)
if not url:
raise HTTPException(status_code=500, detail="Could not generate view URL")
return {"url": url}
# ─────────────────────────────────────────────
# Admin Documents
# ─────────────────────────────────────────────
@router.post("/admin-documents")
async def upload_admin_document(
file: UploadFile = File(...),
doc_key: str = Form(...),
doc_label: str = Form(...),
user_id: int = Form(...),
background: BackgroundTasks = BackgroundTasks(),
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
target_user = crud.get_user_by_id(db, user_id)
if not target_user:
raise HTTPException(status_code=404, detail="Target user not found")
# Regular admins can only upload documents for user-role accounts
if current_user.role == UserRole.admin and target_user.role != UserRole.user:
raise HTTPException(
status_code=403,
detail="Admins can only upload documents for regular user accounts"
)
logger.info(f"Admin {current_user.id} uploading document for user {user_id}")
storage_key = await upload_to_storage(file)
record = AdminDocument(
doc_key=doc_key,
doc_label=doc_label,
filename=file.filename,
storage_key=storage_key,
content_type=file.content_type,
uploaded_by=current_user.id,
user_id=user_id,
)
db.add(record)
db.commit()
db.refresh(record)
crud.log_action(db, "upload_admin_doc", user_id=current_user.id, target=f"admin_doc:{record.id}", detail=f"for user {user_id}")
background.add_task(
send_email,
to=target_user.email,
subject="New Document Uploaded — BookKeepro",
body=f"""
<p>Dear {target_user.name or "Sir/Ma'am"},</p>
<p>An admin has securely uploaded a new document (<strong>{doc_label}</strong>) to your account.</p>
<p>You can view this document by logging into your BookKeepro portal.</p>
<br><strong>BookKeepro Team</strong>
""",
)
return {
"id": record.id,
"doc_label": record.doc_label,
"filename": record.filename,
"storage_key": record.storage_key,
}
@router.get("/admin-documents")
def list_admin_documents(
user_id: int | None = None,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
if current_user.role in [UserRole.admin, UserRole.super_admin]:
if not user_id:
raise HTTPException(status_code=400, detail="user_id is required for admin")
docs = (
db.query(AdminDocument)
.filter(AdminDocument.user_id == user_id, AdminDocument.deleted_at == None)
.order_by(AdminDocument.uploaded_at.desc())
.all()
)
elif current_user.role == UserRole.user:
docs = (
db.query(AdminDocument)
.filter(AdminDocument.user_id == current_user.id, AdminDocument.deleted_at == None)
.order_by(AdminDocument.uploaded_at.desc())
.all()
)
else:
raise HTTPException(status_code=403, detail="Unauthorized")
return [
{
"id": d.id,
"doc_key": d.doc_key,
"doc_label": d.doc_label,
"filename": d.filename,
"storage_key": d.storage_key,
}
for d in docs
]
@router.delete("/admin-documents/{doc_id}")
def delete_admin_document(
doc_id: int,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
doc = db.query(AdminDocument).filter_by(id=doc_id).first()
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
target_user = db.query(User).filter(User.id == doc.user_id).first()
if not target_user:
raise HTTPException(status_code=404, detail="Target user not found")
# Scope restriction: standard admins can only delete documents for base users
if current_user.role == UserRole.admin and target_user.role != UserRole.user:
raise HTTPException(
status_code=403,
detail="Standard admins can only manage documents for standard users"
)
logger.info(f"Admin {current_user.id} deleting admin document {doc_id}")
delete_from_storage(doc.storage_key)
doc.deleted_at = datetime.utcnow()
db.commit()
crud.log_action(db, "delete_admin_doc", user_id=current_user.id, target=f"admin_doc:{doc_id}")
return {"deleted": True}
# ─────────────────────────────────────────────
# Personal Documents
# ─────────────────────────────────────────────
@router.get("/personal-documents")
def list_personal_documents(
tax_year: int | None = None,
skip: int = Query(0, ge=0),
limit: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
q = db.query(PersonalDocument).filter(
PersonalDocument.user_id == current_user.id,
PersonalDocument.deleted_at == None,
)
if tax_year:
q = q.filter(PersonalDocument.tax_year == tax_year)
docs = q.order_by(PersonalDocument.uploaded_at.desc()).offset(skip).limit(limit).all()
return [
{
"id": d.id,
"doc_type": d.doc_type,
"filename": d.filename,
"storage_key": d.storage_key,
"uploaded_at": d.uploaded_at,
"tax_year": d.tax_year,
"review_status": d.review_status,
"review_note": d.review_note,
}
for d in docs
]
@router.post("/personal-documents")
async def upload_personal_document(
background: BackgroundTasks,
file: UploadFile = File(...),
doc_type: str = Form(...),
tax_year: int = Form(2025),
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
logger.info(f"User {current_user.id} uploading personal document: {file.filename}")
storage_key = await upload_to_storage(file)
record = PersonalDocument(
user_id=current_user.id,
doc_type=doc_type,
filename=file.filename,
storage_key=storage_key,
content_type=file.content_type,
tax_year=tax_year,
)
db.add(record)
try:
db.commit()
except IntegrityError:
db.rollback()
# Clean up the already-uploaded S3 object
delete_from_storage(storage_key)
raise HTTPException(
status_code=409,
detail="You have already uploaded this document for this tax year. "
"Delete the existing one to replace it."
)
db.refresh(record)
crud.log_action(db, "upload_personal", user_id=current_user.id, target=f"personal_doc:{record.id}", detail=file.filename)
admins = db.query(User).filter(User.role.in_([UserRole.admin, UserRole.super_admin])).all()
for admin in admins:
background.add_task(
send_email,
to=admin.email,
subject="New Personal Document Uploaded — BookKeepro",
body=f"<p><strong>{current_user.email}</strong> uploaded a personal document: <strong>{file.filename}</strong> ({doc_type}).</p>",
)
return {
"id": record.id,
"filename": record.filename,
"doc_type": record.doc_type,
"storage_key": record.storage_key,
"uploaded_at": record.uploaded_at,
"tax_year": record.tax_year,
}
@router.delete("/personal-documents/{doc_id}")
def delete_personal_document(
doc_id: int,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
doc = (
db.query(PersonalDocument)
.filter(
PersonalDocument.id == doc_id,
PersonalDocument.user_id == current_user.id,
)
.first()
)
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
logger.info(f"User {current_user.id} deleting personal document {doc_id}")
delete_from_storage(doc.storage_key)
doc.deleted_at = datetime.utcnow()
db.commit()
crud.log_action(db, "delete_personal", user_id=current_user.id, target=f"personal_doc:{doc_id}")
return {"deleted": True}
# ─────────────────────────────────────────────
# Business Documents
# ─────────────────────────────────────────────
@router.get("/business-documents")
def list_business_documents(
tax_year: int | None = None,
skip: int = Query(0, ge=0),
limit: int = Query(200, ge=1, le=500),
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
q = db.query(BusinessDocument).filter(
BusinessDocument.user_id == current_user.id,
BusinessDocument.deleted_at == None,
)
if tax_year:
q = q.filter(BusinessDocument.tax_year == tax_year)
docs = q.order_by(BusinessDocument.uploaded_at.desc()).offset(skip).limit(limit).all()
return [
{
"id": d.id,
"business_type": d.business_type,
"filename": d.filename,
"storage_key": d.storage_key,
"uploaded_at": d.uploaded_at,
"tax_year": d.tax_year,
"review_status": d.review_status,
"review_note": d.review_note,
}
for d in docs
]
@router.post("/business-documents")
async def upload_business_document(
background: BackgroundTasks,
file: UploadFile = File(...),
doc_type: str = Form(...),
tax_year: int = Form(2025),
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
logger.info(f"User {current_user.id} uploading business document: {file.filename}")
storage_key = await upload_to_storage(file)
record = BusinessDocument(
user_id=current_user.id,
business_type=doc_type,
filename=file.filename,
storage_key=storage_key,
content_type=file.content_type,
tax_year=tax_year,
)
db.add(record)
try:
db.commit()
except IntegrityError:
db.rollback()
delete_from_storage(storage_key)
raise HTTPException(
status_code=409,
detail="You have already uploaded this document for this tax year. "
"Delete the existing one to replace it."
)
db.refresh(record)
crud.log_action(db, "upload_business", user_id=current_user.id, target=f"business_doc:{record.id}", detail=file.filename)
admins = db.query(User).filter(User.role.in_([UserRole.admin, UserRole.super_admin])).all()
for admin in admins:
background.add_task(
send_email,
to=admin.email,
subject="New Business Document Uploaded — BookKeepro",
body=f"<p><strong>{current_user.email}</strong> uploaded a business document: <strong>{file.filename}</strong> ({doc_type}).</p>",
)
return {
"id": record.id,
"filename": record.filename,
"business_type": record.business_type,
"storage_key": record.storage_key,
"tax_year": record.tax_year,
}
@router.delete("/business-documents/{doc_id}")
def delete_business_document(
doc_id: int,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
doc = db.query(BusinessDocument).filter_by(id=doc_id).first()
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
if doc.user_id != current_user.id:
raise HTTPException(status_code=403, detail="Not authorized")
logger.info(f"User {current_user.id} deleting business document {doc_id}")
delete_from_storage(doc.storage_key)
doc.deleted_at = datetime.utcnow()
db.commit()
crud.log_action(db, "delete_business", user_id=current_user.id, target=f"business_doc:{doc_id}")
return {"deleted": True}
# ─────────────────────────────────────────────
# Review status — admin persists approve/reject decisions
# ─────────────────────────────────────────────
@router.patch("/personal-documents/{doc_id}/review-status")
def set_personal_review_status(
doc_id: int,
payload: ReviewStatusUpdate,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Admin sets approve/reject/pending on a personal document."""
doc = db.query(PersonalDocument).filter_by(id=doc_id).first()
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
doc.review_status = payload.status
doc.review_note = payload.note
db.commit()
crud.log_action(
db, f"review_{payload.status}",
user_id=current_user.id,
target=f"personal_doc:{doc_id}",
detail=f"owner:{doc.user_id}" + (f" note:{payload.note}" if payload.note else ""),
)
return {"id": doc_id, "review_status": payload.status}
@router.patch("/business-documents/{doc_id}/review-status")
def set_business_review_status(
doc_id: int,
payload: ReviewStatusUpdate,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
"""Admin sets approve/reject/pending on a business document."""
doc = db.query(BusinessDocument).filter_by(id=doc_id).first()
if not doc:
raise HTTPException(status_code=404, detail="Document not found")
doc.review_status = payload.status
doc.review_note = payload.note
db.commit()
crud.log_action(
db, f"review_{payload.status}",
user_id=current_user.id,
target=f"business_doc:{doc_id}",
detail=f"owner:{doc.user_id}" + (f" note:{payload.note}" if payload.note else ""),
)
return {"id": doc_id, "review_status": payload.status}
# ─────────────────────────────────────────────
# Admin — all documents for one user
# ─────────────────────────────────────────────
@router.get("/admin/users/{user_id}/documents")
def get_user_all_documents(
user_id: int,
tax_year: int | None = None,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
# Regular admins can only view documents for user-role accounts
if current_user.role == UserRole.admin and user.role != UserRole.user:
raise HTTPException(
status_code=403,
detail="Admins can only view documents for regular user accounts"
)
logger.info(f"Admin {current_user.id} retrieving all documents for user {user_id}")
pq = db.query(PersonalDocument).filter(
PersonalDocument.user_id == user_id, PersonalDocument.deleted_at == None
)
bq = db.query(BusinessDocument).filter(
BusinessDocument.user_id == user_id, BusinessDocument.deleted_at == None
)
if tax_year:
pq = pq.filter(PersonalDocument.tax_year == tax_year)
bq = bq.filter(BusinessDocument.tax_year == tax_year)
personal_docs = pq.order_by(PersonalDocument.uploaded_at.desc()).all()
business_docs = bq.order_by(BusinessDocument.uploaded_at.desc()).all()
documents = [
{
"id": d.id,
"table": "personal",
"doc_type": d.doc_type,
"filename": d.filename,
"storage_key": d.storage_key,
"uploaded_at": d.uploaded_at.isoformat() if d.uploaded_at else None,
"tax_year": d.tax_year,
"review_status": d.review_status,
"review_note": d.review_note,
}
for d in personal_docs
] + [
{
"id": d.id,
"table": "business",
"doc_type": d.business_type,
"filename": d.filename,
"storage_key": d.storage_key,
"uploaded_at": d.uploaded_at.isoformat() if d.uploaded_at else None,
"tax_year": d.tax_year,
"review_status": d.review_status,
"review_note": d.review_note,
}
for d in business_docs
]
return {
"user": {
"id": user.id,
"name": user.name,
"email": user.email,
"role": user.role.value if hasattr(user.role, "value") else str(user.role),
"engagement_acknowledged_at": (
user.engagement_acknowledged_at.isoformat()
if user.engagement_acknowledged_at else None
),
},
"documents": documents,
}
# ─────────────────────────────────────────────
# Admin — delete a user and all documents
# ─────────────────────────────────────────────
@router.delete("/admin/users/{user_id}")
def delete_user_completely(
user_id: int,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
if user_id == current_user.id:
raise HTTPException(status_code=400, detail="Cannot delete your own account")
user = db.query(User).filter(User.id == user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
# Regular admins can only delete user-role accounts
# Super_admin can delete admin or user accounts (but not other super_admins)
if current_user.role == UserRole.admin and user.role != UserRole.user:
raise HTTPException(
status_code=403,
detail="Admins can only delete regular user accounts"
)
if current_user.role == UserRole.super_admin and user.role == UserRole.super_admin:
raise HTTPException(
status_code=403,
detail="Super admin accounts cannot be deleted through the dashboard"
)
logger.info(f"Admin {current_user.id} deleting user {user_id}")
try:
for doc in db.query(AdminDocument).filter(AdminDocument.user_id == user_id).all():
delete_from_storage(doc.storage_key)
db.delete(doc)
for doc in db.query(AdminDocument).filter(AdminDocument.uploaded_by == user_id).all():
delete_from_storage(doc.storage_key)
db.delete(doc)
for doc in db.query(PersonalDocument).filter(PersonalDocument.user_id == user_id).all():
delete_from_storage(doc.storage_key)
db.delete(doc)
for doc in db.query(BusinessDocument).filter(BusinessDocument.user_id == user_id).all():
delete_from_storage(doc.storage_key)
db.delete(doc)
# Clean up legacy uploaded_files rows and audit logs to avoid FK constraint errors on db.delete(user)
from app.models import UploadedFile, AuditLog
db.query(UploadedFile).filter(UploadedFile.owner_id == user_id).delete()
db.query(AuditLog).filter(AuditLog.user_id == user_id).delete()
db.commit()
crud.log_action(db, "delete_user", user_id=current_user.id, target=f"user:{user_id}")
db.delete(user)
db.commit()
except Exception as e:
db.rollback()
logger.error(f"User deletion failed for {user_id}: {e}")
raise HTTPException(status_code=500, detail="Deletion failed. No changes were made.")
return {"deleted": True, "user_id": user_id}
# ─────────────────────────────────────────────
# Batch upload notification — call once after all files uploaded (#11)
# ─────────────────────────────────────────────
@router.post("/notify-upload-complete")
async def notify_upload_complete(
payload: UploadCompleteNotify,
background: BackgroundTasks,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
"""
Send one summary email after a user finishes uploading all documents.
Call this once from the frontend after the upload session is complete.
Replaces the old per-file email approach.
"""
admin_email = os.getenv("ADMIN_EMAIL")
count = payload.file_count
category = payload.doc_category
background.add_task(
send_email,
to=current_user.email,
subject=f"{category} Documents Uploaded — BookKeepro",
body=f"""
<p>Dear {current_user.name or "Sir/Ma'am"},</p>
<p>We received <strong>{count}</strong> {category.lower()}
document{"s" if count != 1 else ""} from you.</p>
<p>Our team will review {"them" if count != 1 else "it"} and update you shortly.</p>
<br><strong>BookKeepro Team</strong>
""",
)
admins = db.query(User).filter(User.role.in_([UserRole.admin, UserRole.super_admin])).all()
for admin in admins:
background.add_task(
send_email,
to=admin.email,
subject=f"New {category} Upload — BookKeepro",
body=f"<p><strong>{current_user.email}</strong> uploaded "
f"{count} {category.lower()} document{'s' if count != 1 else ''}.</p>",
)
return {"status": "notified"}
from pydantic import BaseModel
class NotifyApprovalRequest(BaseModel):
user_id: int
@router.post("/notify/personal")
async def notify_personal_approval(
payload: NotifyApprovalRequest,
background: BackgroundTasks,
db: Session = Depends(get_db),
_=Depends(require_admin),
):
user = db.query(User).filter(User.id == payload.user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
background.add_task(
send_email,
to=user.email,
subject="Personal Documents Approved — BookKeepro",
body=f"""
<p>Dear {user.name or "Sir/Ma'am"},</p>
<p>Your personal documents have been successfully reviewed and approved.</p>
<br><strong>BookKeepro Team</strong>
""",
)
return {"status": "email_sent"}
@router.post("/notify/business")
async def notify_business_approval(
payload: NotifyApprovalRequest,
background: BackgroundTasks,
db: Session = Depends(get_db),
_=Depends(require_admin),
):
user = db.query(User).filter(User.id == payload.user_id).first()
if not user:
raise HTTPException(status_code=404, detail="User not found")
background.add_task(
send_email,
to=user.email,
subject="Business Documents Approved — BookKeepro",
body=f"""
<p>Dear {user.name or "Sir/Ma'am"},</p>
<p>Your business documents have been successfully reviewed and approved.</p>
<br><strong>BookKeepro Team</strong>
""",
)
return {"status": "email_sent"}
# ─────────────────────────────────────────────
# Required Document Templates
# ─────────────────────────────────────────────
from app.models import RequiredDocumentTemplate
@router.get("/templates")
def list_templates(
category: str,
tax_year: int,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
):
templates = (
db.query(RequiredDocumentTemplate)
.filter_by(category=category, tax_year=tax_year)
.order_by(RequiredDocumentTemplate.id.asc())
.all()
)
return [
{
"id": t.id,
"name": t.name,
"download": t.file_url,
}
for t in templates
]
@router.post("/admin/templates")
async def upload_template(
file: UploadFile = File(None),
category: str = Form(...),
tax_year: int = Form(...),
name: str = Form(...),
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
# Only super admin can manage templates
if current_user.role != UserRole.super_admin:
raise HTTPException(status_code=403, detail="Only super admins can manage templates")
file_url = None
if file and file.filename:
storage_key = await upload_to_storage(file)
file_url = get_presigned_url(storage_key)
record = RequiredDocumentTemplate(
category=category,
tax_year=tax_year,
name=name,
file_url=file_url,
)
try:
db.add(record)
db.commit()
db.refresh(record)
except IntegrityError:
db.rollback()
raise HTTPException(status_code=400, detail="A template with this name already exists for the given year.")
return {
"id": record.id,
"name": record.name,
"download": record.file_url,
}
@router.delete("/admin/templates/{template_id}")
def delete_template(
template_id: int,
db: Session = Depends(get_db),
current_user=Depends(get_current_user),
_=Depends(require_admin),
):
if current_user.role != UserRole.super_admin:
raise HTTPException(status_code=403, detail="Only super admins can manage templates")
record = db.query(RequiredDocumentTemplate).filter_by(id=template_id).first()
if not record:
raise HTTPException(status_code=404, detail="Template not found")
if record.file_url and record.file_url.startswith("/uploads/"):
storage_key = record.file_url.split("/uploads/")[1]
delete_from_storage(storage_key)
db.delete(record)
db.commit()
return {"deleted": True}
+202
View File
@@ -0,0 +1,202 @@
from pydantic import BaseModel, EmailStr, field_validator
from typing import Optional, List
from datetime import datetime
# ─────────────────────────────────────────────
# Auth
# ─────────────────────────────────────────────
class SignupRequest(BaseModel):
name: str
email: EmailStr # validates format, not just a plain str
phone: Optional[str] = None
password: str
@field_validator("password")
@classmethod
def password_min_length(cls, v: str) -> str:
if len(v) < 8:
raise ValueError("Password must be at least 8 characters")
return v
@field_validator("name")
@classmethod
def name_not_empty(cls, v: str) -> str:
if not v.strip():
raise ValueError("Name cannot be blank")
return v.strip()
class LoginRequest(BaseModel):
email: EmailStr
password: str
class TokenResponse(BaseModel):
access_token: str
token_type: str
role: Optional[str] = None
user_id: Optional[int] = None
email_verification_required: Optional[bool] = None
class ForgotPasswordRequest(BaseModel):
email: EmailStr
class ResendVerificationRequest(BaseModel):
"""Dedicated schema so resend-verification isn't sharing ForgotPasswordRequest."""
email: EmailStr
class ResetPasswordRequest(BaseModel):
token: str
new_password: str
@field_validator("new_password")
@classmethod
def password_min_length(cls, v: str) -> str:
if len(v) < 8:
raise ValueError("Password must be at least 8 characters")
return v
class RoleChangeRequest(BaseModel):
"""Body for PATCH /api/auth/admin/users/{id}/role — super_admin only."""
role: str
@field_validator("role")
@classmethod
def role_must_be_valid(cls, v: str) -> str:
allowed = {"user", "admin"} # super_admin is DB-only, never assignable via API
if v.lower() not in allowed:
raise ValueError(f"Role must be one of: {', '.join(sorted(allowed))}")
return v.lower()
# ─────────────────────────────────────────────
# Review schemas
# ─────────────────────────────────────────────
class SubmitReviewRequest(BaseModel):
user_id: int
class NotifyUserRequest(BaseModel):
user_id: int
type: str = "personal"
approved: List[str] = []
rejected: List[str] = []
personal_timeline: int = 0
business_timeline: int = 0
@field_validator("approved", "rejected")
@classmethod
def cap_list_length(cls, v: List[str]) -> List[str]:
if len(v) > 100:
raise ValueError("List may not contain more than 100 items")
return v
@field_validator("type")
@classmethod
def valid_type(cls, v: str) -> str:
if v not in ("personal", "business"):
raise ValueError("type must be 'personal' or 'business'")
return v
class AdminDocResponseRequest(BaseModel):
doc_id: int
status: str
reason: str = ""
@field_validator("status")
@classmethod
def valid_status(cls, v: str) -> str:
if v not in ("approved", "rejected"):
raise ValueError("status must be 'approved' or 'rejected'")
return v
@field_validator("reason")
@classmethod
def cap_reason(cls, v: str) -> str:
if len(v) > 1000:
raise ValueError("Reason must be 1000 characters or fewer")
return v
class ReviewStatusUpdate(BaseModel):
"""Body for PATCH /api/upload/{personal,business}-documents/{id}/review-status"""
status: str
note: str = ""
@field_validator("status")
@classmethod
def valid_status(cls, v: str) -> str:
if v not in ("approved", "rejected", "pending"):
raise ValueError("status must be 'approved', 'rejected', or 'pending'")
return v
@field_validator("note")
@classmethod
def cap_note(cls, v: str) -> str:
if len(v) > 500:
raise ValueError("Note must be 500 characters or fewer")
return v
class PersonalDocumentOut(BaseModel):
id: int
doc_type: str
filename: str
storage_key: str
uploaded_at: Optional[datetime] = None
model_config = {"from_attributes": True}
class BusinessDocumentOut(BaseModel):
id: int
business_type: str
filename: str
storage_key: str
uploaded_at: Optional[datetime] = None
model_config = {"from_attributes": True}
class AdminDocumentOut(BaseModel):
id: int
doc_key: str
doc_label: str
filename: str
storage_key: str
uploaded_at: Optional[datetime] = None
model_config = {"from_attributes": True}
# ─────────────────────────────────────────────
# Upload notification schema
# ─────────────────────────────────────────────
class UploadCompleteNotify(BaseModel):
doc_category: str # "Personal" | "Business"
file_count: int
@field_validator("doc_category")
@classmethod
def valid_category(cls, v: str) -> str:
if v not in ("Personal", "Business"):
raise ValueError("doc_category must be 'Personal' or 'Business'")
return v
@field_validator("file_count")
@classmethod
def positive_count(cls, v: int) -> int:
if v < 1:
raise ValueError("file_count must be at least 1")
return v
+85
View File
@@ -0,0 +1,85 @@
import os
import logging
from pathlib import Path
from dotenv import load_dotenv
logger = logging.getLogger(__name__)
# Load .env from project root
BASE_DIR = Path(__file__).resolve().parents[3]
load_dotenv(BASE_DIR / ".env")
def _build_mail_client():
"""Build FastMail client lazily so a bad SMTP config never crashes the app on startup."""
try:
from fastapi_mail import FastMail, ConnectionConfig
smtp_user = os.getenv("SMTP_USER")
smtp_password = os.getenv("SMTP_PASSWORD")
mail_from = os.getenv("MAIL_FROM")
smtp_host = os.getenv("SMTP_HOST")
# Refuse to build a broken config — missing critical values
if not all([smtp_user, smtp_password, mail_from, smtp_host]):
logger.warning(
"Email not configured: one or more SMTP env vars are missing. "
"Set SMTP_USER, SMTP_PASSWORD, MAIL_FROM, SMTP_HOST in .env"
)
return None
# Guard against placeholder value
if "PASTE" in (smtp_password or "").upper():
logger.warning(
"SMTP_PASSWORD looks like a placeholder. "
"Set a real Gmail App Password in .env"
)
return None
conf = ConnectionConfig(
MAIL_USERNAME=smtp_user,
MAIL_PASSWORD=smtp_password,
MAIL_FROM=mail_from,
MAIL_PORT=int(os.getenv("SMTP_PORT", "587")),
MAIL_SERVER=smtp_host,
MAIL_STARTTLS=os.getenv("SMTP_TLS", "True").strip().lower() == "true",
MAIL_SSL_TLS=os.getenv("MAIL_SSL_TLS", "False").strip().lower() == "true",
MAIL_FROM_NAME=os.getenv("MAIL_FROM_NAME", "BookKeepro"),
)
return FastMail(conf)
except Exception as e:
logger.error(f"Failed to initialise email client: {e}")
return None
async def send_email(to: str, subject: str, body: str) -> bool:
"""
Send an HTML email. Returns True on success, False on any failure.
Errors are logged but never crash the caller.
"""
try:
if not to or "@" not in to:
logger.warning(f"Invalid recipient email: {to}")
return False
fm = _build_mail_client()
if fm is None:
logger.warning(f"Email skipped (client not configured) — would have sent to {to}: {subject}")
return False
from fastapi_mail import MessageSchema
message = MessageSchema(
subject=subject,
recipients=[to],
body=body,
subtype="html",
)
await fm.send_message(message)
logger.info(f"Email sent to {to}: {subject}")
return True
except Exception as e:
logger.error(f"Failed to send email to {to}: {e}")
return False
+91
View File
@@ -0,0 +1,91 @@
from app.utils.emailer import send_email
# async def send_login_welcome_email(to: str, name: str | None = None):
# display_name = name or "Valued Customer"
# body = f"""
# <p>Dear {display_name},</p>
# <p>
# Welcome to <strong>BookKeepro</strong>
# </p>
# <p>
# You have successfully logged in to your account.
# We’re excited to support you with your compliance and bookkeeping needs.
# </p>
# <p>
# You can access your dashboard anytime using the link below:
# </p>
# <p>
# <a href="https://bookkeepro.net/dashboard"
# style="color:#0077c8;font-weight:600;text-decoration:none;">
# 👉 Go to Dashboard
# </a>
# </p>
# <p style="margin-top:20px;">
# If this login was not initiated by you, please contact our support team immediately.
# </p>
# <p style="margin-top:20px;">
# Kind regards,<br>
# <strong>BookKeepro Team</strong>
# </p>
# """
# await send_email(
# to=to,
# subject="Welcome to BookKeepro",
# body=body
# )
# app/utils/emailer.py
async def send_signup_welcome_email(to: str, name: str | None = None):
display_name = name or "Valued Customer"
body = f"""
<p>Dear {display_name},</p>
<p>
Welcome to <strong>BookKeepro</strong> 🎉
</p>
<p>
Your account has been successfully created.
We’re excited to support you with your compliance and bookkeeping needs.
</p>
<p>
You can log in to your dashboard using the link below:
</p>
<p>
<a href="https://bookkeepro.net/login"
style="color:#0077c8;font-weight:600;text-decoration:none;">
👉 Login to BookKeepro
</a>
</p>
<p style="margin-top:20px;">
If you did not create this account, please contact our support team immediately.
</p>
<p style="margin-top:20px;">
Kind regards,<br>
<strong>BookKeepro Team</strong>
</p>
"""
await send_email(
to=to,
subject="Welcome to BookKeepro 🎉",
body=body
)