File size: 3,071 Bytes
ccec886
ddbc9ac
9034804
ddbc9ac
 
 
128003a
afc2013
128003a
ddbc9ac
 
a04ed72
ddbc9ac
 
128003a
 
 
ddbc9ac
 
 
 
128003a
 
 
ddbc9ac
 
 
128003a
 
 
ddbc9ac
91bbd67
5166981
 
 
 
 
128003a
da43acc
5166981
10ee58a
ddbc9ac
128003a
 
 
da43acc
128003a
 
da43acc
bf6a2a7
da43acc
bf6a2a7
 
da43acc
bf6a2a7
da43acc
 
128003a
ddbc9ac
 
128003a
ddbc9ac
 
91bbd67
820afe6
f37ec25
bf6a2a7
da43acc
 
 
 
bf6a2a7
da43acc
bf6a2a7
da43acc
 
3110228
820afe6
 
 
 
 
 
 
 
 
 
 
 
ddbc9ac
da43acc
 
ddbc9ac
da43acc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import gradio as gr
import os
import threading
from urllib.parse import urlparse, parse_qs
import discord
from discord.ext import commands
import secrets

# Discord bot -----------------------------------------------------------------------------------------------
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
GRADIO_APP_URL = "https://huggingface.co/spaces/lunarflu/gradio-oauth2"
DISCORD_TOKEN = os.environ.get("DISCORD_TOKEN", None)

# Dictionary to store user IDs and their corresponding unique strings
user_tokens = {}

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user}')

def generate_unique_string(length=6):
    return secrets.token_hex(length // 2)

@bot.command()
async def sendlink(ctx, user: discord.User):
    if ctx.author.id == 811235357663297546:
        unique_string = generate_unique_string()
        user_tokens[user.id] = unique_string
        unique_link = f"{GRADIO_APP_URL}?user_id={user.id}&token={unique_string}"
        await user.send(f"Click the link to sign in with Hugging Face: {unique_link}")

def run_bot():
    bot.run(DISCORD_TOKEN)

threading.Thread(target=run_bot).start()

# Gradio ------------------------------------------------------------------------------------------------------------
def validate_link(request: gr.Request):
    url_str = str(request.url)
    query_params = parse_qs(urlparse(url_str).query)
    user_id = query_params.get('user_id', [None])[0]
    token = query_params.get('token', [None])[0]

    if user_id is None or token is None:
        return False, None, None

    if int(user_id) not in user_tokens or user_tokens[int(user_id)] != token:
        return False, None, None

    return True, user_id, token

def hello(profile: gr.OAuthProfile | None, request: gr.Request) -> str:
    is_valid, user_id, token = validate_link(request)

    if not is_valid:
        return "❌ Invalid link or expired token."

    if profile is None:
        return f"❌ Not logged in. User ID: {user_id}"

    return f"✅ Successfully logged in as {profile.username}. User ID: {user_id}"

with gr.Blocks() as demo:
    gr.Markdown("# Gradio OAuth Space")
    m1 = gr.Markdown()

    def conditional_login_button(request: gr.Request):
        is_valid, _, _ = validate_link(request)
        if is_valid:
            return gr.LoginButton()
        else:
            return gr.Markdown("❌ Invalid link or expired token.")

    login_button = conditional_login_button(gr.Request())
    demo.load(hello, inputs=None, outputs=m1)

    def check_login_status():
        try:
            return login_button.get_session().get("oauth_info", None)
        except AttributeError:
            return None

    def check_login_wrapper():
        session = check_login_status()
        if session is None:
            return "Not logged in."
        else:
            return f"Logged in as {session.get('username', 'Unknown')}"

    if isinstance(login_button, gr.LoginButton):
        login_button.click(check_login_wrapper, inputs=None, outputs=m1)

demo.launch()