Chris Addis commited on
Commit
a10d489
·
1 Parent(s): a1fd37a
Files changed (3) hide show
  1. .ipynb_checkpoints/README-checkpoint.md +13 -0
  2. README.md +1 -0
  3. app.py +29 -271
.ipynb_checkpoints/README-checkpoint.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Oauth Test
3
+ emoji: 💻
4
+ colorFrom: blue
5
+ colorTo: yellow
6
+ sdk: gradio
7
+ sdk_version: 5.29.0
8
+ app_file: app.py
9
+ pinned: false
10
+ license: mit
11
+ ---
12
+
13
+ Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
README.md CHANGED
@@ -7,6 +7,7 @@ sdk: gradio
7
  sdk_version: 5.29.0
8
  app_file: app.py
9
  pinned: false
 
10
  license: mit
11
  ---
12
 
 
7
  sdk_version: 5.29.0
8
  app_file: app.py
9
  pinned: false
10
+ hf_oauth: true
11
  license: mit
12
  ---
13
 
app.py CHANGED
@@ -1,6 +1,6 @@
1
  import gradio as gr
2
  import os
3
- from huggingface_hub import HfApi, hf_hub_url
4
  import json
5
 
6
  # IMPORTANT: Debug prints to verify environment variables
@@ -9,276 +9,34 @@ print(f"Environment variables available: {list(os.environ.keys())}")
9
 
10
  # Get authorized users from environment variable/secret
11
  authorized_users_str = os.environ.get("AUTHORIZED_USER_IDS", "")
12
- print(f"Raw AUTHORIZED_USER_IDS value: '{authorized_users_str}'")
13
-
14
- # Parse the comma-separated list into a set
15
  AUTHORIZED_USER_IDS = set(authorized_users_str.split(',') if authorized_users_str and authorized_users_str.strip() else [])
16
  print(f"Parsed authorized users: {AUTHORIZED_USER_IDS}")
17
 
18
- print("=================================")
19
-
20
- # Function to determine if the current user has full access
21
- def check_user_access():
22
- """Check if the current user has full access based on their Hugging Face identity."""
23
- try:
24
- # Get username from Gradio's authentication context
25
- # In Hugging Face Spaces, this will provide the logged-in username
26
- username = None
27
-
28
- # First, check if we're running in a Hugging Face Space
29
- if hasattr(gr, "me") and callable(gr.me):
30
- try:
31
- # gr.me() returns user information when authenticated in Spaces
32
- user_info = gr.me()
33
- if user_info:
34
- username = user_info.get("username")
35
- print(f"Detected username via gr.me(): {username}")
36
- except Exception as e:
37
- print(f"Error using gr.me(): {e}")
38
-
39
- # Fallback methods to get username
40
- if not username:
41
- # Try USER environment variable (as mentioned in your code)
42
- username = os.environ.get("USER")
43
- if username:
44
- print(f"Using USER env var: {username}")
45
-
46
- # Try SPACE_AUTHOR (might contain space owner's username)
47
- if not username:
48
- space_author = os.environ.get("SPACE_AUTHOR")
49
- if space_author:
50
- username = space_author
51
- print(f"Using SPACE_AUTHOR: {username}")
52
-
53
- # For local development/testing, you can set a mock username
54
- if not username and os.environ.get("DEVELOPMENT_MODE"):
55
- username = os.environ.get("MOCK_USERNAME", "test_user")
56
- print(f"Using mock username: {username}")
57
-
58
- # Debug output
59
- print(f"Detected username: {username}")
60
- print(f"Authorized users: {AUTHORIZED_USER_IDS}")
61
-
62
- # If still no username, user is not logged in
63
- if not username:
64
- print("No username detected, assuming not logged in")
65
- return False, None
66
-
67
- # Check if user is in the authorized list
68
- has_full_access = username in AUTHORIZED_USER_IDS
69
- print(f"Full access granted: {has_full_access}")
70
-
71
- return has_full_access, username
72
- except Exception as e:
73
- print(f"Error checking user access: {e}")
74
- return False, None
75
-
76
- # Function to add the current user to the authorized list (admin function)
77
- def add_current_user_to_authorized():
78
- _, username = check_user_access()
79
- if not username:
80
- return "Not logged in - can't add user", False
81
-
82
- global AUTHORIZED_USER_IDS
83
- if username not in AUTHORIZED_USER_IDS:
84
- AUTHORIZED_USER_IDS.add(username)
85
- print(f"Added {username} to authorized users. New list: {AUTHORIZED_USER_IDS}")
86
- return f"Added {username} to authorized users!", True
87
- else:
88
- return f"{username} is already an authorized user", True
89
-
90
- # Example data processing function (limited functionality)
91
- def process_data_limited(input_text):
92
- """Process data with limited functionality."""
93
- return f"Limited processing: {input_text.upper()}"
94
-
95
- # Example data processing function (full functionality)
96
- def process_data_full(input_text):
97
- """Process data with full functionality."""
98
- word_count = len(input_text.split())
99
- char_count = len(input_text)
100
-
101
- analysis = {
102
- "Original text": input_text,
103
- "Word count": word_count,
104
- "Character count": char_count,
105
- "Uppercase version": input_text.upper(),
106
- "Lowercase version": input_text.lower(),
107
- "Reversed text": input_text[::-1]
108
- }
109
-
110
- return json.dumps(analysis, indent=2)
111
-
112
- # Function to handle form submission and apply the appropriate access level
113
- def handle_submission(input_text):
114
- has_full_access, username = check_user_access()
115
-
116
- if has_full_access:
117
- return process_data_full(input_text), f"Full access granted for {username}", True
118
- else:
119
- limited_user_display = f"Limited access for {username}" if username else "Limited access (not logged in)"
120
- return process_data_limited(input_text), limited_user_display, False
121
-
122
- # Function to get the current login status display
123
- def get_login_status():
124
- has_full_access, username = check_user_access()
125
- status_text = f"Full access for {username}" if has_full_access else \
126
- f"Limited access for {username}" if username else \
127
- "Limited access (not logged in)"
128
-
129
- # Return username or empty string if not detected
130
- user_id = username if username else ""
131
-
132
- return status_text, has_full_access, user_id
133
-
134
- # Create the Gradio interface
135
- with gr.Blocks(title="Access Control Demo") as demo:
136
- gr.Markdown("# Hugging Face Spaces Access Control Demo")
137
- gr.Markdown("""
138
- This demo shows how to implement access control in a Gradio app on Hugging Face Spaces.
139
-
140
- - **Limited access**: Basic functionality only (uppercase conversion)
141
- - **Full access**: Complete text analysis suite (for authorized users only)
142
-
143
- To test different access levels, log in with different Hugging Face accounts.
144
- """)
145
-
146
- # Display current user and access level
147
- with gr.Row():
148
- status_display = gr.Textbox(
149
- label="Current Access Status",
150
- interactive=False
151
- )
152
- access_indicator = gr.Checkbox(
153
- label="Full Access",
154
- interactive=False
155
- )
156
-
157
- # Create the Gradio interface
158
- with gr.Blocks(title="Access Control Demo") as demo:
159
- gr.Markdown("# Hugging Face Spaces Access Control Demo")
160
- gr.Markdown("""
161
- This demo shows how to implement access control in a Gradio app on Hugging Face Spaces.
162
-
163
- - **Limited access**: Basic functionality only (uppercase conversion)
164
- - **Full access**: Complete text analysis suite (for authorized users only)
165
-
166
- Access is controlled via the AUTHORIZED_USER_IDS environment variable/secret.
167
- """)
168
-
169
- # Display current user ID in a dedicated textbox
170
- user_id_display = gr.Textbox(
171
- label="Current User ID",
172
- interactive=False
173
- )
174
-
175
- # Display current user and access level
176
- with gr.Row():
177
- status_display = gr.Textbox(
178
- label="Current Access Status",
179
- interactive=False
180
- )
181
- access_indicator = gr.Checkbox(
182
- label="Full Access",
183
- interactive=False
184
- )
185
-
186
- # Add refresh button
187
- refresh_btn = gr.Button("Refresh Login Status")
188
-
189
- # Input form
190
- with gr.Row():
191
- input_text = gr.Textbox(
192
- label="Enter text to process",
193
- placeholder="Type something here...",
194
- lines=5
195
- )
196
-
197
- # Submit button
198
- submit_btn = gr.Button("Process Text")
199
-
200
- # Output display
201
- output_text = gr.Textbox(
202
- label="Processing Result",
203
- lines=10
204
- )
205
-
206
- # Connect the submit button to the handler function
207
- submit_btn.click(
208
- fn=handle_submission,
209
- inputs=[input_text],
210
- outputs=[output_text, status_display, access_indicator]
211
- )
212
-
213
- # Connect the refresh button to update login status
214
- refresh_btn.click(
215
- fn=get_login_status,
216
- inputs=[],
217
- outputs=[status_display, access_indicator, user_id_display]
218
- )
219
-
220
- # Initialize the status display
221
- demo.load(
222
- fn=get_login_status,
223
- inputs=[],
224
- outputs=[status_display, access_indicator, user_id_display]
225
- )
226
-
227
- # Input form
228
- with gr.Row():
229
- input_text = gr.Textbox(
230
- label="Enter text to process",
231
- placeholder="Type something here...",
232
- lines=5
233
- )
234
-
235
- # Submit button
236
- submit_btn = gr.Button("Process Text")
237
-
238
- # Output display
239
- output_text = gr.Textbox(
240
- label="Processing Result",
241
- lines=10
242
- )
243
-
244
- # Connect the submit button to the handler function
245
- submit_btn.click(
246
- fn=handle_submission,
247
- inputs=[input_text],
248
- outputs=[output_text, status_display, access_indicator]
249
- )
250
-
251
- # Connect the refresh button to update login status
252
- refresh_btn.click(
253
- fn=get_login_status,
254
- inputs=[],
255
- outputs=[status_display, access_indicator]
256
- )
257
-
258
- # Initialize the status display
259
- demo.load(
260
- fn=get_login_status,
261
- inputs=[],
262
- outputs=[status_display, access_indicator]
263
- )
264
-
265
- # Additional information section
266
- gr.Markdown("""
267
- ## How This Works
268
-
269
- 1. When a user accesses this Gradio app on Hugging Face Spaces, their login identity is available
270
- 2. The app checks if the username is in the list of authorized users
271
- 3. Different functionality is provided based on the user's access level
272
- 4. Full access users get the complete set of features
273
- 5. Limited access users (or users who aren't logged in) get basic functionality only
274
-
275
- This pattern can be extended to implement more complex access control scenarios.
276
- """)
277
-
278
- # Launch the app
279
- if __name__ == "__main__":
280
- # For local development, set an environment variable to mock user identities
281
- if os.environ.get("DEVELOPMENT_MODE"):
282
- print("Running in development mode with mock username")
283
-
284
- demo.launch()
 
1
  import gradio as gr
2
  import os
3
+ from huggingface_hub import HfApi, hf_hub_url, whoami
4
  import json
5
 
6
  # IMPORTANT: Debug prints to verify environment variables
 
9
 
10
  # Get authorized users from environment variable/secret
11
  authorized_users_str = os.environ.get("AUTHORIZED_USER_IDS", "")
 
 
 
12
  AUTHORIZED_USER_IDS = set(authorized_users_str.split(',') if authorized_users_str and authorized_users_str.strip() else [])
13
  print(f"Parsed authorized users: {AUTHORIZED_USER_IDS}")
14
 
15
+ def hello(profile: gr.OAuthProfile | None) -> str:
16
+ if profile is None:
17
+ return "I don't know you."
18
+ return f"Hello {profile.name}"
19
+
20
+ def list_organizations(oauth_token: gr.OAuthToken | None) -> str:
21
+ if oauth_token is None:
22
+ return "Please log in to list organizations."
23
+ org_names = [org["name"] for org in whoami(oauth_token.token)["orgs"]]
24
+ return f"You belong to {', '.join(org_names)}."
25
+
26
+ # New function to display authorized user IDs
27
+ def display_authorized_users() -> str:
28
+ if not AUTHORIZED_USER_IDS:
29
+ return "No authorized users configured."
30
+ return f"Authorized User IDs: {', '.join(AUTHORIZED_USER_IDS)}"
31
+
32
+ with gr.Blocks() as demo:
33
+ gr.LoginButton()
34
+ m1 = gr.Markdown()
35
+ m2 = gr.Markdown()
36
+ m3 = gr.Markdown() # New markdown component for authorized users
37
+
38
+ demo.load(hello, inputs=None, outputs=m1)
39
+ demo.load(list_organizations, inputs=None, outputs=m2)
40
+ demo.load(display_authorized_users, inputs=None, outputs=m3) # Load the authorized users display
41
+
42
+ demo.launch()