FadeClip commited on
Commit
2c97677
·
1 Parent(s): a66bba3

Enhance API key functionality with regeneration and better management

Browse files
Files changed (4) hide show
  1. chat.html +2 -0
  2. main.py +27 -1
  3. static/script.js +27 -0
  4. static/style.css +18 -0
chat.html CHANGED
@@ -14,6 +14,8 @@
14
  <label for="api-key-input">API Key:</label>
15
  <input type="password" id="api-key-input" placeholder="Enter API key">
16
  <button id="save-api-key">Save</button>
 
 
17
  </div>
18
  </div>
19
  <div id="chat-window">
 
14
  <label for="api-key-input">API Key:</label>
15
  <input type="password" id="api-key-input" placeholder="Enter API key">
16
  <button id="save-api-key">Save</button>
17
+ <button id="regenerate-key">Regenerate</button>
18
+ <div id="api-key-info">Check server console for auto-generated API key</div>
19
  </div>
20
  </div>
21
  <div id="chat-window">
main.py CHANGED
@@ -19,7 +19,7 @@ app.mount("/static", StaticFiles(directory="static"), name="static")
19
 
20
  def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
21
  """Verify that the provided API key is valid"""
22
- if credentials.credentials != API_KEY:
23
  raise HTTPException(
24
  status_code=401,
25
  detail="Invalid API key"
@@ -58,3 +58,29 @@ async def root():
58
  @app.get("/chat")
59
  async def chat_page():
60
  return FileResponse('chat.html')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
 
20
  def verify_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
21
  """Verify that the provided API key is valid"""
22
+ if credentials.credentials != current_api_key:
23
  raise HTTPException(
24
  status_code=401,
25
  detail="Invalid API key"
 
58
  @app.get("/chat")
59
  async def chat_page():
60
  return FileResponse('chat.html')
61
+
62
+ @app.get("/api/health")
63
+ async def health_check():
64
+ """Health check endpoint to verify API is running"""
65
+ return {"status": "ok"}
66
+
67
+ # Store the current API key in memory
68
+ current_api_key = API_KEY
69
+
70
+ @app.get("/api/config")
71
+ async def get_config():
72
+ """Return configuration information including the API key status (without revealing the key)"""
73
+ has_env_key = bool(os.getenv("OLLAMA_API_KEY"))
74
+ return {
75
+ "api_key_set": has_env_key,
76
+ "model_default": "qwen3:1.7b"
77
+ }
78
+
79
+ @app.post("/api/regenerate_key")
80
+ async def regenerate_api_key(credentials: HTTPAuthorizationCredentials = Depends(security)):
81
+ """Regenerate the API key (requires valid current API key)"""
82
+ global current_api_key
83
+ new_key = secrets.token_urlsafe(32)
84
+ current_api_key = new_key
85
+ print(f"New API Key: {new_key}") # Display the new key in the console
86
+ return {"message": "API key regenerated successfully", "key": new_key}
static/script.js CHANGED
@@ -3,6 +3,7 @@ const messageInput = document.getElementById('message-input');
3
  const sendButton = document.getElementById('send-button');
4
  const apiKeyInput = document.getElementById('api-key-input');
5
  const saveApiKeyButton = document.getElementById('save-api-key');
 
6
 
7
  // Get API key from localStorage
8
  let apiKey = localStorage.getItem('ollama_api_key');
@@ -22,6 +23,32 @@ saveApiKeyButton.addEventListener('click', () => {
22
  }
23
  });
24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
  // Send message function
26
  sendButton.addEventListener('click', sendMessage);
27
  messageInput.addEventListener('keydown', (event) => {
 
3
  const sendButton = document.getElementById('send-button');
4
  const apiKeyInput = document.getElementById('api-key-input');
5
  const saveApiKeyButton = document.getElementById('save-api-key');
6
+ const regenerateKeyButton = document.getElementById('regenerate-key');
7
 
8
  // Get API key from localStorage
9
  let apiKey = localStorage.getItem('ollama_api_key');
 
23
  }
24
  });
25
 
26
+ // Regenerate API key button event
27
+ regenerateKeyButton.addEventListener('click', () => {
28
+ if (confirm('Are you sure you want to regenerate the API key? This will invalidate the current key.')) {
29
+ fetch('/api/regenerate_key', {
30
+ method: 'POST',
31
+ headers: {
32
+ 'Content-Type': 'application/json',
33
+ 'Authorization': `Bearer ${apiKey}`
34
+ }
35
+ })
36
+ .then(response => response.json())
37
+ .then(data => {
38
+ if (data.key) {
39
+ alert(`New API key generated. Please update your API key in the input field. The new key is (also shown in server console): ${data.key}`);
40
+ // Do not automatically update the API key in localStorage for security reasons
41
+ } else {
42
+ alert('Failed to regenerate API key. Please check the server.');
43
+ }
44
+ })
45
+ .catch(error => {
46
+ console.error('Error regenerating API key:', error);
47
+ alert('Error regenerating API key. Please check the server.');
48
+ });
49
+ }
50
+ });
51
+
52
  // Send message function
53
  sendButton.addEventListener('click', sendMessage);
54
  messageInput.addEventListener('keydown', (event) => {
static/style.css CHANGED
@@ -33,6 +33,7 @@ body {
33
  display: flex;
34
  align-items: center;
35
  gap: 10px;
 
36
  }
37
 
38
  #api-key-input {
@@ -41,6 +42,14 @@ body {
41
  border-radius: 3px;
42
  }
43
 
 
 
 
 
 
 
 
 
44
  #save-api-key {
45
  background-color: #007cba;
46
  color: white;
@@ -50,6 +59,15 @@ body {
50
  cursor: pointer;
51
  }
52
 
 
 
 
 
 
 
 
 
 
53
  #chat-window {
54
  flex-grow: 1;
55
  overflow-y: auto;
 
33
  display: flex;
34
  align-items: center;
35
  gap: 10px;
36
+ flex-wrap: wrap;
37
  }
38
 
39
  #api-key-input {
 
42
  border-radius: 3px;
43
  }
44
 
45
+ #api-key-info {
46
+ font-size: 0.8em;
47
+ color: #666;
48
+ background-color: #f0f0f0;
49
+ padding: 3px 6px;
50
+ border-radius: 3px;
51
+ }
52
+
53
  #save-api-key {
54
  background-color: #007cba;
55
  color: white;
 
59
  cursor: pointer;
60
  }
61
 
62
+ #regenerate-key {
63
+ background-color: #ff9800;
64
+ color: white;
65
+ border: none;
66
+ padding: 5px 10px;
67
+ border-radius: 3px;
68
+ cursor: pointer;
69
+ }
70
+
71
  #chat-window {
72
  flex-grow: 1;
73
  overflow-y: auto;