File size: 5,556 Bytes
a54fd97 | 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 | """
User storage for SimpleMem MCP Server
Uses SQLite for user metadata persistence
"""
import sqlite3
import os
from datetime import datetime
from typing import Optional, List
from contextlib import contextmanager
from ..auth.models import User
class UserStore:
"""SQLite-based user storage"""
def __init__(self, db_path: str = "./data/users.db"):
self.db_path = db_path
os.makedirs(os.path.dirname(db_path), exist_ok=True)
self._init_db()
def _init_db(self):
"""Initialize database schema"""
with self._get_connection() as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS users (
user_id TEXT PRIMARY KEY,
openrouter_api_key_encrypted TEXT NOT NULL,
table_name TEXT NOT NULL UNIQUE,
created_at TEXT NOT NULL,
last_active TEXT NOT NULL
)
""")
conn.execute("""
CREATE INDEX IF NOT EXISTS idx_users_table_name
ON users(table_name)
""")
conn.commit()
@contextmanager
def _get_connection(self):
"""Get a database connection with context manager"""
conn = sqlite3.connect(self.db_path)
conn.row_factory = sqlite3.Row
try:
yield conn
finally:
conn.close()
def create_user(self, user: User) -> User:
"""Create a new user"""
with self._get_connection() as conn:
conn.execute(
"""
INSERT INTO users (user_id, openrouter_api_key_encrypted, table_name, created_at, last_active)
VALUES (?, ?, ?, ?, ?)
""",
(
user.user_id,
user.openrouter_api_key_encrypted,
user.table_name,
user.created_at.isoformat(),
user.last_active.isoformat(),
),
)
conn.commit()
return user
def get_user(self, user_id: str) -> Optional[User]:
"""Get user by ID"""
with self._get_connection() as conn:
row = conn.execute(
"SELECT * FROM users WHERE user_id = ?",
(user_id,),
).fetchone()
if row:
return User(
user_id=row["user_id"],
openrouter_api_key_encrypted=row["openrouter_api_key_encrypted"],
table_name=row["table_name"],
created_at=datetime.fromisoformat(row["created_at"]),
last_active=datetime.fromisoformat(row["last_active"]),
)
return None
def get_user_by_table(self, table_name: str) -> Optional[User]:
"""Get user by table name"""
with self._get_connection() as conn:
row = conn.execute(
"SELECT * FROM users WHERE table_name = ?",
(table_name,),
).fetchone()
if row:
return User(
user_id=row["user_id"],
openrouter_api_key_encrypted=row["openrouter_api_key_encrypted"],
table_name=row["table_name"],
created_at=datetime.fromisoformat(row["created_at"]),
last_active=datetime.fromisoformat(row["last_active"]),
)
return None
def update_last_active(self, user_id: str):
"""Update user's last active timestamp"""
with self._get_connection() as conn:
conn.execute(
"UPDATE users SET last_active = ? WHERE user_id = ?",
(datetime.utcnow().isoformat(), user_id),
)
conn.commit()
def update_api_key(self, user_id: str, encrypted_api_key: str):
"""Update user's encrypted API key"""
with self._get_connection() as conn:
conn.execute(
"UPDATE users SET openrouter_api_key_encrypted = ?, last_active = ? WHERE user_id = ?",
(encrypted_api_key, datetime.utcnow().isoformat(), user_id),
)
conn.commit()
def delete_user(self, user_id: str) -> bool:
"""Delete a user"""
with self._get_connection() as conn:
cursor = conn.execute(
"DELETE FROM users WHERE user_id = ?",
(user_id,),
)
conn.commit()
return cursor.rowcount > 0
def list_users(self, limit: int = 100, offset: int = 0) -> List[User]:
"""List all users with pagination"""
with self._get_connection() as conn:
rows = conn.execute(
"SELECT * FROM users ORDER BY created_at DESC LIMIT ? OFFSET ?",
(limit, offset),
).fetchall()
return [
User(
user_id=row["user_id"],
openrouter_api_key_encrypted=row["openrouter_api_key_encrypted"],
table_name=row["table_name"],
created_at=datetime.fromisoformat(row["created_at"]),
last_active=datetime.fromisoformat(row["last_active"]),
)
for row in rows
]
def count_users(self) -> int:
"""Get total user count"""
with self._get_connection() as conn:
row = conn.execute("SELECT COUNT(*) as count FROM users").fetchone()
return row["count"]
|