Fix deployment configs, fix passlib bug, add super admin script
This commit is contained in:
+1
-4
@@ -11,7 +11,6 @@ services:
|
|||||||
MYSQL_DATABASE: ${MYSQL_DATABASE:-bookkeepprodb}
|
MYSQL_DATABASE: ${MYSQL_DATABASE:-bookkeepprodb}
|
||||||
MYSQL_USER: ${MYSQL_USER:-bookkeep}
|
MYSQL_USER: ${MYSQL_USER:-bookkeep}
|
||||||
MYSQL_PASSWORD: ${MYSQL_PASSWORD:-bookkeepro_pass}
|
MYSQL_PASSWORD: ${MYSQL_PASSWORD:-bookkeepro_pass}
|
||||||
DATABASE_URL: mysql+pymysql://${MYSQL_USER:-bookkeep}:${MYSQL_PASSWORD:-bookkeepro_pass}@db:3306/${MYSQL_DATABASE:-bookkeepprodb}
|
|
||||||
ports:
|
ports:
|
||||||
- "8000:8000"
|
- "8000:8000"
|
||||||
depends_on:
|
depends_on:
|
||||||
@@ -36,10 +35,8 @@ services:
|
|||||||
image: mysql:8.4
|
image: mysql:8.4
|
||||||
command: --default-authentication-plugin=mysql_native_password
|
command: --default-authentication-plugin=mysql_native_password
|
||||||
environment:
|
environment:
|
||||||
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:-rootpassword}
|
MYSQL_ROOT_PASSWORD: ${MYSQL_PASSWORD:-rootpassword}
|
||||||
MYSQL_DATABASE: ${MYSQL_DATABASE:-bookkeepprodb}
|
MYSQL_DATABASE: ${MYSQL_DATABASE:-bookkeepprodb}
|
||||||
MYSQL_USER: ${MYSQL_USER:-bookkeep}
|
|
||||||
MYSQL_PASSWORD: ${MYSQL_PASSWORD:-bookkeepro_pass}
|
|
||||||
volumes:
|
volumes:
|
||||||
- mysql_data:/var/lib/mysql
|
- mysql_data:/var/lib/mysql
|
||||||
healthcheck:
|
healthcheck:
|
||||||
|
|||||||
@@ -25,8 +25,8 @@ async function signupUser() {
|
|||||||
|
|
||||||
// Email verification required — show message, do NOT log in
|
// Email verification required — show message, do NOT log in
|
||||||
if (data.email_verification_required) {
|
if (data.email_verification_required) {
|
||||||
const container = document.getElementById('signupForm')?.closest('.container')
|
const container = document.getElementById('signupForm')?.closest('.auth-box')
|
||||||
|| document.querySelector('.container');
|
|| document.querySelector('.auth-box');
|
||||||
if (container) {
|
if (container) {
|
||||||
container.innerHTML = `
|
container.innerHTML = `
|
||||||
<div style="text-align:center;padding:10px 0;">
|
<div style="text-align:center;padding:10px 0;">
|
||||||
|
|||||||
@@ -1,10 +1,8 @@
|
|||||||
|
import warnings
|
||||||
from sqlalchemy.orm import Session
|
from sqlalchemy.orm import Session
|
||||||
from passlib.context import CryptContext
|
import bcrypt
|
||||||
from app.models import User, AuditLog
|
from app.models import User, AuditLog
|
||||||
|
|
||||||
# Single shared password hashing context
|
|
||||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
|
||||||
|
|
||||||
|
|
||||||
# ─────────────────────────────────────────────
|
# ─────────────────────────────────────────────
|
||||||
# User queries
|
# User queries
|
||||||
@@ -31,7 +29,7 @@ def create_user(
|
|||||||
name=name,
|
name=name,
|
||||||
email=email,
|
email=email,
|
||||||
phone=phone,
|
phone=phone,
|
||||||
hashed_password=pwd_context.hash(password),
|
hashed_password=hash_password(password),
|
||||||
role=role,
|
role=role,
|
||||||
is_verified=is_verified,
|
is_verified=is_verified,
|
||||||
)
|
)
|
||||||
@@ -53,11 +51,14 @@ def update_user_password(db: Session, user: User, hashed_password: str) -> None:
|
|||||||
# ─────────────────────────────────────────────
|
# ─────────────────────────────────────────────
|
||||||
|
|
||||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||||
return pwd_context.verify(plain_password, hashed_password)
|
try:
|
||||||
|
return bcrypt.checkpw(plain_password.encode('utf-8'), hashed_password.encode('utf-8'))
|
||||||
|
except Exception:
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def hash_password(plain_password: str) -> str:
|
def hash_password(plain_password: str) -> str:
|
||||||
return pwd_context.hash(plain_password)
|
return bcrypt.hashpw(plain_password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')
|
||||||
|
|
||||||
|
|
||||||
def authenticate_user(db: Session, email: str, password: str) -> User | None:
|
def authenticate_user(db: Session, email: str, password: str) -> User | None:
|
||||||
|
|||||||
@@ -1,83 +1,66 @@
|
|||||||
import os
|
import os
|
||||||
import logging
|
import logging
|
||||||
|
import smtplib
|
||||||
|
from email.message import EmailMessage
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
|
||||||
|
import aiosmtplib
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
# Load .env from project root
|
# Load .env from project root (4 parents up: utils -> app -> api -> services -> Bookkeep)
|
||||||
BASE_DIR = Path(__file__).resolve().parents[3]
|
BASE_DIR = Path(__file__).resolve().parents[4]
|
||||||
load_dotenv(BASE_DIR / ".env")
|
load_dotenv(BASE_DIR / ".env", override=True)
|
||||||
|
|
||||||
|
|
||||||
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 SMTP 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:
|
async def send_email(to: str, subject: str, body: str) -> bool:
|
||||||
"""
|
"""
|
||||||
Send an HTML email. Returns True on success, False on any failure.
|
Send an HTML email via SMTP using the configured mail settings.
|
||||||
Errors are logged but never crash the caller.
|
Falls back gracefully — errors are logged but never crash the caller.
|
||||||
|
Returns True on success, False on any failure.
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
if not to or "@" not in to:
|
if not to or "@" not in to:
|
||||||
logger.warning(f"Invalid recipient email: {to}")
|
logger.warning(f"Invalid recipient email: {to}")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
fm = _build_mail_client()
|
smtp_host = os.getenv("SMTP_HOST")
|
||||||
if fm is None:
|
smtp_port = int(os.getenv("SMTP_PORT", "587"))
|
||||||
logger.warning(f"Email skipped (client not configured) — would have sent to {to}: {subject}")
|
smtp_user = os.getenv("SMTP_USER")
|
||||||
|
smtp_password = os.getenv("SMTP_PASSWORD")
|
||||||
|
mail_from_email = os.getenv("MAIL_FROM") or smtp_user
|
||||||
|
mail_from_name = os.getenv("MAIL_FROM_NAME", "BookKeepro")
|
||||||
|
smtp_tls = os.getenv("SMTP_TLS", "True").strip().lower() == "true"
|
||||||
|
smtp_ssl_tls = os.getenv("MAIL_SSL_TLS", "False").strip().lower() == "true"
|
||||||
|
|
||||||
|
if not smtp_host:
|
||||||
|
logger.warning("SMTP_HOST not set — email skipped")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
from fastapi_mail import MessageSchema
|
if not mail_from_email:
|
||||||
message = MessageSchema(
|
logger.warning("MAIL_FROM not set — email skipped")
|
||||||
subject=subject,
|
return False
|
||||||
recipients=[to],
|
|
||||||
body=body,
|
message = EmailMessage()
|
||||||
subtype="html",
|
message["From"] = f"{mail_from_name} <{mail_from_email}>"
|
||||||
|
message["To"] = to
|
||||||
|
message["Subject"] = subject
|
||||||
|
message.set_content("This email requires an HTML-capable email client.")
|
||||||
|
message.add_alternative(body, subtype="html")
|
||||||
|
|
||||||
|
await aiosmtplib.send(
|
||||||
|
message,
|
||||||
|
hostname=smtp_host,
|
||||||
|
port=smtp_port,
|
||||||
|
username=smtp_user,
|
||||||
|
password=smtp_password,
|
||||||
|
start_tls=smtp_tls and not smtp_ssl_tls,
|
||||||
|
use_tls=smtp_ssl_tls,
|
||||||
|
timeout=15,
|
||||||
)
|
)
|
||||||
|
|
||||||
await fm.send_message(message)
|
logger.info(f"Email sent to {to} via SMTP: {subject}")
|
||||||
logger.info(f"Email sent to {to}: {subject}")
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import getpass
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from app.db import SessionLocal, engine
|
||||||
|
from app import models
|
||||||
|
from app.crud import get_user_by_email, hash_password
|
||||||
|
|
||||||
|
def create_super_admin():
|
||||||
|
# Ensure tables exist
|
||||||
|
models.Base.metadata.create_all(bind=engine)
|
||||||
|
|
||||||
|
print("--- Create Super Admin ---")
|
||||||
|
email = input("Email: ").strip()
|
||||||
|
if not email:
|
||||||
|
print("Email is required.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
name = input("Name [Super Admin]: ").strip()
|
||||||
|
if not name:
|
||||||
|
name = "Super Admin"
|
||||||
|
|
||||||
|
# In a real shell getpass hides input, but for script ease we'll fallback to input() if needed
|
||||||
|
try:
|
||||||
|
password = getpass.getpass("Password: ")
|
||||||
|
except Exception:
|
||||||
|
password = input("Password: ")
|
||||||
|
|
||||||
|
if not password:
|
||||||
|
print("Password is required.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
db: Session = SessionLocal()
|
||||||
|
try:
|
||||||
|
existing = get_user_by_email(db, email)
|
||||||
|
if existing:
|
||||||
|
if existing.role != "super_admin":
|
||||||
|
print(f"User {email} exists with role '{existing.role}'. Upgrading to super_admin...")
|
||||||
|
existing.role = "super_admin"
|
||||||
|
existing.is_verified = 1
|
||||||
|
db.commit()
|
||||||
|
print("Upgrade successful!")
|
||||||
|
else:
|
||||||
|
print("Super admin already exists with this email.")
|
||||||
|
else:
|
||||||
|
user = models.User(
|
||||||
|
name=name,
|
||||||
|
email=email,
|
||||||
|
phone="",
|
||||||
|
hashed_password=hash_password(password),
|
||||||
|
role="super_admin",
|
||||||
|
is_verified=1
|
||||||
|
)
|
||||||
|
db.add(user)
|
||||||
|
db.commit()
|
||||||
|
print("Super admin created successfully!")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"Error: {e}")
|
||||||
|
db.rollback()
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
create_super_admin()
|
||||||
Reference in New Issue
Block a user