quantumflow-sdk 0.1.0__tar.gz

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.
Files changed (66) hide show
  1. quantumflow_sdk-0.1.0/PKG-INFO +190 -0
  2. quantumflow_sdk-0.1.0/README.md +143 -0
  3. quantumflow_sdk-0.1.0/pyproject.toml +89 -0
  4. quantumflow_sdk-0.1.0/setup.cfg +4 -0
  5. quantumflow_sdk-0.1.0/src/api/__init__.py +1 -0
  6. quantumflow_sdk-0.1.0/src/api/auth.py +208 -0
  7. quantumflow_sdk-0.1.0/src/api/main.py +403 -0
  8. quantumflow_sdk-0.1.0/src/api/models.py +137 -0
  9. quantumflow_sdk-0.1.0/src/api/routes/__init__.py +1 -0
  10. quantumflow_sdk-0.1.0/src/api/routes/auth_routes.py +234 -0
  11. quantumflow_sdk-0.1.0/src/api/routes/teleport_routes.py +415 -0
  12. quantumflow_sdk-0.1.0/src/db/__init__.py +15 -0
  13. quantumflow_sdk-0.1.0/src/db/crud.py +319 -0
  14. quantumflow_sdk-0.1.0/src/db/database.py +93 -0
  15. quantumflow_sdk-0.1.0/src/db/models.py +197 -0
  16. quantumflow_sdk-0.1.0/src/quantumflow/__init__.py +47 -0
  17. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/__init__.py +48 -0
  18. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/compression/__init__.py +7 -0
  19. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/compression/amplitude_amplification.py +189 -0
  20. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/compression/qft_compression.py +133 -0
  21. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/compression/token_compression.py +261 -0
  22. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/cryptography/__init__.py +6 -0
  23. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/cryptography/qkd.py +205 -0
  24. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/cryptography/qrng.py +231 -0
  25. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/machine_learning/__init__.py +7 -0
  26. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/machine_learning/qnn.py +276 -0
  27. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/machine_learning/qsvm.py +249 -0
  28. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/machine_learning/vqe.py +229 -0
  29. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/optimization/__init__.py +7 -0
  30. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/optimization/grover.py +223 -0
  31. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/optimization/qaoa.py +251 -0
  32. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/optimization/quantum_annealing.py +237 -0
  33. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/utility/__init__.py +6 -0
  34. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/utility/circuit_optimizer.py +194 -0
  35. quantumflow_sdk-0.1.0/src/quantumflow/algorithms/utility/error_correction.py +330 -0
  36. quantumflow_sdk-0.1.0/src/quantumflow/api/__init__.py +1 -0
  37. quantumflow_sdk-0.1.0/src/quantumflow/api/routes/__init__.py +4 -0
  38. quantumflow_sdk-0.1.0/src/quantumflow/api/routes/billing_routes.py +520 -0
  39. quantumflow_sdk-0.1.0/src/quantumflow/backends/__init__.py +33 -0
  40. quantumflow_sdk-0.1.0/src/quantumflow/backends/base_backend.py +184 -0
  41. quantumflow_sdk-0.1.0/src/quantumflow/backends/braket_backend.py +345 -0
  42. quantumflow_sdk-0.1.0/src/quantumflow/backends/ibm_backend.py +112 -0
  43. quantumflow_sdk-0.1.0/src/quantumflow/backends/simulator_backend.py +86 -0
  44. quantumflow_sdk-0.1.0/src/quantumflow/billing/__init__.py +25 -0
  45. quantumflow_sdk-0.1.0/src/quantumflow/billing/models.py +126 -0
  46. quantumflow_sdk-0.1.0/src/quantumflow/billing/stripe_service.py +619 -0
  47. quantumflow_sdk-0.1.0/src/quantumflow/core/__init__.py +12 -0
  48. quantumflow_sdk-0.1.0/src/quantumflow/core/entanglement.py +164 -0
  49. quantumflow_sdk-0.1.0/src/quantumflow/core/memory.py +147 -0
  50. quantumflow_sdk-0.1.0/src/quantumflow/core/quantum_backprop.py +394 -0
  51. quantumflow_sdk-0.1.0/src/quantumflow/core/quantum_compressor.py +309 -0
  52. quantumflow_sdk-0.1.0/src/quantumflow/core/teleportation.py +386 -0
  53. quantumflow_sdk-0.1.0/src/quantumflow/integrations/__init__.py +107 -0
  54. quantumflow_sdk-0.1.0/src/quantumflow/integrations/autogen_tools.py +501 -0
  55. quantumflow_sdk-0.1.0/src/quantumflow/integrations/crewai_agents.py +425 -0
  56. quantumflow_sdk-0.1.0/src/quantumflow/integrations/crewai_tools.py +407 -0
  57. quantumflow_sdk-0.1.0/src/quantumflow/integrations/langchain_memory.py +385 -0
  58. quantumflow_sdk-0.1.0/src/quantumflow/integrations/langchain_tools.py +366 -0
  59. quantumflow_sdk-0.1.0/src/quantumflow/integrations/mcp_server.py +575 -0
  60. quantumflow_sdk-0.1.0/src/quantumflow_sdk.egg-info/PKG-INFO +190 -0
  61. quantumflow_sdk-0.1.0/src/quantumflow_sdk.egg-info/SOURCES.txt +64 -0
  62. quantumflow_sdk-0.1.0/src/quantumflow_sdk.egg-info/dependency_links.txt +1 -0
  63. quantumflow_sdk-0.1.0/src/quantumflow_sdk.egg-info/entry_points.txt +2 -0
  64. quantumflow_sdk-0.1.0/src/quantumflow_sdk.egg-info/requires.txt +28 -0
  65. quantumflow_sdk-0.1.0/src/quantumflow_sdk.egg-info/top_level.txt +3 -0
  66. quantumflow_sdk-0.1.0/tests/test_quantum_compressor.py +109 -0
@@ -0,0 +1,190 @@
1
+ Metadata-Version: 2.4
2
+ Name: quantumflow-sdk
3
+ Version: 0.1.0
4
+ Summary: Quantum-optimized AI agent workflow platform with 53% token compression
5
+ Author-email: BlockQuantAI <hello@blockquant.ai>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://qflowai.dev
8
+ Project-URL: Documentation, https://qflowai.dev/docs
9
+ Project-URL: Repository, https://github.com/blockquantai/quantumflow
10
+ Project-URL: Issues, https://github.com/blockquantai/quantumflow/issues
11
+ Keywords: quantum,quantum-computing,ai,machine-learning,token-compression,qkd,teleportation,langchain,crewai
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Classifier: Topic :: Scientific/Engineering :: Physics
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ Requires-Dist: numpy>=1.21.0
26
+ Requires-Dist: scipy>=1.7.0
27
+ Provides-Extra: ibm
28
+ Requires-Dist: qiskit>=0.45.0; extra == "ibm"
29
+ Requires-Dist: qiskit-ibm-runtime>=0.15.0; extra == "ibm"
30
+ Provides-Extra: aws
31
+ Requires-Dist: amazon-braket-sdk>=1.50.0; extra == "aws"
32
+ Provides-Extra: langchain
33
+ Requires-Dist: langchain>=0.1.0; extra == "langchain"
34
+ Provides-Extra: crewai
35
+ Requires-Dist: crewai>=0.1.0; extra == "crewai"
36
+ Provides-Extra: all
37
+ Requires-Dist: qiskit>=0.45.0; extra == "all"
38
+ Requires-Dist: qiskit-ibm-runtime>=0.15.0; extra == "all"
39
+ Requires-Dist: amazon-braket-sdk>=1.50.0; extra == "all"
40
+ Requires-Dist: langchain>=0.1.0; extra == "all"
41
+ Requires-Dist: crewai>=0.1.0; extra == "all"
42
+ Provides-Extra: dev
43
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
44
+ Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
45
+ Requires-Dist: black>=23.0.0; extra == "dev"
46
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
47
+
48
+ # QuantumFlow SDK
49
+
50
+ Quantum-optimized AI agent workflow platform with 53% token compression, quantum teleportation, and BB84 QKD.
51
+
52
+ ## Installation
53
+
54
+ ```bash
55
+ pip install quantumflow-sdk
56
+ ```
57
+
58
+ With IBM Quantum support:
59
+ ```bash
60
+ pip install quantumflow-sdk[ibm]
61
+ ```
62
+
63
+ With all integrations:
64
+ ```bash
65
+ pip install quantumflow-sdk[all]
66
+ ```
67
+
68
+ ## Quick Start
69
+
70
+ ### Token Compression
71
+
72
+ ```python
73
+ from quantumflow import QuantumCompressor
74
+
75
+ compressor = QuantumCompressor(backend="simulator")
76
+ result = compressor.compress([100, 200, 150, 175, 225, 180, 160, 190])
77
+
78
+ print(f"Input tokens: {result.input_token_count}")
79
+ print(f"Output qubits: {result.n_qubits}")
80
+ print(f"Compression: {result.compression_percentage:.1f}%")
81
+ ```
82
+
83
+ ### Quantum Backpropagation
84
+
85
+ ```python
86
+ from quantumflow import QuantumBackprop
87
+
88
+ backprop = QuantumBackprop(backend="simulator")
89
+ result = backprop.compute_gradient(
90
+ input_state=[0.5, 0.5],
91
+ target_state=[0.8, 0.2],
92
+ weights=[0.3, 0.7],
93
+ )
94
+
95
+ print(f"Gradients: {result.gradients}")
96
+ print(f"Similarity: {result.similarity:.2%}")
97
+ ```
98
+
99
+ ### Quantum Key Distribution (QKD)
100
+
101
+ ```python
102
+ from quantumflow import QKDExchange
103
+
104
+ qkd = QKDExchange(backend="simulator")
105
+ result = qkd.exchange(key_length=256)
106
+
107
+ print(f"Shared key: {result['key'][:32]}...")
108
+ print(f"Error rate: {result['error_rate']:.2%}")
109
+ print(f"Secure: {result['secure']}")
110
+ ```
111
+
112
+ ### Quantum Teleportation
113
+
114
+ ```python
115
+ from quantumflow import QuantumTeleporter
116
+
117
+ teleporter = QuantumTeleporter(backend="simulator")
118
+
119
+ # Create Bell pairs
120
+ pairs = teleporter.create_bell_pairs(10)
121
+
122
+ # Teleport a quantum state
123
+ state = [0.707 + 0j, 0.707 + 0j] # |+> state
124
+ result = teleporter.teleport_state(state)
125
+
126
+ print(f"Fidelity: {result.fidelity:.4f}")
127
+ print(f"Corrections: {result.corrections_applied}")
128
+ ```
129
+
130
+ ### Secure Messaging
131
+
132
+ ```python
133
+ from quantumflow import SecureMessenger
134
+
135
+ messenger = SecureMessenger(backend="simulator")
136
+
137
+ # Establish secure channel
138
+ channel = messenger.establish_channel("bob@example.com")
139
+
140
+ # Send message via compressed teleportation + QKD
141
+ result = messenger.send_message("Hello, quantum world!")
142
+
143
+ print(f"Compression ratio: {result['compression_ratio']:.1f}x")
144
+ print(f"QKD secured: {result['qkd_secured']}")
145
+ ```
146
+
147
+ ## REST API
148
+
149
+ You can also use the hosted API at `https://api.qflowai.dev`:
150
+
151
+ ```bash
152
+ # Token compression
153
+ curl -X POST https://api.qflowai.dev/v1/compress \
154
+ -H "Content-Type: application/json" \
155
+ -d '{"tokens": [100, 200, 150, 175]}'
156
+
157
+ # QKD exchange
158
+ curl -X POST https://api.qflowai.dev/v1/quantum/qkd/exchange \
159
+ -H "Content-Type: application/json" \
160
+ -d '{"key_length": 256}'
161
+
162
+ # Secure message
163
+ curl -X POST https://api.qflowai.dev/v1/quantum/message \
164
+ -H "Content-Type: application/json" \
165
+ -d '{"message": "Hello quantum world!"}'
166
+ ```
167
+
168
+ ## Features
169
+
170
+ - **53% Token Compression**: Quantum amplitude encoding for exponential compression
171
+ - **Quantum Backpropagation**: 97.78% gradient similarity via teleportation protocol
172
+ - **BB84 QKD**: Unconditionally secure key exchange
173
+ - **Quantum Teleportation**: State transfer without physical qubit transmission
174
+ - **Secure Messaging**: Compressed teleportation + QKD encryption
175
+ - **Multi-Backend**: Simulator, IBM Quantum, AWS Braket
176
+
177
+ ## Framework Integrations
178
+
179
+ - LangChain
180
+ - CrewAI
181
+ - AutoGen
182
+ - Claude MCP
183
+
184
+ ## Documentation
185
+
186
+ Full documentation at [https://qflowai.dev/docs](https://qflowai.dev/docs)
187
+
188
+ ## License
189
+
190
+ MIT License - see LICENSE file for details.
@@ -0,0 +1,143 @@
1
+ # QuantumFlow SDK
2
+
3
+ Quantum-optimized AI agent workflow platform with 53% token compression, quantum teleportation, and BB84 QKD.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install quantumflow-sdk
9
+ ```
10
+
11
+ With IBM Quantum support:
12
+ ```bash
13
+ pip install quantumflow-sdk[ibm]
14
+ ```
15
+
16
+ With all integrations:
17
+ ```bash
18
+ pip install quantumflow-sdk[all]
19
+ ```
20
+
21
+ ## Quick Start
22
+
23
+ ### Token Compression
24
+
25
+ ```python
26
+ from quantumflow import QuantumCompressor
27
+
28
+ compressor = QuantumCompressor(backend="simulator")
29
+ result = compressor.compress([100, 200, 150, 175, 225, 180, 160, 190])
30
+
31
+ print(f"Input tokens: {result.input_token_count}")
32
+ print(f"Output qubits: {result.n_qubits}")
33
+ print(f"Compression: {result.compression_percentage:.1f}%")
34
+ ```
35
+
36
+ ### Quantum Backpropagation
37
+
38
+ ```python
39
+ from quantumflow import QuantumBackprop
40
+
41
+ backprop = QuantumBackprop(backend="simulator")
42
+ result = backprop.compute_gradient(
43
+ input_state=[0.5, 0.5],
44
+ target_state=[0.8, 0.2],
45
+ weights=[0.3, 0.7],
46
+ )
47
+
48
+ print(f"Gradients: {result.gradients}")
49
+ print(f"Similarity: {result.similarity:.2%}")
50
+ ```
51
+
52
+ ### Quantum Key Distribution (QKD)
53
+
54
+ ```python
55
+ from quantumflow import QKDExchange
56
+
57
+ qkd = QKDExchange(backend="simulator")
58
+ result = qkd.exchange(key_length=256)
59
+
60
+ print(f"Shared key: {result['key'][:32]}...")
61
+ print(f"Error rate: {result['error_rate']:.2%}")
62
+ print(f"Secure: {result['secure']}")
63
+ ```
64
+
65
+ ### Quantum Teleportation
66
+
67
+ ```python
68
+ from quantumflow import QuantumTeleporter
69
+
70
+ teleporter = QuantumTeleporter(backend="simulator")
71
+
72
+ # Create Bell pairs
73
+ pairs = teleporter.create_bell_pairs(10)
74
+
75
+ # Teleport a quantum state
76
+ state = [0.707 + 0j, 0.707 + 0j] # |+> state
77
+ result = teleporter.teleport_state(state)
78
+
79
+ print(f"Fidelity: {result.fidelity:.4f}")
80
+ print(f"Corrections: {result.corrections_applied}")
81
+ ```
82
+
83
+ ### Secure Messaging
84
+
85
+ ```python
86
+ from quantumflow import SecureMessenger
87
+
88
+ messenger = SecureMessenger(backend="simulator")
89
+
90
+ # Establish secure channel
91
+ channel = messenger.establish_channel("bob@example.com")
92
+
93
+ # Send message via compressed teleportation + QKD
94
+ result = messenger.send_message("Hello, quantum world!")
95
+
96
+ print(f"Compression ratio: {result['compression_ratio']:.1f}x")
97
+ print(f"QKD secured: {result['qkd_secured']}")
98
+ ```
99
+
100
+ ## REST API
101
+
102
+ You can also use the hosted API at `https://api.qflowai.dev`:
103
+
104
+ ```bash
105
+ # Token compression
106
+ curl -X POST https://api.qflowai.dev/v1/compress \
107
+ -H "Content-Type: application/json" \
108
+ -d '{"tokens": [100, 200, 150, 175]}'
109
+
110
+ # QKD exchange
111
+ curl -X POST https://api.qflowai.dev/v1/quantum/qkd/exchange \
112
+ -H "Content-Type: application/json" \
113
+ -d '{"key_length": 256}'
114
+
115
+ # Secure message
116
+ curl -X POST https://api.qflowai.dev/v1/quantum/message \
117
+ -H "Content-Type: application/json" \
118
+ -d '{"message": "Hello quantum world!"}'
119
+ ```
120
+
121
+ ## Features
122
+
123
+ - **53% Token Compression**: Quantum amplitude encoding for exponential compression
124
+ - **Quantum Backpropagation**: 97.78% gradient similarity via teleportation protocol
125
+ - **BB84 QKD**: Unconditionally secure key exchange
126
+ - **Quantum Teleportation**: State transfer without physical qubit transmission
127
+ - **Secure Messaging**: Compressed teleportation + QKD encryption
128
+ - **Multi-Backend**: Simulator, IBM Quantum, AWS Braket
129
+
130
+ ## Framework Integrations
131
+
132
+ - LangChain
133
+ - CrewAI
134
+ - AutoGen
135
+ - Claude MCP
136
+
137
+ ## Documentation
138
+
139
+ Full documentation at [https://qflowai.dev/docs](https://qflowai.dev/docs)
140
+
141
+ ## License
142
+
143
+ MIT License - see LICENSE file for details.
@@ -0,0 +1,89 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "quantumflow-sdk"
7
+ version = "0.1.0"
8
+ description = "Quantum-optimized AI agent workflow platform with 53% token compression"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ authors = [
12
+ {name = "BlockQuantAI", email = "hello@blockquant.ai"}
13
+ ]
14
+ keywords = [
15
+ "quantum",
16
+ "quantum-computing",
17
+ "ai",
18
+ "machine-learning",
19
+ "token-compression",
20
+ "qkd",
21
+ "teleportation",
22
+ "langchain",
23
+ "crewai",
24
+ ]
25
+ classifiers = [
26
+ "Development Status :: 4 - Beta",
27
+ "Intended Audience :: Developers",
28
+ "Intended Audience :: Science/Research",
29
+ "Operating System :: OS Independent",
30
+ "Programming Language :: Python :: 3",
31
+ "Programming Language :: Python :: 3.9",
32
+ "Programming Language :: Python :: 3.10",
33
+ "Programming Language :: Python :: 3.11",
34
+ "Programming Language :: Python :: 3.12",
35
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
36
+ "Topic :: Scientific/Engineering :: Physics",
37
+ ]
38
+ requires-python = ">=3.9"
39
+ dependencies = [
40
+ "numpy>=1.21.0",
41
+ "scipy>=1.7.0",
42
+ ]
43
+
44
+ [project.optional-dependencies]
45
+ ibm = ["qiskit>=0.45.0", "qiskit-ibm-runtime>=0.15.0"]
46
+ aws = ["amazon-braket-sdk>=1.50.0"]
47
+ langchain = ["langchain>=0.1.0"]
48
+ crewai = ["crewai>=0.1.0"]
49
+ all = [
50
+ "qiskit>=0.45.0",
51
+ "qiskit-ibm-runtime>=0.15.0",
52
+ "amazon-braket-sdk>=1.50.0",
53
+ "langchain>=0.1.0",
54
+ "crewai>=0.1.0",
55
+ ]
56
+ dev = [
57
+ "pytest>=7.0.0",
58
+ "pytest-asyncio>=0.21.0",
59
+ "black>=23.0.0",
60
+ "ruff>=0.1.0",
61
+ ]
62
+
63
+ [project.urls]
64
+ Homepage = "https://qflowai.dev"
65
+ Documentation = "https://qflowai.dev/docs"
66
+ Repository = "https://github.com/blockquantai/quantumflow"
67
+ Issues = "https://github.com/blockquantai/quantumflow/issues"
68
+
69
+ [project.scripts]
70
+ quantumflow = "quantumflow.cli:main"
71
+
72
+ [tool.setuptools.packages.find]
73
+ where = ["src"]
74
+
75
+ [tool.setuptools.package-dir]
76
+ "" = "src"
77
+
78
+ [tool.black]
79
+ line-length = 100
80
+ target-version = ["py39", "py310", "py311", "py312"]
81
+
82
+ [tool.ruff]
83
+ line-length = 100
84
+ select = ["E", "F", "I", "N", "W"]
85
+ ignore = ["E501"]
86
+
87
+ [tool.pytest.ini_options]
88
+ testpaths = ["tests"]
89
+ asyncio_mode = "auto"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1 @@
1
+ """QuantumFlow API Package."""
@@ -0,0 +1,208 @@
1
+ """
2
+ Authentication for QuantumFlow API.
3
+
4
+ Supports:
5
+ - API Key authentication
6
+ - JWT tokens for user sessions
7
+ - Database-backed user management
8
+ """
9
+
10
+ import os
11
+ from datetime import datetime, timedelta
12
+ from typing import Optional
13
+ from uuid import UUID
14
+
15
+ from fastapi import HTTPException, Security, status, Depends
16
+ from fastapi.security import APIKeyHeader, HTTPBearer
17
+ from jose import JWTError, jwt
18
+ from pydantic import BaseModel
19
+ from sqlalchemy.orm import Session
20
+
21
+ from db.database import get_db
22
+ from db import crud
23
+ from db.models import User, APIKey as APIKeyModel
24
+
25
+
26
+ # Configuration
27
+ API_KEY_HEADER = APIKeyHeader(name="X-API-Key", auto_error=False)
28
+ BEARER_SCHEME = HTTPBearer(auto_error=False)
29
+
30
+ SECRET_KEY = os.getenv("JWT_SECRET", "dev-secret-key-change-in-production")
31
+ ALGORITHM = "HS256"
32
+ ACCESS_TOKEN_EXPIRE_MINUTES = 60 * 24 # 24 hours
33
+
34
+
35
+ class TokenData(BaseModel):
36
+ """JWT token payload."""
37
+ user_id: str
38
+ exp: Optional[datetime] = None
39
+
40
+
41
+ class TokenResponse(BaseModel):
42
+ """Token response model."""
43
+ access_token: str
44
+ token_type: str = "bearer"
45
+ expires_in: int
46
+
47
+
48
+ class UserResponse(BaseModel):
49
+ """User response model."""
50
+ id: str
51
+ email: str
52
+ name: Optional[str]
53
+ tier: str
54
+ is_active: bool
55
+
56
+ class Config:
57
+ from_attributes = True
58
+
59
+
60
+ class APIKeyResponse(BaseModel):
61
+ """API key response (without full key)."""
62
+ id: str
63
+ name: str
64
+ prefix: str
65
+ created_at: datetime
66
+ last_used: Optional[datetime]
67
+ is_active: bool
68
+
69
+ class Config:
70
+ from_attributes = True
71
+
72
+
73
+ # ============== JWT Functions ==============
74
+
75
+ def create_access_token(user_id: str, expires_delta: Optional[timedelta] = None) -> str:
76
+ """Create a JWT access token."""
77
+ expire = datetime.utcnow() + (expires_delta or timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES))
78
+ to_encode = {"sub": user_id, "exp": expire}
79
+ return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
80
+
81
+
82
+ def verify_token(token: str) -> Optional[TokenData]:
83
+ """Verify and decode a JWT token."""
84
+ try:
85
+ payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
86
+ user_id: str = payload.get("sub")
87
+ if user_id is None:
88
+ return None
89
+ return TokenData(user_id=user_id, exp=payload.get("exp"))
90
+ except JWTError:
91
+ return None
92
+
93
+
94
+ # ============== Auth Dependencies ==============
95
+
96
+ def get_db_session():
97
+ """Get database session."""
98
+ db = next(get_db())
99
+ try:
100
+ yield db
101
+ finally:
102
+ db.close()
103
+
104
+
105
+ async def get_current_user(
106
+ api_key: Optional[str] = Security(API_KEY_HEADER),
107
+ bearer: Optional[object] = Security(BEARER_SCHEME),
108
+ db: Session = Depends(get_db_session),
109
+ ) -> User:
110
+ """
111
+ Get the current authenticated user.
112
+
113
+ Supports both API Key and Bearer token authentication.
114
+ Returns the User object from database.
115
+ """
116
+ # Try API Key first
117
+ if api_key:
118
+ key_record = crud.get_api_key(db, api_key)
119
+ if key_record:
120
+ crud.update_api_key_usage(db, key_record)
121
+ user = crud.get_user(db, key_record.user_id)
122
+ if user and user.is_active:
123
+ return user
124
+
125
+ # Try Bearer token
126
+ if bearer and hasattr(bearer, 'credentials'):
127
+ token_data = verify_token(bearer.credentials)
128
+ if token_data:
129
+ try:
130
+ user_id = UUID(token_data.user_id)
131
+ user = crud.get_user(db, user_id)
132
+ if user and user.is_active:
133
+ return user
134
+ except ValueError:
135
+ pass
136
+
137
+ # Fallback: Allow dev key in development
138
+ if api_key == "qf_dev_key_123" and os.getenv("ENV", "development") == "development":
139
+ # Create or get dev user
140
+ dev_user = crud.get_user_by_email(db, "dev@quantumflow.local")
141
+ if not dev_user:
142
+ dev_user = crud.create_user(db, "dev@quantumflow.local", "devpassword", "Dev User")
143
+ return dev_user
144
+
145
+ raise HTTPException(
146
+ status_code=status.HTTP_401_UNAUTHORIZED,
147
+ detail="Invalid or missing authentication",
148
+ headers={"WWW-Authenticate": "Bearer"},
149
+ )
150
+
151
+
152
+ async def get_optional_user(
153
+ api_key: Optional[str] = Security(API_KEY_HEADER),
154
+ bearer: Optional[object] = Security(BEARER_SCHEME),
155
+ db: Session = Depends(get_db_session),
156
+ ) -> Optional[User]:
157
+ """Get user if authenticated, None otherwise."""
158
+ try:
159
+ return await get_current_user(api_key, bearer, db)
160
+ except HTTPException:
161
+ return None
162
+
163
+
164
+ async def get_current_active_user(
165
+ current_user: User = Depends(get_current_user),
166
+ ) -> User:
167
+ """Ensure user is active."""
168
+ if not current_user.is_active:
169
+ raise HTTPException(
170
+ status_code=status.HTTP_403_FORBIDDEN,
171
+ detail="User account is disabled",
172
+ )
173
+ return current_user
174
+
175
+
176
+ async def check_user_quota(
177
+ current_user: User = Depends(get_current_active_user),
178
+ db: Session = Depends(get_db_session),
179
+ ) -> User:
180
+ """Check if user is within their usage quota."""
181
+ if not crud.check_quota(db, current_user):
182
+ raise HTTPException(
183
+ status_code=status.HTTP_429_TOO_MANY_REQUESTS,
184
+ detail="Monthly API quota exceeded. Please upgrade your plan.",
185
+ )
186
+ return current_user
187
+
188
+
189
+ # ============== Helper Functions ==============
190
+
191
+ def authenticate_user(db: Session, email: str, password: str) -> Optional[User]:
192
+ """Authenticate user by email and password."""
193
+ return crud.authenticate_user(db, email, password)
194
+
195
+
196
+ def create_user(db: Session, email: str, password: str, name: Optional[str] = None) -> User:
197
+ """Create a new user."""
198
+ return crud.create_user(db, email, password, name)
199
+
200
+
201
+ def create_api_key_for_user(
202
+ db: Session,
203
+ user_id: UUID,
204
+ name: str,
205
+ scopes: Optional[list[str]] = None,
206
+ ) -> tuple[APIKeyModel, str]:
207
+ """Create API key for user. Returns (key_record, raw_key)."""
208
+ return crud.create_api_key(db, user_id, name, scopes)