Skip to content

Commit

Permalink
Login to fill API key (#132)
Browse files Browse the repository at this point in the history
* login to fill API key

* Update auth.py

* Update auth.py

* fmt

* simplify implementation of callback

* Update auth.py

* Update auth.py

* refine cross-window communication

* unify query

* Update apiKey.js

* Update apiKey.js

* use window.location.origin

* Update apiKey.js

Update main.py

Update apiKey.js

set

add

add

Create main.py

* Update auth.py

* Update main.py

* Update main.py

* Update apiKey.js

* Update styleUploadFile.js

* Create requirements.txt

* Update main.py
  • Loading branch information
jackalcooper authored Sep 25, 2024
1 parent f76b381 commit b5f9f17
Show file tree
Hide file tree
Showing 5 changed files with 139 additions and 4 deletions.
6 changes: 3 additions & 3 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,17 @@ repos:
hooks:
- id: sort-imports
name: Sort imports
entry: python -m isort --profile black .
entry: python3 -m isort --profile black .
language: system
types: [python]
- id: format-code
name: Format code
entry: python -m black .
entry: python3 -m black .
language: system
types: [python]
- id: flake8-code-check
name: Code Quality Check
entry: python -m flake8 .
entry: python3 -m flake8 .
language: system
types: [python]

Expand Down
118 changes: 118 additions & 0 deletions bizyair_extras/oauth_callback/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import argparse
import asyncio
import json

import aiohttp
from aiohttp import web


# Set up command-line argument parsing
def parse_arguments():
parser = argparse.ArgumentParser(description="OAuth Callback Server")
parser.add_argument(
"--account_endpoint",
type=str,
default="https://account.siliconflow.cn",
help="The account endpoint URL",
)
parser.add_argument(
"--cloud_endpoint",
type=str,
default="https://cloud.siliconflow.cn",
help="The cloud endpoint URL",
)
parser.add_argument(
"--client_id",
type=str,
default="SFaJLLq0y6CAMoyDm81aMu",
help="The client ID for OAuth",
)
parser.add_argument(
"--secret",
type=str,
required=True,
help="The secret for OAuth",
)
parser.add_argument(
"--port",
type=int,
default=8080,
help="The port to run the server on",
)

return parser.parse_args()


args = parse_arguments()
ACCOUNT_ENDPOINT = args.account_endpoint
CLOUD_ENDPOINT = args.cloud_endpoint
client_id = args.client_id
secret = args.secret
port = args.port # Added the port argument


async def fetch_api_key(request):
code = request.rel_url.query.get("code")

if not code:
return web.Response(text="Missing 'code' parameter", status=400)

token_fetch_url = f"{ACCOUNT_ENDPOINT}/api/open/oauth"

# Prepare the payload
payload = {"clientId": client_id, "secret": secret, "code": code}

async with aiohttp.ClientSession() as session:
# Make the first POST request to fetch the token
async with session.post(token_fetch_url, json=payload) as response:
if not response.ok:
return web.Response(text="Failed to fetch access token", status=500)

token_json = await response.json()
access_token = (
token_json["data"]["access_token"] if token_json.get("status") else None
)

if not access_token:
return web.Response(text="Failed to retrieve access token", status=500)

print("access_token", access_token)

api_key_url = f"{CLOUD_ENDPOINT}/api/oauth/apikeys"
headers = {"Authorization": f"token {access_token}"}

# Make the second POST request to fetch API keys
async with session.post(api_key_url, headers=headers) as api_key_response:
api_keys_data = await api_key_response.json()
print("apiKeysData", api_keys_data)

if api_keys_data.get("data"):
return web.Response(
text=f"""
<html>
<head>
<title>BizyAir</title>
</head>
<body>
<h1>Just a moment...</h1>
<script>
window.opener.postMessage({json.dumps(api_keys_data["data"])}, '*');
</script>
</body>
</html>
""",
content_type="text/html",
)
else:
return web.Response(text="Failed to fetch API key", status=500)


async def init_app():
app = web.Application()
app.router.add_get("/bizyair/oauth_callback", fetch_api_key)
return app


if __name__ == "__main__":
app = asyncio.run(init_app())
web.run_app(app, port=port) # Use the port argument here
1 change: 1 addition & 0 deletions bizyair_extras/oauth_callback/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
aiohttp
4 changes: 3 additions & 1 deletion js/dialog/apiKey.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { dialog } from '../subassembly/dialog.js';
import { $el } from "../../../scripts/ui.js";
import { openOAuthPopup } from "./oauth.js";
export function apiKey() {
async function toSubmit() {
const apiKey = document.querySelector('#bizyair-api-key');
Expand Down Expand Up @@ -48,7 +49,8 @@ export function apiKey() {
this.className = 'cm-input-item'
}
}),
$el('p.confirm-word', {}, ['Please visit', $el('a.bizyair-link', { href: 'https://cloud.siliconflow.cn', target: '_blank' }, ['https://cloud.siliconflow.cn']), " to get your key."]),
$el('p.confirm-word', {}, ['Please', $el('a.bizyair-link', { href: '', target: '_blank', onclick: () => openOAuthPopup((key) => document.querySelector('#bizyair-api-key').value = key ) }, ['click to login']), " and autofill the key,"]),
$el('p.confirm-word', {}, ['or visit', $el('a.bizyair-link', { href: 'https://cloud.siliconflow.cn', target: '_blank' }, ['https://cloud.siliconflow.cn']), " to get your key and input manually."]),
$el('p.confirm-word', {}, [
"Setting the API Key signifies agreement to the",
$el('a.bizyair-link', {
Expand Down
14 changes: 14 additions & 0 deletions js/dialog/oauth.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Open a new window for the OAuth
export const openOAuthPopup = async (setKey) => {
const clientId = 'SFaJLLq0y6CAMoyDm81aMu';
const ACCOUNT_ENDPOINT = 'https://account.siliconflow.cn';
const authUrl = `${ACCOUNT_ENDPOINT}/oauth?client_id=${clientId}`;
const popup = window.open(authUrl, 'oauthPopup', 'width=600,height=600');
window.addEventListener('message', (event) => {
if (event.data.length > 0 && event.data[0]['secretKey'] !== undefined) {
setKey(event.data[0]['secretKey']);
}
popup.close();
});
window.postMessage
}

0 comments on commit b5f9f17

Please sign in to comment.