42 lines
1.3 KiB
Python
42 lines
1.3 KiB
Python
from __future__ import annotations
|
|
import secrets
|
|
import time
|
|
import json
|
|
from pathlib import Path
|
|
from .config import OAUTH_STATE
|
|
from .vault import load_tokens, save_tokens
|
|
|
|
|
|
def start(provider: str, redirect_uri: str) -> dict:
|
|
provider = provider.lower()
|
|
if provider not in {'openai', 'anthropic'}:
|
|
raise ValueError('Unsupported provider')
|
|
state = secrets.token_urlsafe(24)
|
|
OAUTH_STATE.mkdir(parents=True, exist_ok=True)
|
|
(OAUTH_STATE / f'{provider}-{state}.json').write_text(json.dumps({
|
|
'provider': provider,
|
|
'state': state,
|
|
'redirect_uri': redirect_uri,
|
|
'ts': int(time.time())
|
|
}))
|
|
return {
|
|
'provider': provider,
|
|
'state': state,
|
|
'auth_url': f'https://auth.example/{provider}?state={state}&redirect_uri={redirect_uri}'
|
|
}
|
|
|
|
|
|
def callback(provider: str, state: str, code: str) -> dict:
|
|
p = OAUTH_STATE / f'{provider}-{state}.json'
|
|
if not p.exists():
|
|
raise ValueError('Invalid state')
|
|
tokens = load_tokens()
|
|
tokens[provider] = {
|
|
'access_token': f'stub_access_{code[:8]}',
|
|
'refresh_token': f'stub_refresh_{code[:8]}',
|
|
'updated_at': int(time.time())
|
|
}
|
|
save_tokens(tokens)
|
|
p.unlink(missing_ok=True)
|
|
return {'ok': True, 'provider': provider}
|