thibaud frere commited on
Commit
4563b43
·
1 Parent(s): a4001b5
Files changed (1) hide show
  1. index.html +54 -14
index.html CHANGED
@@ -13,12 +13,17 @@
13
  </head>
14
  <body>
15
  <h1>HF OAuth Example</h1>
16
- <button id="signin">Sign in with Hugging Face</button>
 
 
 
17
  <button id="signout" style="display:none;">Sign out</button>
18
  <div id="status"></div>
19
  <pre id="userinfo" style="display:none;"></pre>
20
  <script>
21
- const CLIENT_ID = window.huggingfaceConfig?.oauth?.client_id || 'e0906ea6-519f-4aa0-a128-9b7df044e477';
 
 
22
  const REDIRECT_URI = window.location.origin + window.location.pathname;
23
 
24
  function showLoggedIn(userinfo) {
@@ -39,8 +44,10 @@
39
  document.getElementById('signin').onclick = function () {
40
  const state = Math.random().toString(36).slice(2);
41
  localStorage.setItem('hf_oauth_state', state);
42
- const url = `https://huggingface.co/oauth/authorize?client_id=${CLIENT_ID}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&response_type=code&scope=openid%20profile&state=${state}`;
43
- window.location = url;
 
 
44
  };
45
 
46
  document.getElementById('signout').onclick = function () {
@@ -55,30 +62,63 @@
55
  if (params.has('code') && params.has('state')) {
56
  const state = params.get('state');
57
  if (state !== localStorage.getItem('hf_oauth_state')) {
58
- document.getElementById('status').textContent = 'Invalid state';
59
  return;
60
  }
61
 
62
  const code = params.get('code');
63
- document.getElementById('status').textContent = 'Getting user info...';
64
 
65
  try {
66
- const resp = await fetch('https://huggingface.co/api/whoami-v2', {
67
- headers: { Authorization: `Bearer ${code}` }
 
 
 
 
 
 
 
 
 
 
 
68
  });
69
 
70
- if (resp.ok) {
71
- const userinfo = await resp.json();
72
- localStorage.setItem('hf_oauth_userinfo', JSON.stringify(userinfo, null, 2));
73
- showLoggedIn(JSON.stringify(userinfo, null, 2));
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74
  } else {
75
- document.getElementById('status').textContent = 'Auth successful!';
76
- showLoggedIn(`Code: ${code}`);
77
  }
78
 
79
  window.history.replaceState({}, '', window.location.pathname);
80
  } catch (error) {
 
81
  document.getElementById('status').textContent = 'Error: ' + error.message;
 
82
  }
83
  return;
84
  }
 
13
  </head>
14
  <body>
15
  <h1>HF OAuth Example</h1>
16
+
17
+ <img src="https://huggingface.co/datasets/huggingface/badges/resolve/main/sign-in-with-huggingface-xl-dark.svg"
18
+ alt="Sign in with Hugging Face" id="signin" style="cursor:pointer;display:none;max-width:300px;">
19
+
20
  <button id="signout" style="display:none;">Sign out</button>
21
  <div id="status"></div>
22
  <pre id="userinfo" style="display:none;"></pre>
23
  <script>
24
+ // Use environment variables provided by HF Spaces OAuth
25
+ const CLIENT_ID = window.OAUTH_CLIENT_ID || 'e0906ea6-519f-4aa0-a128-9b7df044e477';
26
+ const CLIENT_SECRET = window.OAUTH_CLIENT_SECRET;
27
  const REDIRECT_URI = window.location.origin + window.location.pathname;
28
 
29
  function showLoggedIn(userinfo) {
 
44
  document.getElementById('signin').onclick = function () {
45
  const state = Math.random().toString(36).slice(2);
46
  localStorage.setItem('hf_oauth_state', state);
47
+ // Use official OAuth URL as per documentation
48
+ const url = `https://huggingface.co/oauth/authorize?redirect_uri=${encodeURIComponent(REDIRECT_URI)}&scope=openid%20profile&client_id=${CLIENT_ID}&state=${state}`;
49
+ // Open in new tab to avoid iframe issues
50
+ window.open(url, '_blank');
51
  };
52
 
53
  document.getElementById('signout').onclick = function () {
 
62
  if (params.has('code') && params.has('state')) {
63
  const state = params.get('state');
64
  if (state !== localStorage.getItem('hf_oauth_state')) {
65
+ document.getElementById('status').textContent = 'Invalid state parameter';
66
  return;
67
  }
68
 
69
  const code = params.get('code');
70
+ document.getElementById('status').textContent = 'Exchanging code for access token...';
71
 
72
  try {
73
+ // Official token exchange as per HF documentation
74
+ const tokenResponse = await fetch('https://huggingface.co/oauth/token', {
75
+ method: 'POST',
76
+ headers: {
77
+ 'Content-Type': 'application/x-www-form-urlencoded',
78
+ 'Authorization': `Basic ${btoa(CLIENT_ID + ':' + (CLIENT_SECRET || ''))}`
79
+ },
80
+ body: new URLSearchParams({
81
+ grant_type: 'authorization_code',
82
+ code: code,
83
+ redirect_uri: REDIRECT_URI,
84
+ client_id: CLIENT_ID
85
+ })
86
  });
87
 
88
+ if (!tokenResponse.ok) {
89
+ throw new Error(`Token exchange failed: ${tokenResponse.status}`);
90
+ }
91
+
92
+ const tokenData = await tokenResponse.json();
93
+
94
+ if (tokenData.access_token) {
95
+ // Get user info with access token
96
+ document.getElementById('status').textContent = 'Getting user information...';
97
+
98
+ const userResponse = await fetch('https://huggingface.co/oauth/userinfo', {
99
+ headers: {
100
+ 'Authorization': `Bearer ${tokenData.access_token}`
101
+ }
102
+ });
103
+
104
+ if (userResponse.ok) {
105
+ const userInfo = await userResponse.json();
106
+ const userInfoStr = JSON.stringify(userInfo, null, 2);
107
+ localStorage.setItem('hf_oauth_token', tokenData.access_token);
108
+ localStorage.setItem('hf_oauth_userinfo', userInfoStr);
109
+ showLoggedIn(userInfoStr);
110
+ } else {
111
+ throw new Error('Failed to get user info');
112
+ }
113
  } else {
114
+ throw new Error('No access token received');
 
115
  }
116
 
117
  window.history.replaceState({}, '', window.location.pathname);
118
  } catch (error) {
119
+ console.error('OAuth error:', error);
120
  document.getElementById('status').textContent = 'Error: ' + error.message;
121
+ showLoggedOut();
122
  }
123
  return;
124
  }