webscout 8.3.3__py3-none-any.whl → 8.3.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of webscout might be problematic. Click here for more details.
- webscout/AIutel.py +53 -800
- webscout/Bard.py +2 -22
- webscout/Provider/AISEARCH/__init__.py +11 -10
- webscout/Provider/AISEARCH/felo_search.py +7 -3
- webscout/Provider/AISEARCH/scira_search.py +26 -11
- webscout/Provider/AISEARCH/stellar_search.py +53 -8
- webscout/Provider/Deepinfra.py +81 -57
- webscout/Provider/ExaChat.py +9 -5
- webscout/Provider/Flowith.py +1 -1
- webscout/Provider/FreeGemini.py +2 -2
- webscout/Provider/Gemini.py +3 -10
- webscout/Provider/GeminiProxy.py +31 -5
- webscout/Provider/LambdaChat.py +39 -31
- webscout/Provider/Netwrck.py +5 -8
- webscout/Provider/OLLAMA.py +8 -9
- webscout/Provider/OPENAI/README.md +1 -1
- webscout/Provider/OPENAI/TogetherAI.py +57 -48
- webscout/Provider/OPENAI/TwoAI.py +94 -1
- webscout/Provider/OPENAI/__init__.py +1 -3
- webscout/Provider/OPENAI/autoproxy.py +1 -1
- webscout/Provider/OPENAI/copilot.py +73 -26
- webscout/Provider/OPENAI/deepinfra.py +60 -24
- webscout/Provider/OPENAI/exachat.py +9 -5
- webscout/Provider/OPENAI/monochat.py +3 -3
- webscout/Provider/OPENAI/netwrck.py +4 -7
- webscout/Provider/OPENAI/qodo.py +630 -0
- webscout/Provider/OPENAI/scirachat.py +86 -49
- webscout/Provider/OPENAI/textpollinations.py +19 -14
- webscout/Provider/OPENAI/venice.py +1 -0
- webscout/Provider/Perplexitylabs.py +163 -147
- webscout/Provider/Qodo.py +478 -0
- webscout/Provider/TTI/__init__.py +1 -0
- webscout/Provider/TTI/monochat.py +3 -3
- webscout/Provider/TTI/together.py +7 -6
- webscout/Provider/TTI/venice.py +368 -0
- webscout/Provider/TextPollinationsAI.py +19 -14
- webscout/Provider/TogetherAI.py +57 -44
- webscout/Provider/TwoAI.py +96 -2
- webscout/Provider/TypliAI.py +33 -27
- webscout/Provider/UNFINISHED/PERPLEXED_search.py +254 -0
- webscout/Provider/UNFINISHED/fetch_together_models.py +6 -11
- webscout/Provider/Venice.py +1 -0
- webscout/Provider/WiseCat.py +18 -20
- webscout/Provider/__init__.py +4 -10
- webscout/Provider/copilot.py +58 -61
- webscout/Provider/freeaichat.py +64 -55
- webscout/Provider/monochat.py +275 -0
- webscout/Provider/scira_chat.py +115 -21
- webscout/Provider/toolbaz.py +5 -10
- webscout/Provider/typefully.py +1 -11
- webscout/Provider/x0gpt.py +325 -315
- webscout/__init__.py +4 -11
- webscout/auth/__init__.py +19 -4
- webscout/auth/api_key_manager.py +189 -189
- webscout/auth/auth_system.py +25 -40
- webscout/auth/config.py +105 -6
- webscout/auth/database.py +377 -22
- webscout/auth/models.py +185 -130
- webscout/auth/request_processing.py +175 -11
- webscout/auth/routes.py +119 -5
- webscout/auth/server.py +9 -2
- webscout/auth/simple_logger.py +236 -0
- webscout/sanitize.py +1074 -0
- webscout/version.py +1 -1
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/METADATA +9 -150
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/RECORD +70 -72
- webscout/Provider/AI21.py +0 -177
- webscout/Provider/HuggingFaceChat.py +0 -469
- webscout/Provider/OPENAI/README_AUTOPROXY.md +0 -238
- webscout/Provider/OPENAI/freeaichat.py +0 -363
- webscout/Provider/OPENAI/typegpt.py +0 -368
- webscout/Provider/OPENAI/uncovrAI.py +0 -477
- webscout/Provider/WritingMate.py +0 -273
- webscout/Provider/typegpt.py +0 -284
- webscout/Provider/uncovr.py +0 -333
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/WHEEL +0 -0
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/entry_points.txt +0 -0
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/licenses/LICENSE.md +0 -0
- {webscout-8.3.3.dist-info → webscout-8.3.5.dist-info}/top_level.txt +0 -0
webscout/__init__.py
CHANGED
|
@@ -17,12 +17,9 @@ from .litagent import LitAgent
|
|
|
17
17
|
from .scout import *
|
|
18
18
|
from .zeroart import *
|
|
19
19
|
from .yep_search import *
|
|
20
|
-
|
|
21
|
-
# from .litprinter import lit, litprint, ic, install, uninstall
|
|
22
|
-
agent = LitAgent()
|
|
23
|
-
|
|
24
|
-
__repo__ = "https://github.com/OE-LUCIFER/Webscout"
|
|
20
|
+
from .AIutel import *
|
|
25
21
|
|
|
22
|
+
useragent = LitAgent()
|
|
26
23
|
# Add update checker
|
|
27
24
|
from .update_checker import check_for_updates
|
|
28
25
|
try:
|
|
@@ -30,10 +27,6 @@ try:
|
|
|
30
27
|
if update_message:
|
|
31
28
|
print(update_message)
|
|
32
29
|
except Exception:
|
|
33
|
-
pass # Silently handle any update check
|
|
34
|
-
|
|
35
|
-
import logging
|
|
36
|
-
logging.getLogger("webscout").addHandler(logging.NullHandler())
|
|
37
|
-
|
|
30
|
+
pass # Silently handle any update check errors
|
|
38
31
|
# Import models for easy access
|
|
39
|
-
from .models import model
|
|
32
|
+
from .models import model
|
webscout/auth/__init__.py
CHANGED
|
@@ -26,9 +26,24 @@ def start_server(*args, **kwargs):
|
|
|
26
26
|
from .server import start_server as _start_server
|
|
27
27
|
return _start_server(*args, **kwargs)
|
|
28
28
|
from .routes import Api
|
|
29
|
-
from .config import ServerConfig, AppConfig
|
|
30
29
|
from .exceptions import APIError
|
|
31
|
-
|
|
30
|
+
|
|
31
|
+
# Lazy imports for config classes to avoid initialization issues
|
|
32
|
+
def get_server_config():
|
|
33
|
+
from .config import ServerConfig
|
|
34
|
+
return ServerConfig
|
|
35
|
+
|
|
36
|
+
def get_app_config():
|
|
37
|
+
from .config import AppConfig
|
|
38
|
+
return AppConfig
|
|
39
|
+
|
|
40
|
+
def initialize_provider_map():
|
|
41
|
+
from .providers import initialize_provider_map as _init_provider_map
|
|
42
|
+
return _init_provider_map()
|
|
43
|
+
|
|
44
|
+
def initialize_tti_provider_map():
|
|
45
|
+
from .providers import initialize_tti_provider_map as _init_tti_provider_map
|
|
46
|
+
return _init_tti_provider_map()
|
|
32
47
|
|
|
33
48
|
__all__ = [
|
|
34
49
|
"User",
|
|
@@ -47,8 +62,8 @@ __all__ = [
|
|
|
47
62
|
"run_api",
|
|
48
63
|
"start_server",
|
|
49
64
|
"Api",
|
|
50
|
-
"
|
|
51
|
-
"
|
|
65
|
+
"get_server_config",
|
|
66
|
+
"get_app_config",
|
|
52
67
|
"APIError",
|
|
53
68
|
"initialize_provider_map",
|
|
54
69
|
"initialize_tti_provider_map"
|
webscout/auth/api_key_manager.py
CHANGED
|
@@ -1,189 +1,189 @@
|
|
|
1
|
-
# webscout/auth/api_key_manager.py
|
|
2
|
-
|
|
3
|
-
import secrets
|
|
4
|
-
import string
|
|
5
|
-
from datetime import datetime, timezone, timedelta
|
|
6
|
-
from typing import Optional, Tuple
|
|
7
|
-
import hashlib
|
|
8
|
-
import logging
|
|
9
|
-
|
|
10
|
-
from .models import User, APIKey
|
|
11
|
-
from .database import DatabaseManager
|
|
12
|
-
|
|
13
|
-
logger = logging.getLogger(__name__)
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
class APIKeyManager:
|
|
17
|
-
"""Manages API key generation, validation, and lifecycle."""
|
|
18
|
-
|
|
19
|
-
def __init__(self, database_manager: DatabaseManager):
|
|
20
|
-
self.db = database_manager
|
|
21
|
-
self.key_prefix = "ws_" # webscout prefix
|
|
22
|
-
self.key_length = 32 # Length of the random part
|
|
23
|
-
|
|
24
|
-
def generate_api_key(self) -> str:
|
|
25
|
-
"""Generate a secure API key."""
|
|
26
|
-
# Generate random string
|
|
27
|
-
alphabet = string.ascii_letters + string.digits
|
|
28
|
-
random_part = ''.join(secrets.choice(alphabet) for _ in range(self.key_length))
|
|
29
|
-
|
|
30
|
-
# Add prefix
|
|
31
|
-
api_key = f"{self.key_prefix}{random_part}"
|
|
32
|
-
|
|
33
|
-
return api_key
|
|
34
|
-
|
|
35
|
-
def hash_api_key(self, api_key: str) -> str:
|
|
36
|
-
"""Hash an API key for secure storage (optional, for extra security)."""
|
|
37
|
-
return hashlib.sha256(api_key.encode()).hexdigest()
|
|
38
|
-
|
|
39
|
-
async def create_api_key(
|
|
40
|
-
self,
|
|
41
|
-
username: str,
|
|
42
|
-
telegram_id: str,
|
|
43
|
-
name: Optional[str] = None,
|
|
44
|
-
rate_limit: int = 10,
|
|
45
|
-
expires_in_days: Optional[int] = None
|
|
46
|
-
) -> Tuple[APIKey, User]:
|
|
47
|
-
"""Create a new API key and associated user if needed. Only one API key per user allowed."""
|
|
48
|
-
|
|
49
|
-
# Check if user already exists by telegram_id
|
|
50
|
-
user = await self.db.get_user_by_telegram_id(telegram_id)
|
|
51
|
-
|
|
52
|
-
if user:
|
|
53
|
-
# Check if user already has an API key
|
|
54
|
-
existing_keys = await self.db.get_api_keys_by_user(user.id)
|
|
55
|
-
active_keys = [key for key in existing_keys if key.is_active and not key.is_expired()]
|
|
56
|
-
|
|
57
|
-
if active_keys:
|
|
58
|
-
raise ValueError(f"User with Telegram ID {telegram_id} already has an active API key. Only one API key per user is allowed.")
|
|
59
|
-
else:
|
|
60
|
-
# Check if username is already taken
|
|
61
|
-
existing_user = await self.db.get_user_by_username(username)
|
|
62
|
-
if existing_user:
|
|
63
|
-
raise ValueError(f"Username '{username}' is already taken")
|
|
64
|
-
|
|
65
|
-
# Create new user
|
|
66
|
-
user = User(
|
|
67
|
-
username=username,
|
|
68
|
-
telegram_id=telegram_id,
|
|
69
|
-
created_at=datetime.now(timezone.utc),
|
|
70
|
-
updated_at=datetime.now(timezone.utc)
|
|
71
|
-
)
|
|
72
|
-
try:
|
|
73
|
-
user = await self.db.create_user(user)
|
|
74
|
-
logger.info(f"Created new user: {user.username} (Telegram ID: {telegram_id})")
|
|
75
|
-
except ValueError as e:
|
|
76
|
-
# User might already exist, try to get it
|
|
77
|
-
if "already exists" in str(e):
|
|
78
|
-
user = await self.db.get_user_by_telegram_id(telegram_id)
|
|
79
|
-
if not user:
|
|
80
|
-
raise e
|
|
81
|
-
else:
|
|
82
|
-
raise e
|
|
83
|
-
|
|
84
|
-
# Generate API key
|
|
85
|
-
api_key_value = self.generate_api_key()
|
|
86
|
-
|
|
87
|
-
# Calculate expiration
|
|
88
|
-
expires_at = None
|
|
89
|
-
if expires_in_days:
|
|
90
|
-
expires_at = datetime.now(timezone.utc) + timedelta(days=expires_in_days)
|
|
91
|
-
|
|
92
|
-
# Create API key object
|
|
93
|
-
api_key = APIKey(
|
|
94
|
-
key=api_key_value,
|
|
95
|
-
user_id=user.id,
|
|
96
|
-
name=name,
|
|
97
|
-
created_at=datetime.now(timezone.utc),
|
|
98
|
-
expires_at=expires_at,
|
|
99
|
-
rate_limit=rate_limit,
|
|
100
|
-
is_active=True
|
|
101
|
-
)
|
|
102
|
-
|
|
103
|
-
# Store in database
|
|
104
|
-
try:
|
|
105
|
-
api_key = await self.db.create_api_key(api_key)
|
|
106
|
-
logger.info(f"Created API key for user {user.username}: {api_key.id}")
|
|
107
|
-
return api_key, user
|
|
108
|
-
except ValueError as e:
|
|
109
|
-
# Key collision (very unlikely), try again
|
|
110
|
-
if "already exists" in str(e):
|
|
111
|
-
logger.warning("API key collision detected, regenerating...")
|
|
112
|
-
return await self.create_api_key(username, telegram_id, name, rate_limit, expires_in_days)
|
|
113
|
-
raise e
|
|
114
|
-
|
|
115
|
-
async def validate_api_key(self, api_key: str) -> Tuple[bool, Optional[APIKey], Optional[str]]:
|
|
116
|
-
"""
|
|
117
|
-
Validate an API key.
|
|
118
|
-
|
|
119
|
-
Returns:
|
|
120
|
-
Tuple of (is_valid, api_key_object, error_message)
|
|
121
|
-
"""
|
|
122
|
-
if not api_key:
|
|
123
|
-
return False, None, "API key is required"
|
|
124
|
-
|
|
125
|
-
if not api_key.startswith(self.key_prefix):
|
|
126
|
-
return False, None, "Invalid API key format"
|
|
127
|
-
|
|
128
|
-
try:
|
|
129
|
-
# Get API key from database
|
|
130
|
-
key_obj = await self.db.get_api_key(api_key)
|
|
131
|
-
|
|
132
|
-
if not key_obj:
|
|
133
|
-
return False, None, "API key not found"
|
|
134
|
-
|
|
135
|
-
if not key_obj.is_active:
|
|
136
|
-
return False, None, "API key is inactive"
|
|
137
|
-
|
|
138
|
-
if key_obj.is_expired():
|
|
139
|
-
return False, None, "API key has expired"
|
|
140
|
-
|
|
141
|
-
# Update last used timestamp
|
|
142
|
-
key_obj.last_used_at = datetime.now(timezone.utc)
|
|
143
|
-
key_obj.usage_count += 1
|
|
144
|
-
|
|
145
|
-
try:
|
|
146
|
-
await self.db.update_api_key(key_obj)
|
|
147
|
-
except Exception as e:
|
|
148
|
-
logger.warning(f"Failed to update API key usage: {e}")
|
|
149
|
-
|
|
150
|
-
return True, key_obj, None
|
|
151
|
-
|
|
152
|
-
except Exception as e:
|
|
153
|
-
logger.error(f"Error validating API key: {e}")
|
|
154
|
-
return False, None, "Internal error during validation"
|
|
155
|
-
|
|
156
|
-
async def revoke_api_key(self, api_key: str) -> bool:
|
|
157
|
-
"""Revoke an API key by marking it as inactive."""
|
|
158
|
-
try:
|
|
159
|
-
key_obj = await self.db.get_api_key(api_key)
|
|
160
|
-
|
|
161
|
-
if not key_obj:
|
|
162
|
-
return False
|
|
163
|
-
|
|
164
|
-
key_obj.is_active = False
|
|
165
|
-
key_obj.updated_at = datetime.now(timezone.utc)
|
|
166
|
-
|
|
167
|
-
await self.db.update_api_key(key_obj)
|
|
168
|
-
logger.info(f"Revoked API key: {key_obj.id}")
|
|
169
|
-
return True
|
|
170
|
-
|
|
171
|
-
except Exception as e:
|
|
172
|
-
logger.error(f"Error revoking API key: {e}")
|
|
173
|
-
return False
|
|
174
|
-
|
|
175
|
-
async def get_user_api_keys(self, user_id: str) -> list[APIKey]:
|
|
176
|
-
"""Get all API keys for a user."""
|
|
177
|
-
try:
|
|
178
|
-
return await self.db.get_api_keys_by_user(user_id)
|
|
179
|
-
except Exception as e:
|
|
180
|
-
logger.error(f"Error getting user API keys: {e}")
|
|
181
|
-
return []
|
|
182
|
-
|
|
183
|
-
async def cleanup_expired_keys(self) -> int:
|
|
184
|
-
"""Clean up expired API keys (mark as inactive)."""
|
|
185
|
-
# This would require a method to get all API keys, which we haven't implemented
|
|
186
|
-
# For now, we'll just return 0
|
|
187
|
-
# In a production system, you'd want to implement this properly
|
|
188
|
-
logger.info("Cleanup expired keys called (not implemented)")
|
|
189
|
-
return 0
|
|
1
|
+
# webscout/auth/api_key_manager.py
|
|
2
|
+
|
|
3
|
+
import secrets
|
|
4
|
+
import string
|
|
5
|
+
from datetime import datetime, timezone, timedelta
|
|
6
|
+
from typing import Optional, Tuple
|
|
7
|
+
import hashlib
|
|
8
|
+
import logging
|
|
9
|
+
|
|
10
|
+
from .models import User, APIKey
|
|
11
|
+
from .database import DatabaseManager
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class APIKeyManager:
|
|
17
|
+
"""Manages API key generation, validation, and lifecycle."""
|
|
18
|
+
|
|
19
|
+
def __init__(self, database_manager: DatabaseManager):
|
|
20
|
+
self.db = database_manager
|
|
21
|
+
self.key_prefix = "ws_" # webscout prefix
|
|
22
|
+
self.key_length = 32 # Length of the random part
|
|
23
|
+
|
|
24
|
+
def generate_api_key(self) -> str:
|
|
25
|
+
"""Generate a secure API key."""
|
|
26
|
+
# Generate random string
|
|
27
|
+
alphabet = string.ascii_letters + string.digits
|
|
28
|
+
random_part = ''.join(secrets.choice(alphabet) for _ in range(self.key_length))
|
|
29
|
+
|
|
30
|
+
# Add prefix
|
|
31
|
+
api_key = f"{self.key_prefix}{random_part}"
|
|
32
|
+
|
|
33
|
+
return api_key
|
|
34
|
+
|
|
35
|
+
def hash_api_key(self, api_key: str) -> str:
|
|
36
|
+
"""Hash an API key for secure storage (optional, for extra security)."""
|
|
37
|
+
return hashlib.sha256(api_key.encode()).hexdigest()
|
|
38
|
+
|
|
39
|
+
async def create_api_key(
|
|
40
|
+
self,
|
|
41
|
+
username: str,
|
|
42
|
+
telegram_id: str,
|
|
43
|
+
name: Optional[str] = None,
|
|
44
|
+
rate_limit: int = 10,
|
|
45
|
+
expires_in_days: Optional[int] = None
|
|
46
|
+
) -> Tuple[APIKey, User]:
|
|
47
|
+
"""Create a new API key and associated user if needed. Only one API key per user allowed."""
|
|
48
|
+
|
|
49
|
+
# Check if user already exists by telegram_id
|
|
50
|
+
user = await self.db.get_user_by_telegram_id(telegram_id)
|
|
51
|
+
|
|
52
|
+
if user:
|
|
53
|
+
# Check if user already has an API key
|
|
54
|
+
existing_keys = await self.db.get_api_keys_by_user(user.id)
|
|
55
|
+
active_keys = [key for key in existing_keys if key.is_active and not key.is_expired()]
|
|
56
|
+
|
|
57
|
+
if active_keys:
|
|
58
|
+
raise ValueError(f"User with Telegram ID {telegram_id} already has an active API key. Only one API key per user is allowed.")
|
|
59
|
+
else:
|
|
60
|
+
# Check if username is already taken
|
|
61
|
+
existing_user = await self.db.get_user_by_username(username)
|
|
62
|
+
if existing_user:
|
|
63
|
+
raise ValueError(f"Username '{username}' is already taken")
|
|
64
|
+
|
|
65
|
+
# Create new user
|
|
66
|
+
user = User(
|
|
67
|
+
username=username,
|
|
68
|
+
telegram_id=telegram_id,
|
|
69
|
+
created_at=datetime.now(timezone.utc),
|
|
70
|
+
updated_at=datetime.now(timezone.utc)
|
|
71
|
+
)
|
|
72
|
+
try:
|
|
73
|
+
user = await self.db.create_user(user)
|
|
74
|
+
logger.info(f"Created new user: {user.username} (Telegram ID: {telegram_id})")
|
|
75
|
+
except ValueError as e:
|
|
76
|
+
# User might already exist, try to get it
|
|
77
|
+
if "already exists" in str(e):
|
|
78
|
+
user = await self.db.get_user_by_telegram_id(telegram_id)
|
|
79
|
+
if not user:
|
|
80
|
+
raise e
|
|
81
|
+
else:
|
|
82
|
+
raise e
|
|
83
|
+
|
|
84
|
+
# Generate API key
|
|
85
|
+
api_key_value = self.generate_api_key()
|
|
86
|
+
|
|
87
|
+
# Calculate expiration
|
|
88
|
+
expires_at = None
|
|
89
|
+
if expires_in_days:
|
|
90
|
+
expires_at = datetime.now(timezone.utc) + timedelta(days=expires_in_days)
|
|
91
|
+
|
|
92
|
+
# Create API key object
|
|
93
|
+
api_key = APIKey(
|
|
94
|
+
key=api_key_value,
|
|
95
|
+
user_id=user.id,
|
|
96
|
+
name=name,
|
|
97
|
+
created_at=datetime.now(timezone.utc),
|
|
98
|
+
expires_at=expires_at,
|
|
99
|
+
rate_limit=rate_limit,
|
|
100
|
+
is_active=True
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
# Store in database
|
|
104
|
+
try:
|
|
105
|
+
api_key = await self.db.create_api_key(api_key)
|
|
106
|
+
logger.info(f"Created API key for user {user.username}: {api_key.id}")
|
|
107
|
+
return api_key, user
|
|
108
|
+
except ValueError as e:
|
|
109
|
+
# Key collision (very unlikely), try again
|
|
110
|
+
if "already exists" in str(e):
|
|
111
|
+
logger.warning("API key collision detected, regenerating...")
|
|
112
|
+
return await self.create_api_key(username, telegram_id, name, rate_limit, expires_in_days)
|
|
113
|
+
raise e
|
|
114
|
+
|
|
115
|
+
async def validate_api_key(self, api_key: str) -> Tuple[bool, Optional[APIKey], Optional[str]]:
|
|
116
|
+
"""
|
|
117
|
+
Validate an API key.
|
|
118
|
+
|
|
119
|
+
Returns:
|
|
120
|
+
Tuple of (is_valid, api_key_object, error_message)
|
|
121
|
+
"""
|
|
122
|
+
if not api_key:
|
|
123
|
+
return False, None, "API key is required"
|
|
124
|
+
|
|
125
|
+
if not api_key.startswith(self.key_prefix):
|
|
126
|
+
return False, None, "Invalid API key format"
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
# Get API key from database
|
|
130
|
+
key_obj = await self.db.get_api_key(api_key)
|
|
131
|
+
|
|
132
|
+
if not key_obj:
|
|
133
|
+
return False, None, "API key not found"
|
|
134
|
+
|
|
135
|
+
if not key_obj.is_active:
|
|
136
|
+
return False, None, "API key is inactive"
|
|
137
|
+
|
|
138
|
+
if key_obj.is_expired():
|
|
139
|
+
return False, None, "API key has expired"
|
|
140
|
+
|
|
141
|
+
# Update last used timestamp
|
|
142
|
+
key_obj.last_used_at = datetime.now(timezone.utc)
|
|
143
|
+
key_obj.usage_count += 1
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
await self.db.update_api_key(key_obj)
|
|
147
|
+
except Exception as e:
|
|
148
|
+
logger.warning(f"Failed to update API key usage: {e}")
|
|
149
|
+
|
|
150
|
+
return True, key_obj, None
|
|
151
|
+
|
|
152
|
+
except Exception as e:
|
|
153
|
+
logger.error(f"Error validating API key: {e}")
|
|
154
|
+
return False, None, "Internal error during validation"
|
|
155
|
+
|
|
156
|
+
async def revoke_api_key(self, api_key: str) -> bool:
|
|
157
|
+
"""Revoke an API key by marking it as inactive."""
|
|
158
|
+
try:
|
|
159
|
+
key_obj = await self.db.get_api_key(api_key)
|
|
160
|
+
|
|
161
|
+
if not key_obj:
|
|
162
|
+
return False
|
|
163
|
+
|
|
164
|
+
key_obj.is_active = False
|
|
165
|
+
key_obj.updated_at = datetime.now(timezone.utc)
|
|
166
|
+
|
|
167
|
+
await self.db.update_api_key(key_obj)
|
|
168
|
+
logger.info(f"Revoked API key: {key_obj.id}")
|
|
169
|
+
return True
|
|
170
|
+
|
|
171
|
+
except Exception as e:
|
|
172
|
+
logger.error(f"Error revoking API key: {e}")
|
|
173
|
+
return False
|
|
174
|
+
|
|
175
|
+
async def get_user_api_keys(self, user_id: str) -> list[APIKey]:
|
|
176
|
+
"""Get all API keys for a user."""
|
|
177
|
+
try:
|
|
178
|
+
return await self.db.get_api_keys_by_user(user_id)
|
|
179
|
+
except Exception as e:
|
|
180
|
+
logger.error(f"Error getting user API keys: {e}")
|
|
181
|
+
return []
|
|
182
|
+
|
|
183
|
+
async def cleanup_expired_keys(self) -> int:
|
|
184
|
+
"""Clean up expired API keys (mark as inactive)."""
|
|
185
|
+
# This would require a method to get all API keys, which we haven't implemented
|
|
186
|
+
# For now, we'll just return 0
|
|
187
|
+
# In a production system, you'd want to implement this properly
|
|
188
|
+
logger.info("Cleanup expired keys called (not implemented)")
|
|
189
|
+
return 0
|
webscout/auth/auth_system.py
CHANGED
|
@@ -32,43 +32,41 @@ def initialize_auth_system(app: FastAPI, auth_required: bool = True, rate_limit_
|
|
|
32
32
|
"""Initialize the authentication system."""
|
|
33
33
|
global db_manager, api_key_manager, rate_limiter, auth_middleware
|
|
34
34
|
|
|
35
|
-
if not auth_required:
|
|
36
|
-
logger.info("Auth system is disabled (no-auth mode): skipping DB and API key manager initialization.")
|
|
37
|
-
db_manager = None
|
|
38
|
-
api_key_manager = None
|
|
39
|
-
rate_limiter = None
|
|
40
|
-
auth_middleware = None
|
|
41
|
-
return
|
|
42
|
-
|
|
43
35
|
try:
|
|
44
|
-
# Initialize database manager
|
|
36
|
+
# Initialize database manager (always needed for request logging)
|
|
45
37
|
mongo_url = os.getenv("MONGODB_URL")
|
|
46
38
|
data_dir = os.getenv("WEBSCOUT_DATA_DIR", "data")
|
|
47
39
|
|
|
48
40
|
db_manager = DatabaseManager(mongo_url, data_dir)
|
|
49
41
|
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
42
|
+
if not auth_required:
|
|
43
|
+
logger.info("Auth system is disabled (no-auth mode): initializing only database for request logging.")
|
|
44
|
+
api_key_manager = None
|
|
45
|
+
rate_limiter = None
|
|
46
|
+
auth_middleware = None
|
|
47
|
+
else:
|
|
48
|
+
# Initialize API key manager
|
|
49
|
+
api_key_manager = APIKeyManager(db_manager)
|
|
50
|
+
|
|
51
|
+
# Initialize rate limiter
|
|
52
|
+
rate_limiter = RateLimiter(db_manager)
|
|
53
|
+
|
|
54
|
+
# Initialize auth middleware with configuration
|
|
55
|
+
auth_middleware = AuthMiddleware(
|
|
56
|
+
api_key_manager,
|
|
57
|
+
rate_limiter,
|
|
58
|
+
auth_required=auth_required,
|
|
59
|
+
rate_limit_enabled=rate_limit_enabled
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
# Add auth middleware to app
|
|
63
|
+
app.middleware("http")(auth_middleware)
|
|
66
64
|
|
|
67
65
|
# Add startup event to initialize database
|
|
68
66
|
async def startup_event():
|
|
69
67
|
if db_manager:
|
|
70
68
|
await db_manager.initialize()
|
|
71
|
-
logger.info("
|
|
69
|
+
logger.info("Database system initialized successfully")
|
|
72
70
|
logger.info(f"Auth required: {auth_required}, Rate limiting: {rate_limit_enabled}")
|
|
73
71
|
|
|
74
72
|
# Store startup function for later use
|
|
@@ -84,17 +82,4 @@ def initialize_auth_system(app: FastAPI, auth_required: bool = True, rate_limit_
|
|
|
84
82
|
|
|
85
83
|
def get_auth_components():
|
|
86
84
|
"""Get the initialized authentication components."""
|
|
87
|
-
|
|
88
|
-
return {
|
|
89
|
-
"db_manager": None,
|
|
90
|
-
"api_key_manager": None,
|
|
91
|
-
"rate_limiter": None,
|
|
92
|
-
"auth_middleware": None
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
return {
|
|
96
|
-
"db_manager": db_manager,
|
|
97
|
-
"api_key_manager": api_key_manager,
|
|
98
|
-
"rate_limiter": rate_limiter,
|
|
99
|
-
"auth_middleware": auth_middleware
|
|
100
|
-
}
|
|
85
|
+
return api_key_manager, db_manager, rate_limiter
|