Spaces:
Build error
Build error
File size: 7,678 Bytes
1bd7131 |
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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
# Google Sign-In Client Integration Guide
Quick guide for frontend developers to integrate Google Sign-In with the APIGateway.
## Setup
### 1. Get Your Google Client ID
Use the same `GOOGLE_CLIENT_ID` that's configured on the backend.
### 2. Add Google Identity Services Script
```html
<script src="https://accounts.google.com/gsi/client" async defer></script>
```
---
## Option A: One-Tap / Button Sign-In (Recommended)
```html
<!DOCTYPE html>
<html>
<head>
<script src="https://accounts.google.com/gsi/client" async defer></script>
</head>
<body>
<!-- Google One Tap prompt -->
<div id="g_id_onload"
data-client_id="YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com"
data-callback="handleGoogleSignIn"
data-auto_prompt="false">
</div>
<!-- Sign In Button -->
<div class="g_id_signin"
data-type="standard"
data-size="large"
data-theme="outline"
data-text="sign_in_with"
data-shape="rectangular"
data-logo_alignment="left">
</div>
<script>
const API_BASE = 'https://your-api-gateway.com'; // Change this
async function handleGoogleSignIn(response) {
try {
// Send Google token to your backend
const res = await fetch(`${API_BASE}/auth/google`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id_token: response.credential,
temp_user_id: localStorage.getItem('temp_user_id') // optional
})
});
const data = await res.json();
if (data.success) {
// Store the access token
localStorage.setItem('access_token', data.access_token);
localStorage.setItem('user', JSON.stringify({
user_id: data.user_id,
email: data.email,
name: data.name,
credits: data.credits
}));
console.log('Signed in!', data.is_new_user ? 'New user' : 'Existing user');
// Redirect or update UI
window.location.reload();
} else {
alert('Sign in failed: ' + (data.detail || 'Unknown error'));
}
} catch (error) {
console.error('Sign in error:', error);
alert('Sign in failed. Please try again.');
}
}
</script>
</body>
</html>
```
---
## Option B: Programmatic Sign-In
```javascript
const API_BASE = 'https://your-api-gateway.com';
// Initialize Google Sign-In
function initGoogleSignIn(clientId) {
google.accounts.id.initialize({
client_id: clientId,
callback: handleGoogleSignIn
});
// Render button in a container
google.accounts.id.renderButton(
document.getElementById('google-signin-btn'),
{ theme: 'outline', size: 'large', text: 'signin_with' }
);
}
// Handle the response
async function handleGoogleSignIn(response) {
const res = await fetch(`${API_BASE}/auth/google`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id_token: response.credential })
});
const data = await res.json();
if (data.success) {
localStorage.setItem('access_token', data.access_token);
}
}
// Call on page load
window.onload = () => initGoogleSignIn('YOUR_CLIENT_ID.apps.googleusercontent.com');
```
---
## Making API Calls
After sign-in, use the access token for all API calls:
```javascript
const API_BASE = 'https://your-api-gateway.com';
async function apiCall(endpoint, options = {}) {
const token = localStorage.getItem('access_token');
if (!token) {
throw new Error('Not signed in');
}
const response = await fetch(`${API_BASE}${endpoint}`, {
...options,
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json',
...options.headers
}
});
if (response.status === 401) {
// Token expired - need to sign in again
localStorage.removeItem('access_token');
window.location.href = '/login';
return;
}
return response.json();
}
// Examples
async function getCurrentUser() {
return apiCall('/auth/me');
}
async function generateText(prompt) {
return apiCall('/gemini/generate-text', {
method: 'POST',
body: JSON.stringify({ prompt })
});
}
async function checkJobStatus(jobId) {
return apiCall(`/gemini/job/${jobId}`);
}
```
---
## API Endpoints Reference
| Endpoint | Method | Auth Required | Description |
|----------|--------|---------------|-------------|
| `/auth/google` | POST | β | Sign in with Google token |
| `/auth/me` | GET | β
| Get current user info |
| `/auth/refresh` | POST | β | Refresh access token |
| `/gemini/generate-text` | POST | β
| Generate text (costs 1 credit) |
| `/gemini/generate-video` | POST | β
| Generate video (costs 1 credit) |
| `/gemini/job/{job_id}` | GET | β
| Check job status |
---
## Sign Out
```javascript
function signOut() {
localStorage.removeItem('access_token');
localStorage.removeItem('user');
// Optionally call logout endpoint for audit
fetch(`${API_BASE}/auth/logout`, {
method: 'POST',
headers: { 'Authorization': `Bearer ${token}` }
});
// Revoke Google session
google.accounts.id.disableAutoSelect();
window.location.href = '/';
}
```
---
## Error Handling
| Status | Meaning | Action |
|--------|---------|--------|
| 401 | Token expired/invalid | Redirect to sign-in |
| 402 | Insufficient credits | Show "buy credits" prompt |
| 429 | Rate limited | Wait and retry |
```javascript
async function apiCallWithErrorHandling(endpoint, options) {
const response = await apiCall(endpoint, options);
if (response.status === 402) {
alert('You have run out of credits!');
return null;
}
return response;
}
```
---
## React Example
```jsx
import { useEffect, useState } from 'react';
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
// Check if already signed in
const token = localStorage.getItem('access_token');
if (token) {
fetch('/auth/me', {
headers: { 'Authorization': `Bearer ${token}` }
})
.then(r => r.json())
.then(setUser)
.catch(() => localStorage.removeItem('access_token'));
}
// Initialize Google Sign-In
window.handleGoogleSignIn = async (response) => {
const res = await fetch('/auth/google', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id_token: response.credential })
});
const data = await res.json();
if (data.success) {
localStorage.setItem('access_token', data.access_token);
setUser(data);
}
};
}, []);
if (!user) {
return (
<div>
<div id="g_id_onload"
data-client_id="YOUR_CLIENT_ID"
data-callback="handleGoogleSignIn" />
<div className="g_id_signin" data-type="standard" />
</div>
);
}
return <div>Welcome, {user.name}! Credits: {user.credits}</div>;
}
```
|