Monteeq CI commited on
Commit
2893cc2
Β·
1 Parent(s): f1bfaaf

πŸš€ Deploy from GitHub @ 77b253d514d91e93ec286153badba977a74696a0

Browse files

Triggered by: Smasduq
Message: feat: update admin dashboard dependencies, enhance login flow, and improve API interactions

- Added new dependencies: @hookform/resolvers, framer-motion, react-hook-form, react-is, and zod.
- Updated @vitejs /plugin-react and vite versions in devDependencies.
- Refactored login function to handle token retrieval and user role validation more robustly.
- Introduced new API functions for managing videos and reports.
- Updated README with relevant scripts and development notes.
- Enhanced CORS handling in backend middleware for improved security and flexibility.

app/api/v1/endpoints/admin.py CHANGED
@@ -16,19 +16,30 @@ from app.services.email_service import send_pro_upgrade_email
16
 
17
  router = APIRouter()
18
 
 
 
 
 
 
 
19
  @router.post("/login", response_model=schemas.Token)
 
20
  async def login_for_admin_access_token(
21
- db: Session = Depends(get_db),
22
  form_data: OAuth2PasswordRequestForm = Depends()
23
  ):
 
24
  user = crud_user.get_user_by_username(db, username=form_data.username)
 
 
 
25
  if not user or not security.verify_password(form_data.password, user.hashed_password):
26
  raise HTTPException(
27
  status_code=status.HTTP_401_UNAUTHORIZED,
28
  detail="Incorrect username or password",
29
  headers={"WWW-Authenticate": "Bearer"},
30
  )
31
-
32
  if user.role != "admin":
33
  raise HTTPException(
34
  status_code=status.HTTP_403_FORBIDDEN,
@@ -39,7 +50,7 @@ async def login_for_admin_access_token(
39
  access_token = security.create_access_token(
40
  data={"sub": user.username}, expires_delta=access_token_expires
41
  )
42
- return {"access_token": access_token, "token_type": "bearer"}
43
 
44
 
45
  @router.get("/users", response_model=List[schemas.User])
@@ -119,7 +130,10 @@ def get_storage_mode(
119
  current_user: dict = Depends(admin_only)
120
  ):
121
  mode = crud_setting.get_setting(db, "storage_mode")
122
- return {"mode": mode or config.STORAGE_MODE}
 
 
 
123
 
124
  @router.put("/settings/storage-mode")
125
  def update_storage_mode(
@@ -127,7 +141,10 @@ def update_storage_mode(
127
  db: Session = Depends(get_db),
128
  current_user: dict = Depends(admin_only)
129
  ):
130
- if mode not in ["gcs", "local"]:
 
 
 
131
  raise HTTPException(status_code=400, detail="Invalid storage mode")
132
 
133
  crud_setting.update_setting(db, "storage_mode", mode)
 
16
 
17
  router = APIRouter()
18
 
19
+ @router.options("/login")
20
+ async def admin_login_options():
21
+ """Explicit CORS preflight handler β€” prevents form-body parser from running on OPTIONS."""
22
+ return {}
23
+
24
+
25
  @router.post("/login", response_model=schemas.Token)
26
+
27
  async def login_for_admin_access_token(
28
+ db: Session = Depends(get_db),
29
  form_data: OAuth2PasswordRequestForm = Depends()
30
  ):
31
+ # Support login by username OR email
32
  user = crud_user.get_user_by_username(db, username=form_data.username)
33
+ if not user:
34
+ user = crud_user.get_user_by_email(db, email=form_data.username)
35
+
36
  if not user or not security.verify_password(form_data.password, user.hashed_password):
37
  raise HTTPException(
38
  status_code=status.HTTP_401_UNAUTHORIZED,
39
  detail="Incorrect username or password",
40
  headers={"WWW-Authenticate": "Bearer"},
41
  )
42
+
43
  if user.role != "admin":
44
  raise HTTPException(
45
  status_code=status.HTTP_403_FORBIDDEN,
 
50
  access_token = security.create_access_token(
51
  data={"sub": user.username}, expires_delta=access_token_expires
52
  )
53
+ return {"access_token": access_token, "token_type": "bearer", "username": user.username}
54
 
55
 
56
  @router.get("/users", response_model=List[schemas.User])
 
130
  current_user: dict = Depends(admin_only)
131
  ):
132
  mode = crud_setting.get_setting(db, "storage_mode")
133
+ mode = mode or config.STORAGE_MODE
134
+ if mode == "gcs":
135
+ mode = "s3"
136
+ return {"mode": mode}
137
 
138
  @router.put("/settings/storage-mode")
139
  def update_storage_mode(
 
141
  db: Session = Depends(get_db),
142
  current_user: dict = Depends(admin_only)
143
  ):
144
+ # Normalize legacy "gcs" label to "s3" (AWS from .env)
145
+ if mode == "gcs":
146
+ mode = "s3"
147
+ if mode not in ["s3", "local"]:
148
  raise HTTPException(status_code=400, detail="Invalid storage mode")
149
 
150
  crud_setting.update_setting(db, "storage_mode", mode)
app/api/v1/endpoints/videos.py CHANGED
@@ -460,7 +460,7 @@ def delete_video_files(video: Video):
460
  s3_key = None
461
  if current_mode == "local" and url.startswith(f"{config.BASE_URL}/static/"):
462
  s3_key = url.replace(f"{config.BASE_URL}/static/", "")
463
- elif current_mode == "s3" and ("amazonaws.com" in url or "cdn.monteeq.com" in url):
464
  # Extract key after .com/
465
  if ".com/" in url:
466
  s3_key = url.split(".com/")[1]
 
460
  s3_key = None
461
  if current_mode == "local" and url.startswith(f"{config.BASE_URL}/static/"):
462
  s3_key = url.replace(f"{config.BASE_URL}/static/", "")
463
+ elif current_mode in ("s3", "gcs") and ("amazonaws.com" in url or "cdn.monteeq.com" in url):
464
  # Extract key after .com/
465
  if ".com/" in url:
466
  s3_key = url.split(".com/")[1]
app/core/config.py CHANGED
@@ -22,15 +22,16 @@ DATABASE_URL = os.getenv("DATABASE_URL")
22
  FLASH_QUOTA_LIMIT = 50
23
  HOME_QUOTA_LIMIT = 20
24
 
25
- # Storage Configuration
26
- STORAGE_MODE = os.getenv("STORAGE_MODE", "s3") # 'local' or 's3'
27
- AWS_ACCESS_KEY_ID = os.getenv("S3_ACCESS_KEY", os.getenv("AWS_ACCESS_KEY_ID", ""))
28
- AWS_SECRET_ACCESS_KEY = os.getenv("S3_SECRET_KEY", os.getenv("AWS_SECRET_ACCESS_KEY", ""))
29
- AWS_STORAGE_BUCKET_NAME = os.getenv("S3_BUCKET_NAME", os.getenv("AWS_STORAGE_BUCKET_NAME", "monteeq"))
30
- AWS_S3_REGION_NAME = os.getenv("S3_REGION", os.getenv("AWS_S3_REGION_NAME", "eu-north-1"))
31
- S3_ENDPOINT = os.getenv("S3_ENDPOINT", None)
 
32
  AWS_S3_USE_ACCELERATE = os.getenv("AWS_S3_USE_ACCELERATE", "false").lower() == "true"
33
- AWS_CLOUDFRONT_DOMAIN = os.getenv("AWS_CLOUDFRONT_DOMAIN", "") # Remove default to avoid broken URLs
34
 
35
  PAYSTACK_SECRET_KEY = os.getenv("PAYSTACK_SECRET_KEY", "")
36
  # STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY", "")
 
22
  FLASH_QUOTA_LIMIT = 50
23
  HOME_QUOTA_LIMIT = 20
24
 
25
+ # Storage Configuration β€” prefer AWS_* from .env; S3_* kept as fallbacks
26
+ STORAGE_MODE = os.getenv("STORAGE_MODE", "s3") # 'local' or 's3'
27
+ AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID") or os.getenv("S3_ACCESS_KEY", "")
28
+ AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY") or os.getenv("S3_SECRET_KEY", "")
29
+ AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME") or os.getenv("S3_BUCKET_NAME", "monteeq")
30
+ AWS_S3_REGION_NAME = os.getenv("AWS_S3_REGION_NAME") or os.getenv("S3_REGION", "eu-north-1")
31
+ _raw_endpoint = os.getenv("S3_ENDPOINT") or ""
32
+ S3_ENDPOINT = _raw_endpoint.strip() or None # empty string β†’ native AWS
33
  AWS_S3_USE_ACCELERATE = os.getenv("AWS_S3_USE_ACCELERATE", "false").lower() == "true"
34
+ AWS_CLOUDFRONT_DOMAIN = os.getenv("AWS_CLOUDFRONT_DOMAIN", "")
35
 
36
  PAYSTACK_SECRET_KEY = os.getenv("PAYSTACK_SECRET_KEY", "")
37
  # STRIPE_SECRET_KEY = os.getenv("STRIPE_SECRET_KEY", "")
app/core/storage.py CHANGED
@@ -68,6 +68,9 @@ class Storage:
68
  self._mode = setting.value
69
  else:
70
  self._mode = config.STORAGE_MODE
 
 
 
71
  self._mode_cache_time = current_time
72
  except Exception as e:
73
  logger.error(f"Error fetching storage_mode from DB: {e}", exc_info=True)
 
68
  self._mode = setting.value
69
  else:
70
  self._mode = config.STORAGE_MODE
71
+ # Legacy "gcs" label β†’ AWS S3 (credentials from .env)
72
+ if self._mode == "gcs":
73
+ self._mode = "s3"
74
  self._mode_cache_time = current_time
75
  except Exception as e:
76
  logger.error(f"Error fetching storage_mode from DB: {e}", exc_info=True)
main.py CHANGED
@@ -47,39 +47,58 @@ app.add_middleware(RequestIDMiddleware)
47
  # ── Anti-Bot Middleware ───────────────────────────────────────────────────────
48
  class AntiBotMiddleware(BaseHTTPMiddleware):
49
  """Identify and block malicious bots globally with CORS support."""
 
 
 
 
 
 
 
 
 
 
 
50
  async def dispatch(self, request: Request, call_next):
51
  from app.core import security
52
-
53
- # 1. Skip check for OPTIONS (CORS preflight), static files, health, and SEO/Sitemaps
54
- if (request.method == "OPTIONS" or
55
- request.url.path.startswith("/static") or
56
- request.url.path == "/health" or
57
- "/seo/" in request.url.path or
58
- "sitemap" in request.url.path):
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  return await call_next(request)
60
-
61
- # 2. Heuristic check
62
  if security.is_bot(request):
63
  ua = request.headers.get("User-Agent", "Unknown")
64
  logger.warning(f"Bot detected and blocked: {ua} from {request.client.host if request.client else 'unknown'}")
65
-
66
  response = JSONResponse(
67
  status_code=403,
68
  content={"detail": "Access denied. Automated traffic detected.", "ua": ua}
69
  )
70
-
71
- # Manually add CORS headers to ensure the browser doesn't throw a generic 'Failed to fetch'
72
- origin = request.headers.get("Origin")
73
- if origin:
74
- # Basic validation: only allow our known domains
75
- if any(domain in origin for domain in ["monteeq.com", "localhost"]):
76
- response.headers["Access-Control-Allow-Origin"] = origin
77
- response.headers["Access-Control-Allow-Credentials"] = "true"
78
-
79
  return response
80
-
81
  return await call_next(request)
82
 
 
83
  app.add_middleware(AntiBotMiddleware)
84
 
85
  # CORS middleware - MUST be added before other middleware
@@ -93,9 +112,13 @@ app.add_middleware(
93
  "https://monteeqorg-backend.hf.space",
94
  "http://localhost:5173",
95
  "http://localhost:5174",
 
96
  ],
 
 
 
97
  allow_credentials=True,
98
- allow_methods=["*"],
99
  allow_headers=["*"],
100
  )
101
 
 
47
  # ── Anti-Bot Middleware ───────────────────────────────────────────────────────
48
  class AntiBotMiddleware(BaseHTTPMiddleware):
49
  """Identify and block malicious bots globally with CORS support."""
50
+
51
+ ALLOWED_ORIGINS = {
52
+ "https://www.monteeq.com",
53
+ "https://monteeq.com",
54
+ "https://admin.monteeq.com",
55
+ "https://www.admin.monteeq.com",
56
+ "https://monteeqorg-backend.hf.space",
57
+ "http://localhost:5173",
58
+ "http://localhost:5174",
59
+ }
60
+
61
  async def dispatch(self, request: Request, call_next):
62
  from app.core import security
63
+
64
+ # Short-circuit CORS preflight β€” return 200 with CORS headers immediately.
65
+ # This prevents BaseHTTPMiddleware body-buffering from interfering with
66
+ # CORSMiddleware and stops the form-body parser from running on OPTIONS.
67
+ if request.method == "OPTIONS":
68
+ origin = request.headers.get("Origin", "")
69
+ response = JSONResponse(status_code=200, content={})
70
+ if origin in self.ALLOWED_ORIGINS:
71
+ response.headers["Access-Control-Allow-Origin"] = origin
72
+ response.headers["Access-Control-Allow-Credentials"] = "true"
73
+ response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, PATCH, OPTIONS"
74
+ response.headers["Access-Control-Allow-Headers"] = "*"
75
+ response.headers["Access-Control-Max-Age"] = "600"
76
+ return response
77
+
78
+ # Skip bot check for static files, health, and SEO endpoints
79
+ if (request.url.path.startswith("/static") or
80
+ request.url.path == "/health" or
81
+ "/seo/" in request.url.path or
82
+ "sitemap" in request.url.path):
83
  return await call_next(request)
84
+
85
+ # Heuristic bot check
86
  if security.is_bot(request):
87
  ua = request.headers.get("User-Agent", "Unknown")
88
  logger.warning(f"Bot detected and blocked: {ua} from {request.client.host if request.client else 'unknown'}")
89
+ origin = request.headers.get("Origin", "")
90
  response = JSONResponse(
91
  status_code=403,
92
  content={"detail": "Access denied. Automated traffic detected.", "ua": ua}
93
  )
94
+ if origin in self.ALLOWED_ORIGINS:
95
+ response.headers["Access-Control-Allow-Origin"] = origin
96
+ response.headers["Access-Control-Allow-Credentials"] = "true"
 
 
 
 
 
 
97
  return response
98
+
99
  return await call_next(request)
100
 
101
+
102
  app.add_middleware(AntiBotMiddleware)
103
 
104
  # CORS middleware - MUST be added before other middleware
 
112
  "https://monteeqorg-backend.hf.space",
113
  "http://localhost:5173",
114
  "http://localhost:5174",
115
+ "http://127.0.0.1:5174",
116
  ],
117
+ # Regex covers any localhost / 127.0.0.1 port for local dev.
118
+ # Production origins are covered by the explicit list above.
119
+ allow_origin_regex=r"http://(localhost|127\.0\.0\.1)(:\d+)?$",
120
  allow_credentials=True,
121
+ allow_methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
122
  allow_headers=["*"],
123
  )
124