Spaces:
Running

axeronis commited on
Commit
50d41d0
·
1 Parent(s): 8e64778

fix: Robust database cleanup and security fixes for password hashing

Browse files
backend/app/core/security.py CHANGED
@@ -1,48 +1,34 @@
1
  """Security utilities for password hashing and JWT token management."""
2
  from datetime import datetime, timedelta
3
  from typing import Optional
4
- from passlib.context import CryptContext
5
  import jwt
6
  from fastapi import HTTPException, status
7
 
8
  from app.core.config import settings
9
 
10
 
11
- # Password hashing context
12
- pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
13
-
14
 
15
  def get_password_hash(password: str) -> str:
16
  """
17
  Hash a password using bcrypt.
18
- Truncates password to 72 bytes to comply with bcrypt limitations.
19
-
20
- Args:
21
- password: Plain text password
22
-
23
- Returns:
24
- Hashed password string
25
  """
26
- # Bcrypt has a 72 byte password limit, truncate if necessary
27
- password_bytes = password.encode('utf-8')[:72]
28
- return pwd_context.hash(password_bytes)
29
 
30
 
31
  def verify_password(plain_password: str, hashed_password: str) -> bool:
32
  """
33
  Verify a password against a hash.
34
- Truncates password to 72 bytes to comply with bcrypt limitations.
35
-
36
- Args:
37
- plain_password: Plain text password to verify
38
- hashed_password: Hashed password to compare against
39
-
40
- Returns:
41
- True if password matches, False otherwise
42
  """
43
- # Bcrypt has a 72 byte password limit, truncate if necessary
44
- password_bytes = plain_password.encode('utf-8')[:72]
45
- return pwd_context.verify(password_bytes, hashed_password)
 
 
 
46
 
47
 
48
  def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
 
1
  """Security utilities for password hashing and JWT token management."""
2
  from datetime import datetime, timedelta
3
  from typing import Optional
4
+ import bcrypt
5
  import jwt
6
  from fastapi import HTTPException, status
7
 
8
  from app.core.config import settings
9
 
10
 
11
+ # Password hashing context (Removed passlib due to bcrypt compatibility issues)
 
 
12
 
13
  def get_password_hash(password: str) -> str:
14
  """
15
  Hash a password using bcrypt.
 
 
 
 
 
 
 
16
  """
17
+ pwd_bytes = password.encode('utf-8')
18
+ salt = bcrypt.gensalt()
19
+ return bcrypt.hashpw(pwd_bytes, salt).decode('utf-8')
20
 
21
 
22
  def verify_password(plain_password: str, hashed_password: str) -> bool:
23
  """
24
  Verify a password against a hash.
 
 
 
 
 
 
 
 
25
  """
26
+ try:
27
+ pwd_bytes = plain_password.encode('utf-8')
28
+ hash_bytes = hashed_password.encode('utf-8')
29
+ return bcrypt.checkpw(pwd_bytes, hash_bytes)
30
+ except Exception:
31
+ return False
32
 
33
 
34
  def create_access_token(data: dict, expires_delta: Optional[timedelta] = None) -> str:
backend/scripts/cleanup_users.py CHANGED
@@ -6,11 +6,19 @@ import os
6
  # Add the parent directory to the path so we can import the app modules
7
  sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8
 
9
- from sqlmodel import select, delete
10
  from sqlalchemy.ext.asyncio import AsyncSession
11
  from app.core.database import async_session_maker
12
  from app.models.user import User
13
  from app.models.tenant import Tenant
 
 
 
 
 
 
 
 
14
  from app.core.config import settings
15
 
16
  async def cleanup_database():
@@ -27,18 +35,66 @@ async def cleanup_database():
27
 
28
  async with async_session_maker() as session:
29
  try:
30
- # Delete Users first (due to foreign key constraints, though often it's the other way if cascade is set,
31
- # but usually User depends on Tenant. User.tenant_id -> Tenant.id)
32
- # Actually, User has a foreign key to Tenant. So we delete Users first.
 
 
33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  print("Deleting Users...")
35
  statement = delete(User)
36
- result = await session.exec(statement)
37
  print(f"Deleted {result.rowcount} users.")
38
 
 
39
  print("Deleting Tenants...")
40
  statement = delete(Tenant)
41
- result = await session.exec(statement)
42
  print(f"Deleted {result.rowcount} tenants.")
43
 
44
  await session.commit()
 
6
  # Add the parent directory to the path so we can import the app modules
7
  sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
8
 
9
+ from sqlmodel import select, delete, update
10
  from sqlalchemy.ext.asyncio import AsyncSession
11
  from app.core.database import async_session_maker
12
  from app.models.user import User
13
  from app.models.tenant import Tenant
14
+ from app.models.lead import Lead, Conversation, Message
15
+ from app.models.product import Product
16
+ from app.models.booking import Appointment, Availability
17
+ from app.models.partner import Partner, PartnerEarning
18
+ from app.models.sales_stage import SalesStage
19
+ from app.models.knowledge import KnowledgeBase
20
+ from app.models.ai_training import AIFeedback, AITrainingExample, AILearningRule
21
+ from app.models.crm_integration import CRMIntegration, CRMSyncLog, CRMFieldMapping, LeadCRMLink
22
  from app.core.config import settings
23
 
24
  async def cleanup_database():
 
35
 
36
  async with async_session_maker() as session:
37
  try:
38
+
39
+
40
+ # 1. Delete deeply nested dependencies (Grandchildren)
41
+ print("Deleting Messages...")
42
+ await session.execute(delete(Message))
43
 
44
+ print("Deleting CRM Logs & Links...")
45
+ await session.execute(delete(CRMSyncLog))
46
+ await session.execute(delete(LeadCRMLink))
47
+ await session.execute(delete(CRMFieldMapping))
48
+
49
+ print("Deleting AI Training Data & Knowledge Base...")
50
+ await session.execute(delete(AIFeedback))
51
+ await session.execute(delete(AITrainingExample))
52
+ await session.execute(delete(AILearningRule))
53
+ await session.execute(delete(KnowledgeBase))
54
+
55
+ # 2. Delete Children
56
+ print("Deleting Conversations...")
57
+ await session.execute(delete(Conversation))
58
+
59
+ print("Deleting Appointments & Availability...")
60
+ await session.execute(delete(Appointment))
61
+ await session.execute(delete(Availability))
62
+
63
+ print("Deleting Products...")
64
+ await session.execute(delete(Product))
65
+
66
+ print("Deleting Sales Stages...")
67
+ await session.execute(delete(SalesStage))
68
+
69
+ print("Deleting CRM Integrations...")
70
+ await session.execute(delete(CRMIntegration))
71
+
72
+ print("Deleting Leads...")
73
+ await session.execute(delete(Lead))
74
+
75
+ # 3. Break Cycles (Tenant -> Partner)
76
+ print("Nullifying Tenant -> Partner links...")
77
+ # We must nullify partner_ref_id in Tenants to safely delete Partners
78
+ statement = update(Tenant).values(partner_ref_id=None)
79
+ await session.execute(statement)
80
+
81
+ # 4. Delete Partners (referred by Tenant, refers to User)
82
+ print("Deleting Partner Earnings...")
83
+ await session.execute(delete(PartnerEarning))
84
+
85
+ print("Deleting Partners...")
86
+ await session.execute(delete(Partner))
87
+
88
+ # 5. Delete Users (refers to Tenant)
89
  print("Deleting Users...")
90
  statement = delete(User)
91
+ result = await session.execute(statement)
92
  print(f"Deleted {result.rowcount} users.")
93
 
94
+ # 6. Delete Tenants (Top level)
95
  print("Deleting Tenants...")
96
  statement = delete(Tenant)
97
+ result = await session.execute(statement)
98
  print(f"Deleted {result.rowcount} tenants.")
99
 
100
  await session.commit()
backend/scripts/create_superuser.py CHANGED
@@ -21,7 +21,7 @@ async def create_superuser():
21
  async with async_session_maker() as session:
22
  # Check if user exists
23
  statement = select(User).where(User.email == email)
24
- result = await session.exec(statement)
25
  user = result.first()
26
 
27
  if user:
@@ -33,7 +33,7 @@ async def create_superuser():
33
  tenant = Tenant(
34
  name="Admin Tenant",
35
  business_name="MicroFunnel Admin",
36
- subscription_plan="enterprise"
37
  )
38
  session.add(tenant)
39
  await session.commit()
 
21
  async with async_session_maker() as session:
22
  # Check if user exists
23
  statement = select(User).where(User.email == email)
24
+ result = await session.execute(statement)
25
  user = result.first()
26
 
27
  if user:
 
33
  tenant = Tenant(
34
  name="Admin Tenant",
35
  business_name="MicroFunnel Admin",
36
+ subscription_plan="unlimited"
37
  )
38
  session.add(tenant)
39
  await session.commit()