Compare commits
1 Commits
codex/crea
...
codex/defi
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
761740de12 |
@@ -26,6 +26,7 @@ from services.database import get_db
|
||||
from middleware.auth_middleware import get_current_user, get_current_user_with_query_token
|
||||
from api.story_writer.utils.auth import require_authenticated_user
|
||||
from utils.asset_tracker import save_asset_to_library
|
||||
from models.asset_metadata_schema import build_podcast_asset_metadata
|
||||
from models.story_models import StoryAudioResult
|
||||
from loguru import logger
|
||||
from ..constants import get_podcast_audio_service, get_podcast_media_dir
|
||||
@@ -217,11 +218,11 @@ async def upload_podcast_audio(
|
||||
title=f"Uploaded Audio - {project_id}",
|
||||
description="Uploaded podcast audio/voice sample",
|
||||
tags=["podcast", "audio", "upload", project_id],
|
||||
asset_metadata={
|
||||
"project_id": project_id,
|
||||
"type": "uploaded_audio",
|
||||
"status": "completed",
|
||||
},
|
||||
asset_metadata=build_podcast_asset_metadata(
|
||||
asset_role="uploaded_audio",
|
||||
project_id=project_id,
|
||||
origin="podcast.audio.upload",
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[Podcast] Failed to save audio asset: {e}")
|
||||
@@ -455,11 +456,12 @@ async def generate_podcast_audio(
|
||||
provider=result.get("provider"),
|
||||
model=result.get("model"),
|
||||
cost=result.get("cost"),
|
||||
asset_metadata={
|
||||
"scene_id": request.scene_id,
|
||||
"scene_title": request.scene_title,
|
||||
"status": "completed",
|
||||
},
|
||||
asset_metadata=build_podcast_asset_metadata(
|
||||
asset_role="podcast_audio",
|
||||
project_id=request.project_id,
|
||||
origin="podcast.audio.generate",
|
||||
extras={"scene_id": request.scene_id, "scene_title": request.scene_title},
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[Podcast] Failed to save audio asset: {e}")
|
||||
@@ -621,13 +623,12 @@ async def combine_podcast_audio(
|
||||
title=f"Combined Podcast - {request.project_id}",
|
||||
description=f"Combined podcast audio from {len(request.scene_ids)} scenes",
|
||||
tags=["podcast", "audio", "combined", request.project_id],
|
||||
asset_metadata={
|
||||
"project_id": request.project_id,
|
||||
"scene_ids": request.scene_ids,
|
||||
"scene_count": len(request.scene_ids),
|
||||
"total_duration": total_duration,
|
||||
"status": "completed",
|
||||
},
|
||||
asset_metadata=build_podcast_asset_metadata(
|
||||
asset_role="combined_podcast_audio",
|
||||
project_id=request.project_id,
|
||||
origin="podcast.audio.combine",
|
||||
extras={"scene_ids": request.scene_ids, "scene_count": len(request.scene_ids), "total_duration": total_duration},
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[Podcast] Failed to save combined audio asset: {e}")
|
||||
|
||||
@@ -18,6 +18,7 @@ from api.story_writer.utils.auth import require_authenticated_user
|
||||
from services.llm_providers.main_image_generation import generate_image
|
||||
from services.llm_providers.main_image_editing import edit_image
|
||||
from utils.asset_tracker import save_asset_to_library
|
||||
from models.asset_metadata_schema import build_podcast_asset_metadata
|
||||
from loguru import logger
|
||||
from ..constants import get_podcast_media_dir, PODCAST_AVATARS_SUBDIR
|
||||
from ..presenter_personas import choose_persona_id, get_persona
|
||||
@@ -111,11 +112,11 @@ async def upload_podcast_avatar(
|
||||
title=f"Podcast Presenter Avatar - {project_id}",
|
||||
description="Podcast presenter avatar image",
|
||||
tags=["podcast", "avatar", project_id],
|
||||
asset_metadata={
|
||||
"project_id": project_id,
|
||||
"type": "presenter_avatar",
|
||||
"status": "completed",
|
||||
},
|
||||
asset_metadata=build_podcast_asset_metadata(
|
||||
asset_role="presenter_avatar",
|
||||
project_id=project_id,
|
||||
origin="podcast.avatar.upload",
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[Podcast] Failed to save avatar asset (non-fatal): {e}")
|
||||
@@ -223,12 +224,12 @@ async def make_avatar_presentable(
|
||||
tags=["podcast", "avatar", "presenter", "transformed", project_id],
|
||||
provider=result.provider,
|
||||
model=result.model,
|
||||
asset_metadata={
|
||||
"project_id": project_id,
|
||||
"type": "transformed_presenter",
|
||||
"original_avatar_url": avatar_url,
|
||||
"status": "completed",
|
||||
},
|
||||
asset_metadata=build_podcast_asset_metadata(
|
||||
asset_role="transformed_presenter",
|
||||
project_id=project_id,
|
||||
origin="podcast.avatar.make_presentable",
|
||||
extras={"original_avatar_url": avatar_url},
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[Podcast] Failed to save transformed avatar asset: {e}")
|
||||
@@ -404,14 +405,12 @@ async def generate_podcast_presenters(
|
||||
tags=["podcast", "avatar", "presenter", project_id],
|
||||
provider=result.provider,
|
||||
model=result.model,
|
||||
asset_metadata={
|
||||
"project_id": project_id,
|
||||
"speaker_number": i + 1,
|
||||
"type": "generated_presenter",
|
||||
"status": "completed",
|
||||
"persona_id": selected_persona_id,
|
||||
"seed": seed,
|
||||
},
|
||||
asset_metadata=build_podcast_asset_metadata(
|
||||
asset_role="generated_presenter",
|
||||
project_id=project_id,
|
||||
origin="podcast.avatar.generate",
|
||||
extras={"speaker_number": i + 1, "persona_id": selected_persona_id, "seed": seed},
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[Podcast] Failed to save presenter asset: {e}")
|
||||
|
||||
@@ -16,6 +16,7 @@ from middleware.auth_middleware import get_current_user, get_current_user_with_q
|
||||
from api.story_writer.utils.auth import require_authenticated_user
|
||||
from services.llm_providers.main_image_generation import generate_image, generate_character_image
|
||||
from utils.asset_tracker import save_asset_to_library
|
||||
from models.asset_metadata_schema import build_podcast_asset_metadata
|
||||
from loguru import logger
|
||||
from ..constants import get_podcast_media_dir
|
||||
from ..models import PodcastImageRequest, PodcastImageResponse
|
||||
@@ -417,11 +418,12 @@ async def generate_podcast_scene_image(
|
||||
tags=["podcast", "scene", request.scene_id],
|
||||
provider=result.provider,
|
||||
model=result.model,
|
||||
asset_metadata={
|
||||
"scene_id": request.scene_id,
|
||||
"scene_title": request.scene_title,
|
||||
"status": "completed",
|
||||
},
|
||||
asset_metadata=build_podcast_asset_metadata(
|
||||
asset_role="podcast_scene_image",
|
||||
project_id=request.project_id,
|
||||
origin="podcast.images.generate",
|
||||
extras={"scene_id": request.scene_id, "scene_title": request.scene_title},
|
||||
),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[Podcast] Failed to save image asset: {e}")
|
||||
|
||||
76
backend/models/asset_metadata_schema.py
Normal file
76
backend/models/asset_metadata_schema.py
Normal file
@@ -0,0 +1,76 @@
|
||||
"""Shared schema/builders for content asset metadata."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, Optional, Tuple
|
||||
|
||||
SCHEMA_VERSION = "1.0"
|
||||
PODCAST_FEATURE = "podcast_maker"
|
||||
|
||||
REQUIRED_KEYS = (
|
||||
"schema_version",
|
||||
"feature",
|
||||
"asset_role",
|
||||
"project_id",
|
||||
"status",
|
||||
"origin",
|
||||
)
|
||||
|
||||
|
||||
def build_asset_metadata(
|
||||
*,
|
||||
feature: str,
|
||||
asset_role: str,
|
||||
project_id: Optional[str],
|
||||
status: str,
|
||||
origin: str,
|
||||
extras: Optional[Dict[str, Any]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Build normalized, versioned asset metadata payload."""
|
||||
metadata: Dict[str, Any] = {
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"feature": feature,
|
||||
"asset_role": asset_role,
|
||||
"project_id": project_id or "unknown",
|
||||
"status": status,
|
||||
"origin": origin,
|
||||
}
|
||||
if extras:
|
||||
metadata.update({k: v for k, v in extras.items() if v is not None})
|
||||
return metadata
|
||||
|
||||
|
||||
def build_podcast_asset_metadata(
|
||||
*,
|
||||
asset_role: str,
|
||||
project_id: Optional[str],
|
||||
status: str = "completed",
|
||||
origin: str,
|
||||
extras: Optional[Dict[str, Any]] = None,
|
||||
) -> Dict[str, Any]:
|
||||
"""Podcast-specific metadata builder."""
|
||||
return build_asset_metadata(
|
||||
feature=PODCAST_FEATURE,
|
||||
asset_role=asset_role,
|
||||
project_id=project_id,
|
||||
status=status,
|
||||
origin=origin,
|
||||
extras=extras,
|
||||
)
|
||||
|
||||
|
||||
def validate_asset_metadata(metadata: Optional[Dict[str, Any]]) -> Tuple[bool, str]:
|
||||
"""Validate minimum schema requirements."""
|
||||
if metadata is None:
|
||||
return False, "asset_metadata is required"
|
||||
if not isinstance(metadata, dict):
|
||||
return False, "asset_metadata must be a dictionary"
|
||||
|
||||
missing = [key for key in REQUIRED_KEYS if not metadata.get(key)]
|
||||
if missing:
|
||||
return False, f"asset_metadata missing required keys: {', '.join(missing)}"
|
||||
|
||||
if str(metadata.get("schema_version")) != SCHEMA_VERSION:
|
||||
return False, f"Unsupported schema_version: {metadata.get('schema_version')}"
|
||||
|
||||
return True, "ok"
|
||||
63
backend/scripts/backfill_podcast_asset_metadata.py
Normal file
63
backend/scripts/backfill_podcast_asset_metadata.py
Normal file
@@ -0,0 +1,63 @@
|
||||
"""Backfill recent podcast assets with normalized metadata schema."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict
|
||||
|
||||
from sqlalchemy import desc
|
||||
|
||||
from services.database import SessionLocal
|
||||
from models.content_asset_models import ContentAsset, AssetSource
|
||||
from models.asset_metadata_schema import build_podcast_asset_metadata, validate_asset_metadata
|
||||
|
||||
|
||||
def infer_role(meta: Dict[str, Any], filename: str) -> str:
|
||||
return (
|
||||
meta.get("asset_role")
|
||||
or meta.get("type")
|
||||
or ("podcast_audio" if filename.lower().endswith((".mp3", ".wav", ".m4a")) else "podcast_asset")
|
||||
)
|
||||
|
||||
|
||||
def main(days: int = 90) -> None:
|
||||
db = SessionLocal()
|
||||
updated = 0
|
||||
scanned = 0
|
||||
since = datetime.utcnow() - timedelta(days=days)
|
||||
try:
|
||||
assets = (
|
||||
db.query(ContentAsset)
|
||||
.filter(ContentAsset.source_module == AssetSource.PODCAST_MAKER)
|
||||
.filter(ContentAsset.created_at >= since)
|
||||
.order_by(desc(ContentAsset.created_at))
|
||||
.all()
|
||||
)
|
||||
|
||||
for asset in assets:
|
||||
scanned += 1
|
||||
meta = asset.asset_metadata or {}
|
||||
is_valid, _ = validate_asset_metadata(meta)
|
||||
if is_valid:
|
||||
continue
|
||||
|
||||
role = infer_role(meta, asset.filename or "")
|
||||
normalized = build_podcast_asset_metadata(
|
||||
asset_role=role,
|
||||
project_id=meta.get("project_id"),
|
||||
status=meta.get("status", "completed"),
|
||||
origin=meta.get("origin", "migration.backfill_podcast_asset_metadata"),
|
||||
extras=meta,
|
||||
)
|
||||
asset.asset_metadata = normalized
|
||||
db.add(asset)
|
||||
updated += 1
|
||||
|
||||
db.commit()
|
||||
print(f"Scanned={scanned} Updated={updated} Since={since.isoformat()}")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -9,27 +9,26 @@ from typing import Optional, Dict, Any, List
|
||||
from datetime import datetime, timedelta
|
||||
from loguru import logger
|
||||
|
||||
from services.database import get_user_db_path
|
||||
from services.token_crypto_service import TokenCryptoService
|
||||
|
||||
from services.database import get_user_db_path
|
||||
|
||||
class WixOAuthService:
|
||||
"""Manages Wix OAuth2 authentication flow and token storage."""
|
||||
|
||||
|
||||
def __init__(self, db_path: Optional[str] = None):
|
||||
self.db_path = db_path
|
||||
self.token_crypto = TokenCryptoService()
|
||||
|
||||
|
||||
def _get_db_path(self, user_id: str) -> str:
|
||||
if self.db_path:
|
||||
return self.db_path
|
||||
return get_user_db_path(user_id)
|
||||
|
||||
|
||||
def _init_db(self, user_id: str):
|
||||
"""Initialize database tables for OAuth tokens."""
|
||||
db_path = self._get_db_path(user_id)
|
||||
# Ensure directory exists
|
||||
os.makedirs(os.path.dirname(db_path), exist_ok=True)
|
||||
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
@@ -46,133 +45,168 @@ class WixOAuthService:
|
||||
member_id TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
is_active BOOLEAN DEFAULT TRUE,
|
||||
token_key_version TEXT,
|
||||
token_key_reference TEXT
|
||||
is_active BOOLEAN DEFAULT TRUE
|
||||
)
|
||||
''')
|
||||
for column_name, column_def in [
|
||||
("token_key_version", "TEXT"),
|
||||
("token_key_reference", "TEXT"),
|
||||
]:
|
||||
try:
|
||||
cursor.execute(f"ALTER TABLE wix_oauth_tokens ADD COLUMN {column_name} {column_def}")
|
||||
except sqlite3.OperationalError:
|
||||
pass
|
||||
conn.commit()
|
||||
|
||||
def store_tokens(self, user_id: str, access_token: str, refresh_token: Optional[str] = None,
|
||||
expires_in: Optional[int] = None, token_type: str = 'bearer', scope: Optional[str] = None,
|
||||
site_id: Optional[str] = None, member_id: Optional[str] = None) -> bool:
|
||||
|
||||
def store_tokens(
|
||||
self,
|
||||
user_id: str,
|
||||
access_token: str,
|
||||
refresh_token: Optional[str] = None,
|
||||
expires_in: Optional[int] = None,
|
||||
token_type: str = 'bearer',
|
||||
scope: Optional[str] = None,
|
||||
site_id: Optional[str] = None,
|
||||
member_id: Optional[str] = None
|
||||
) -> bool:
|
||||
"""
|
||||
Store Wix OAuth tokens in the database.
|
||||
|
||||
Args:
|
||||
user_id: User ID (Clerk string)
|
||||
access_token: Access token from Wix
|
||||
refresh_token: Optional refresh token
|
||||
expires_in: Optional expiration time in seconds
|
||||
token_type: Token type (default: 'bearer')
|
||||
scope: Optional OAuth scope
|
||||
site_id: Optional Wix site ID
|
||||
member_id: Optional Wix member ID
|
||||
|
||||
Returns:
|
||||
True if tokens were stored successfully
|
||||
"""
|
||||
try:
|
||||
# Ensure DB is initialized for this user
|
||||
self._init_db(user_id)
|
||||
db_path = self._get_db_path(user_id)
|
||||
expires_at = datetime.now() + timedelta(seconds=expires_in) if expires_in else None
|
||||
encrypted_access_token, encrypted_refresh_token = self.token_crypto.encrypt_pair(access_token, refresh_token)
|
||||
|
||||
|
||||
expires_at = None
|
||||
if expires_in:
|
||||
expires_at = datetime.now() + timedelta(seconds=expires_in)
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO wix_oauth_tokens
|
||||
(user_id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id, token_key_version, token_key_reference)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (
|
||||
user_id,
|
||||
encrypted_access_token,
|
||||
encrypted_refresh_token,
|
||||
token_type,
|
||||
expires_at,
|
||||
expires_in,
|
||||
scope,
|
||||
site_id,
|
||||
member_id,
|
||||
self.token_crypto.key_version,
|
||||
self.token_crypto.key_reference,
|
||||
))
|
||||
INSERT INTO wix_oauth_tokens
|
||||
(user_id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (user_id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id))
|
||||
conn.commit()
|
||||
logger.info(f"Wix OAuth: Encrypted token stored for user {user_id}")
|
||||
logger.info(f"Wix OAuth: Token inserted into database for user {user_id}")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error storing Wix tokens for user {user_id}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def get_user_tokens(self, user_id: str) -> List[Dict[str, Any]]:
|
||||
"""Get all active Wix token rows (encrypted values)."""
|
||||
"""Get all active Wix tokens for a user."""
|
||||
try:
|
||||
# Ensure database tables exist to prevent 'no such table' errors
|
||||
self._init_db(user_id)
|
||||
|
||||
db_path = self._get_db_path(user_id)
|
||||
if not os.path.exists(db_path):
|
||||
return []
|
||||
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
SELECT id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id, created_at, token_key_version, token_key_reference
|
||||
SELECT id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id, created_at
|
||||
FROM wix_oauth_tokens
|
||||
WHERE user_id = ? AND is_active = TRUE AND (expires_at IS NULL OR expires_at > datetime('now'))
|
||||
ORDER BY created_at DESC
|
||||
''', (user_id,))
|
||||
|
||||
return [{
|
||||
"id": row[0], "access_token": row[1], "refresh_token": row[2], "token_type": row[3],
|
||||
"expires_at": row[4], "expires_in": row[5], "scope": row[6], "site_id": row[7],
|
||||
"member_id": row[8], "created_at": row[9], "token_key_version": row[10],
|
||||
"token_key_reference": row[11]
|
||||
} for row in cursor.fetchall()]
|
||||
|
||||
tokens = []
|
||||
for row in cursor.fetchall():
|
||||
tokens.append({
|
||||
"id": row[0],
|
||||
"access_token": row[1],
|
||||
"refresh_token": row[2],
|
||||
"token_type": row[3],
|
||||
"expires_at": row[4],
|
||||
"expires_in": row[5],
|
||||
"scope": row[6],
|
||||
"site_id": row[7],
|
||||
"member_id": row[8],
|
||||
"created_at": row[9]
|
||||
})
|
||||
|
||||
return tokens
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting Wix tokens for user {user_id}: {e}")
|
||||
return []
|
||||
|
||||
def get_user_tokens_decrypted(self, user_id: str) -> List[Dict[str, Any]]:
|
||||
"""Decrypt tokens for integration managers and token refresh routines."""
|
||||
decrypted = []
|
||||
for token in self.get_user_tokens(user_id):
|
||||
token_copy = dict(token)
|
||||
token_copy["access_token"] = self.token_crypto.decrypt_token(token_copy.get("access_token"))
|
||||
token_copy["refresh_token"] = self.token_crypto.decrypt_token(token_copy.get("refresh_token"))
|
||||
decrypted.append(token_copy)
|
||||
return decrypted
|
||||
|
||||
|
||||
def get_user_token_status(self, user_id: str) -> Dict[str, Any]:
|
||||
"""Get detailed token status for a user including expired tokens."""
|
||||
try:
|
||||
# Ensure database tables exist to prevent 'no such table' errors
|
||||
self._init_db(user_id)
|
||||
|
||||
db_path = self._get_db_path(user_id)
|
||||
if not os.path.exists(db_path):
|
||||
return {"has_tokens": False, "has_active_tokens": False, "has_expired_tokens": False,
|
||||
"active_tokens": [], "expired_tokens": [], "total_tokens": 0, "last_token_date": None}
|
||||
return {
|
||||
"has_tokens": False,
|
||||
"has_active_tokens": False,
|
||||
"has_expired_tokens": False,
|
||||
"active_tokens": [],
|
||||
"expired_tokens": [],
|
||||
"total_tokens": 0,
|
||||
"last_token_date": None
|
||||
}
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Get all tokens (active and expired)
|
||||
cursor.execute('''
|
||||
SELECT id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id,
|
||||
created_at, is_active, token_key_version, token_key_reference
|
||||
SELECT id, access_token, refresh_token, token_type, expires_at, expires_in, scope, site_id, member_id, created_at, is_active
|
||||
FROM wix_oauth_tokens
|
||||
WHERE user_id = ?
|
||||
ORDER BY created_at DESC
|
||||
''', (user_id,))
|
||||
|
||||
all_tokens, active_tokens, expired_tokens = [], [], []
|
||||
|
||||
all_tokens = []
|
||||
active_tokens = []
|
||||
expired_tokens = []
|
||||
|
||||
for row in cursor.fetchall():
|
||||
token_data = {
|
||||
"id": row[0], "access_token": row[1], "refresh_token": row[2], "token_type": row[3],
|
||||
"expires_at": row[4], "expires_in": row[5], "scope": row[6], "site_id": row[7],
|
||||
"member_id": row[8], "created_at": row[9], "is_active": bool(row[10]),
|
||||
"token_key_version": row[11], "token_key_reference": row[12]
|
||||
"id": row[0],
|
||||
"access_token": row[1],
|
||||
"refresh_token": row[2],
|
||||
"token_type": row[3],
|
||||
"expires_at": row[4],
|
||||
"expires_in": row[5],
|
||||
"scope": row[6],
|
||||
"site_id": row[7],
|
||||
"member_id": row[8],
|
||||
"created_at": row[9],
|
||||
"is_active": bool(row[10])
|
||||
}
|
||||
all_tokens.append(token_data)
|
||||
|
||||
|
||||
# Determine expiry using robust parsing and is_active flag
|
||||
is_active_flag = bool(row[10])
|
||||
not_expired = False
|
||||
try:
|
||||
expires_at_val = row[4]
|
||||
if expires_at_val:
|
||||
# First try Python parsing
|
||||
try:
|
||||
dt = datetime.fromisoformat(expires_at_val) if isinstance(expires_at_val, str) else expires_at_val
|
||||
not_expired = dt > datetime.now()
|
||||
except Exception:
|
||||
# Fallback to SQLite comparison
|
||||
cursor.execute("SELECT datetime('now') < ?", (expires_at_val,))
|
||||
not_expired = cursor.fetchone()[0] == 1
|
||||
else:
|
||||
# No expiry stored => consider not expired
|
||||
not_expired = True
|
||||
except Exception:
|
||||
not_expired = False
|
||||
@@ -181,7 +215,7 @@ class WixOAuthService:
|
||||
active_tokens.append(token_data)
|
||||
else:
|
||||
expired_tokens.append(token_data)
|
||||
|
||||
|
||||
return {
|
||||
"has_tokens": len(all_tokens) > 0,
|
||||
"has_active_tokens": len(active_tokens) > 0,
|
||||
@@ -191,101 +225,81 @@ class WixOAuthService:
|
||||
"total_tokens": len(all_tokens),
|
||||
"last_token_date": all_tokens[0]["created_at"] if all_tokens else None
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting Wix token status for user {user_id}: {e}")
|
||||
return {"has_tokens": False, "has_active_tokens": False, "has_expired_tokens": False,
|
||||
"active_tokens": [], "expired_tokens": [], "total_tokens": 0, "last_token_date": None, "error": str(e)}
|
||||
|
||||
def update_tokens(self, user_id: str, access_token: str, refresh_token: Optional[str] = None,
|
||||
expires_in: Optional[int] = None) -> bool:
|
||||
return {
|
||||
"has_tokens": False,
|
||||
"has_active_tokens": False,
|
||||
"has_expired_tokens": False,
|
||||
"active_tokens": [],
|
||||
"expired_tokens": [],
|
||||
"total_tokens": 0,
|
||||
"last_token_date": None,
|
||||
"error": str(e)
|
||||
}
|
||||
|
||||
def update_tokens(
|
||||
self,
|
||||
user_id: str,
|
||||
access_token: str,
|
||||
refresh_token: Optional[str] = None,
|
||||
expires_in: Optional[int] = None
|
||||
) -> bool:
|
||||
"""Update tokens for a user (e.g., after refresh)."""
|
||||
try:
|
||||
# Ensure DB initialized for this user
|
||||
self._init_db(user_id)
|
||||
db_path = self._get_db_path(user_id)
|
||||
expires_at = datetime.now() + timedelta(seconds=expires_in) if expires_in else None
|
||||
encrypted_access_token = self.token_crypto.encrypt_token(access_token)
|
||||
encrypted_refresh_token = self.token_crypto.encrypt_token(refresh_token) if refresh_token else None
|
||||
|
||||
expires_at = None
|
||||
if expires_in:
|
||||
expires_at = datetime.now() + timedelta(seconds=expires_in)
|
||||
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
if refresh_token:
|
||||
cursor.execute('''
|
||||
UPDATE wix_oauth_tokens
|
||||
SET access_token = ?, refresh_token = ?, expires_at = ?, expires_in = ?,
|
||||
is_active = TRUE, updated_at = datetime('now'), token_key_version = ?, token_key_reference = ?
|
||||
WHERE user_id = ? AND (refresh_token = ? OR refresh_token = ?)
|
||||
''', (encrypted_access_token, encrypted_refresh_token, expires_at, expires_in,
|
||||
self.token_crypto.key_version, self.token_crypto.key_reference,
|
||||
user_id, encrypted_refresh_token, refresh_token))
|
||||
UPDATE wix_oauth_tokens
|
||||
SET access_token = ?, refresh_token = ?, expires_at = ?, expires_in = ?,
|
||||
is_active = TRUE, updated_at = datetime('now')
|
||||
WHERE user_id = ? AND refresh_token = ?
|
||||
''', (access_token, refresh_token, expires_at, expires_in, user_id, refresh_token))
|
||||
else:
|
||||
cursor.execute('''
|
||||
UPDATE wix_oauth_tokens
|
||||
SET access_token = ?, expires_at = ?, expires_in = ?,
|
||||
is_active = TRUE, updated_at = datetime('now'), token_key_version = ?, token_key_reference = ?
|
||||
UPDATE wix_oauth_tokens
|
||||
SET access_token = ?, expires_at = ?, expires_in = ?,
|
||||
is_active = TRUE, updated_at = datetime('now')
|
||||
WHERE user_id = ? AND id = (SELECT id FROM wix_oauth_tokens WHERE user_id = ? ORDER BY created_at DESC LIMIT 1)
|
||||
''', (encrypted_access_token, expires_at, expires_in,
|
||||
self.token_crypto.key_version, self.token_crypto.key_reference, user_id, user_id))
|
||||
''', (access_token, expires_at, expires_in, user_id, user_id))
|
||||
conn.commit()
|
||||
logger.info(f"Wix OAuth: Encrypted tokens updated for user {user_id}")
|
||||
logger.info(f"Wix OAuth: Tokens updated for user {user_id}")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error updating Wix tokens for user {user_id}: {e}")
|
||||
return False
|
||||
|
||||
def rotate_token_encryption(self, user_id: str, batch_size: int = 100) -> Dict[str, int]:
|
||||
"""Re-encrypt existing token rows in batches for key rotation."""
|
||||
self._init_db(user_id)
|
||||
db_path = self._get_db_path(user_id)
|
||||
rotated, skipped, last_id = 0, 0, 0
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
while True:
|
||||
cursor.execute('''
|
||||
SELECT id, access_token, refresh_token
|
||||
FROM wix_oauth_tokens
|
||||
WHERE user_id = ? AND id > ?
|
||||
ORDER BY id ASC
|
||||
LIMIT ?
|
||||
''', (user_id, last_id, batch_size))
|
||||
rows = cursor.fetchall()
|
||||
if not rows:
|
||||
break
|
||||
|
||||
for row_id, enc_access, enc_refresh in rows:
|
||||
last_id = row_id
|
||||
try:
|
||||
plain_access = self.token_crypto.decrypt_token(enc_access)
|
||||
plain_refresh = self.token_crypto.decrypt_token(enc_refresh) if enc_refresh else None
|
||||
except Exception:
|
||||
skipped += 1
|
||||
continue
|
||||
|
||||
new_access, new_refresh = self.token_crypto.encrypt_pair(plain_access, plain_refresh)
|
||||
cursor.execute('''
|
||||
UPDATE wix_oauth_tokens
|
||||
SET access_token = ?, refresh_token = ?, token_key_version = ?, token_key_reference = ?, updated_at = datetime('now')
|
||||
WHERE id = ?
|
||||
''', (new_access, new_refresh, self.token_crypto.key_version, self.token_crypto.key_reference, row_id))
|
||||
rotated += 1
|
||||
conn.commit()
|
||||
|
||||
logger.info(f"Wix OAuth: Encryption rotation complete for user {user_id}; rotated={rotated}, skipped={skipped}")
|
||||
return {"rotated": rotated, "skipped": skipped}
|
||||
|
||||
|
||||
def revoke_token(self, user_id: str, token_id: int) -> bool:
|
||||
"""Revoke a Wix OAuth token."""
|
||||
try:
|
||||
db_path = self._get_db_path(user_id)
|
||||
with sqlite3.connect(db_path) as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
UPDATE wix_oauth_tokens
|
||||
UPDATE wix_oauth_tokens
|
||||
SET is_active = FALSE, updated_at = datetime('now')
|
||||
WHERE user_id = ? AND id = ?
|
||||
''', (user_id, token_id))
|
||||
conn.commit()
|
||||
|
||||
if cursor.rowcount > 0:
|
||||
logger.info(f"Wix token {token_id} revoked for user {user_id}")
|
||||
return True
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error revoking Wix token: {e}")
|
||||
return False
|
||||
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
"""Service for encrypting/decrypting integration tokens with key version metadata."""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import os
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from cryptography.fernet import Fernet, InvalidToken
|
||||
from loguru import logger
|
||||
|
||||
|
||||
class TokenCryptoService:
|
||||
"""Token encryption/decryption service with key version support."""
|
||||
|
||||
ENV_KEY = "ALWRITY_TOKEN_ENCRYPTION_KEY"
|
||||
ENV_KEY_VERSION = "ALWRITY_TOKEN_KEY_VERSION"
|
||||
|
||||
def __init__(self):
|
||||
raw_key = os.getenv(self.ENV_KEY, "")
|
||||
if raw_key:
|
||||
self._fernet_key = self._normalize_key(raw_key)
|
||||
else:
|
||||
self._fernet_key = self._derive_dev_key()
|
||||
self._fernet = Fernet(self._fernet_key)
|
||||
self._key_version = os.getenv(self.ENV_KEY_VERSION, "v1")
|
||||
self._key_reference = self._fingerprint(self._fernet_key)
|
||||
|
||||
@property
|
||||
def key_version(self) -> str:
|
||||
return self._key_version
|
||||
|
||||
@property
|
||||
def key_reference(self) -> str:
|
||||
return self._key_reference
|
||||
|
||||
def encrypt_token(self, token: Optional[str]) -> Optional[str]:
|
||||
if token is None:
|
||||
return None
|
||||
return self._fernet.encrypt(token.encode("utf-8")).decode("utf-8")
|
||||
|
||||
def decrypt_token(self, encrypted_token: Optional[str]) -> Optional[str]:
|
||||
if encrypted_token is None:
|
||||
return None
|
||||
try:
|
||||
return self._fernet.decrypt(encrypted_token.encode("utf-8")).decode("utf-8")
|
||||
except InvalidToken:
|
||||
logger.error("Token decryption failed due to invalid token/key")
|
||||
raise
|
||||
|
||||
def encrypt_pair(self, access_token: str, refresh_token: Optional[str]) -> Tuple[str, Optional[str]]:
|
||||
return self.encrypt_token(access_token), self.encrypt_token(refresh_token)
|
||||
|
||||
@staticmethod
|
||||
def _normalize_key(raw_key: str) -> bytes:
|
||||
raw_key = raw_key.strip()
|
||||
if len(raw_key) == 44 and raw_key.endswith("="):
|
||||
return raw_key.encode("utf-8")
|
||||
digest = hashlib.sha256(raw_key.encode("utf-8")).digest()
|
||||
return base64.urlsafe_b64encode(digest)
|
||||
|
||||
@staticmethod
|
||||
def _derive_dev_key() -> bytes:
|
||||
seed = "alwrity-local-token-key"
|
||||
digest = hashlib.sha256(seed.encode("utf-8")).digest()
|
||||
return base64.urlsafe_b64encode(digest)
|
||||
|
||||
@staticmethod
|
||||
def _fingerprint(key: bytes) -> str:
|
||||
return hashlib.sha256(key).hexdigest()[:16]
|
||||
@@ -11,6 +11,8 @@ import logging
|
||||
import re
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from models.asset_metadata_schema import validate_asset_metadata
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Maximum file size (100MB)
|
||||
@@ -140,6 +142,12 @@ def save_asset_to_library(
|
||||
if len(title) > 200:
|
||||
title = title[:197] + '...'
|
||||
|
||||
metadata_payload = asset_metadata or {}
|
||||
is_valid_metadata, validation_message = validate_asset_metadata(metadata_payload)
|
||||
if not is_valid_metadata:
|
||||
logger.error(f"Invalid asset metadata: {validation_message}")
|
||||
return None
|
||||
|
||||
service = ContentAssetService(db)
|
||||
asset = service.create_asset(
|
||||
user_id=user_id,
|
||||
@@ -154,7 +162,7 @@ def save_asset_to_library(
|
||||
description=description,
|
||||
prompt=prompt,
|
||||
tags=tags or [],
|
||||
asset_metadata=asset_metadata or {},
|
||||
asset_metadata=metadata_payload,
|
||||
provider=provider,
|
||||
model=model,
|
||||
cost=cost,
|
||||
|
||||
Reference in New Issue
Block a user