Spaces:
Sleeping
Sleeping
| import gradio as gr | |
| import requests | |
| import os | |
| API_URL = os.getenv("API_URL", "http://localhost:8000") | |
| def login(username, password): | |
| try: | |
| response = requests.post( | |
| f"{API_URL}/token", | |
| data={"username": username, "password": password, "grant_type": "password"}, | |
| headers={"Content-Type": "application/x-www-form-urlencoded"} | |
| ) | |
| if response.status_code == 200: | |
| token = response.json().get("access_token") | |
| return f"Login successful! Token: {token[:15]}... (truncated)" | |
| return f"Login failed: {response.json().get('detail', 'Unknown error')}" | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| def get_user_info(token): | |
| try: | |
| response = requests.get( | |
| f"{API_URL}/users/me", | |
| headers={"Authorization": f"Bearer {token}"} | |
| ) | |
| return str(response.json()) | |
| except Exception as e: | |
| return f"Error: {str(e)}" | |
| with gr.Blocks() as demo: | |
| gr.Markdown(""" | |
| # Secure JWT Authentication | |
| Test credentials: username=`testuser`, password=`secret` | |
| """) | |
| with gr.Row(): | |
| with gr.Column(): | |
| gr.Markdown("## Login") | |
| username = gr.Textbox(label="Username") | |
| password = gr.Textbox(label="Password", type="password") | |
| login_btn = gr.Button("Login") | |
| login_output = gr.Textbox(label="Login Result") | |
| with gr.Column(): | |
| gr.Markdown("## Get User Info") | |
| token = gr.Textbox(label="Your JWT Token") | |
| user_btn = gr.Button("Get User Info") | |
| user_output = gr.Textbox(label="User Info") | |
| login_btn.click(login, inputs=[username, password], outputs=login_output) | |
| user_btn.click(get_user_info, inputs=token, outputs=user_output) | |
| if __name__ == "__main__": | |
| demo.launch(server_name="0.0.0.0", server_port=7860) |