Spaces:
Build error
Build error
File size: 12,469 Bytes
a85cab8 c6ce1a6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
"""
Authentication Manager Module for NAVADA
Handles user authentication, session management, and conversation storage.
"""
import hashlib
import secrets
import sqlite3
import json
from datetime import datetime, timedelta
from typing import Dict, Any, Optional, List
import logging
logger = logging.getLogger(__name__)
class AuthManager:
"""Simple authentication manager with SQLite backend."""
def __init__(self, db_path: str = "navada_auth.db"):
self.db_path = db_path
self.init_database()
def init_database(self):
"""Initialize database tables."""
try:
# Use timeout to prevent hanging
with sqlite3.connect(self.db_path, timeout=5.0) as conn:
cursor = conn.cursor()
# Set pragmas for better performance
cursor.execute("PRAGMA journal_mode=WAL")
cursor.execute("PRAGMA synchronous=NORMAL")
# Users table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
user_id TEXT PRIMARY KEY,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE,
password_hash TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Sessions table
cursor.execute('''
CREATE TABLE IF NOT EXISTS sessions (
session_token TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
expires_at TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
# Conversations table
cursor.execute('''
CREATE TABLE IF NOT EXISTS conversations (
conversation_id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
thread_id TEXT,
mode TEXT,
messages TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
# User actions log table
cursor.execute('''
CREATE TABLE IF NOT EXISTS user_actions (
action_id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
action_type TEXT,
details TEXT,
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(user_id)
)
''')
conn.commit()
logger.info("Database tables initialized successfully")
except sqlite3.OperationalError as e:
if "database is locked" in str(e):
logger.error("Database is locked - another process may be using it")
else:
logger.error(f"Database operational error: {e}")
except Exception as e:
logger.error(f"Database initialization error: {e}")
def hash_password(self, password: str) -> str:
"""Hash a password using SHA256."""
return hashlib.sha256(password.encode()).hexdigest()
def generate_token(self) -> str:
"""Generate a secure random token."""
return secrets.token_urlsafe(32)
def register_user(self, username: str, password: str, email: Optional[str] = None) -> Dict[str, Any]:
"""Register a new user."""
try:
with sqlite3.connect(self.db_path, timeout=5.0) as conn:
cursor = conn.cursor()
# Check if user exists
cursor.execute("SELECT username FROM users WHERE username = ?", (username,))
if cursor.fetchone():
return {"success": False, "message": "Username already exists"}
# Create user
user_id = secrets.token_urlsafe(16)
password_hash = self.hash_password(password)
cursor.execute('''
INSERT INTO users (user_id, username, email, password_hash)
VALUES (?, ?, ?, ?)
''', (user_id, username, email, password_hash))
conn.commit()
return {
"success": True,
"message": "User registered successfully",
"user_id": user_id
}
except Exception as e:
logger.error(f"Registration error: {e}")
return {"success": False, "message": str(e)}
def authenticate_user(self, username: str, password: str) -> Dict[str, Any]:
"""Authenticate a user and create a session."""
try:
with sqlite3.connect(self.db_path, timeout=5.0) as conn:
cursor = conn.cursor()
# Get user
password_hash = self.hash_password(password)
cursor.execute('''
SELECT user_id, username FROM users
WHERE username = ? AND password_hash = ?
''', (username, password_hash))
user = cursor.fetchone()
if not user:
return {"success": False, "message": "Invalid credentials"}
user_id, username = user
# Create session
session_token = self.generate_token()
auth_token = self.generate_token()
expires_at = datetime.now() + timedelta(hours=24)
cursor.execute('''
INSERT INTO sessions (session_token, user_id, expires_at)
VALUES (?, ?, ?)
''', (session_token, user_id, expires_at))
conn.commit()
return {
"success": True,
"message": "Login successful",
"user_id": user_id,
"username": username,
"session_token": session_token,
"auth_token": auth_token
}
except Exception as e:
logger.error(f"Authentication error: {e}")
return {"success": False, "message": str(e)}
def validate_session(self, session_token: str) -> Dict[str, Any]:
"""Validate a session token."""
try:
with sqlite3.connect(self.db_path, timeout=5.0) as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT s.user_id, s.expires_at, u.username
FROM sessions s
JOIN users u ON s.user_id = u.user_id
WHERE s.session_token = ?
''', (session_token,))
session = cursor.fetchone()
if not session:
return {"valid": False, "message": "Invalid session"}
user_id, expires_at, username = session
# Check expiration
if datetime.fromisoformat(expires_at) < datetime.now():
return {"valid": False, "message": "Session expired"}
return {
"valid": True,
"user_id": user_id,
"username": username
}
except Exception as e:
logger.error(f"Session validation error: {e}")
return {"valid": False, "message": str(e)}
def logout_user(self, session_token: str) -> Dict[str, Any]:
"""Logout user by removing session."""
try:
with sqlite3.connect(self.db_path, timeout=5.0) as conn:
cursor = conn.cursor()
cursor.execute("DELETE FROM sessions WHERE session_token = ?", (session_token,))
conn.commit()
return {"success": True, "message": "Logged out successfully"}
except Exception as e:
logger.error(f"Logout error: {e}")
return {"success": False, "message": str(e)}
def save_full_conversation(self, user_id: str, thread_id: str, mode: str, messages: List[Dict]) -> Dict[str, Any]:
"""Save a conversation to database."""
try:
with sqlite3.connect(self.db_path, timeout=5.0) as conn:
cursor = conn.cursor()
conversation_id = secrets.token_urlsafe(16)
messages_json = json.dumps(messages)
cursor.execute('''
INSERT INTO conversations (conversation_id, user_id, thread_id, mode, messages)
VALUES (?, ?, ?, ?, ?)
''', (conversation_id, user_id, thread_id, mode, messages_json))
conn.commit()
return {"success": True, "conversation_id": conversation_id}
except Exception as e:
logger.error(f"Save conversation error: {e}")
return {"success": False, "message": str(e)}
def get_user_conversations(self, user_id: str, limit: int = 10) -> List[Dict[str, Any]]:
"""Get user's recent conversations."""
try:
with sqlite3.connect(self.db_path, timeout=5.0) as conn:
cursor = conn.cursor()
cursor.execute('''
SELECT conversation_id, thread_id, mode, messages, created_at
FROM conversations
WHERE user_id = ?
ORDER BY created_at DESC
LIMIT ?
''', (user_id, limit))
conversations = []
for row in cursor.fetchall():
conv_id, thread_id, mode, messages_json, created_at = row
conversations.append({
"conversation_id": conv_id,
"thread_id": thread_id,
"mode": mode,
"messages": json.loads(messages_json) if messages_json else [],
"created_at": created_at
})
return conversations
except Exception as e:
logger.error(f"Get conversations error: {e}")
return []
def log_user_action(self, user_id: str, action_type: str, details: Optional[Dict] = None) -> Dict[str, Any]:
"""Log a user action."""
try:
with sqlite3.connect(self.db_path, timeout=5.0) as conn:
cursor = conn.cursor()
details_json = json.dumps(details) if details else None
cursor.execute('''
INSERT INTO user_actions (user_id, action_type, details)
VALUES (?, ?, ?)
''', (user_id, action_type, details_json))
conn.commit()
return {"success": True}
except Exception as e:
logger.error(f"Log action error: {e}")
return {"success": False, "message": str(e)}
def save_conversation(self, user_id: str, chainlit_session_id: str, role: str, content: str, persona_mode: str = None, metadata: Optional[Dict] = None) -> Dict[str, Any]:
"""Save individual conversation messages with chainlit session tracking."""
try:
# Use log_user_action for individual message logging
details = {
"chainlit_session_id": chainlit_session_id,
"role": role,
"content": content,
"persona_mode": persona_mode,
"metadata": metadata or {}
}
return self.log_user_action(
user_id=user_id,
action_type=f"message_{role}",
details=details
)
except Exception as e:
logger.error(f"Save conversation message error: {e}")
return {"success": False, "message": str(e)}
# Create singleton instance
auth_manager = AuthManager() |