auth-service / test-client.html
seraj-b2
Harden JSON parsing and error middleware
f5c3825
Raw History Blame Contribute Delete
11.3 kB
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Google Auth Backend Tester</title>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<style>
:root {
--bg: #0f172a;
--card-bg: #1e293b;
--text: #f8fafc;
--muted: #94a3b8;
--primary: #3b82f6;
--primary-hover: #2563eb;
--success: #10b981;
--error: #ef4444;
--border: #334155;
}
* { box-sizing: border-box; margin: 0; padding: 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; }
body { background-color: var(--bg); color: var(--text); padding: 2rem; min-height: 100vh; display: flex; flex-direction: column; align-items: center; }
.container { width: 100%; max-width: 800px; display: flex; flex-direction: column; gap: 1.5rem; }
.card { background-color: var(--card-bg); border: 1px solid var(--border); border-radius: 12px; padding: 1.5rem; box-shadow: 0 10px 15px -3px rgba(0, 0, 0, 0.3); }
h1 { font-size: 1.5rem; font-weight: 700; display: flex; align-items: center; gap: 0.5rem; }
p.subtitle { color: var(--muted); font-size: 0.9rem; margin-top: 0.25rem; }
.form-group { display: flex; flex-direction: column; gap: 0.5rem; margin-top: 1rem; }
label { font-size: 0.85rem; font-weight: 600; color: var(--muted); }
input { background: #0f172a; border: 1px solid var(--border); border-radius: 8px; padding: 0.75rem 1rem; color: #fff; font-size: 0.95rem; outline: none; }
input:focus { border-color: var(--primary); }
.btn-row { display: flex; gap: 0.75rem; flex-wrap: wrap; margin-top: 1rem; }
button { background: var(--primary); color: #fff; border: none; border-radius: 8px; padding: 0.75rem 1.25rem; font-weight: 600; cursor: pointer; transition: background 0.2s; }
button:hover { background: var(--primary-hover); }
button.btn-secondary { background: #334155; }
button.btn-secondary:hover { background: #475569; }
button.btn-danger { background: var(--error); }
button.btn-danger:hover { background: #dc2626; }
button:disabled { opacity: 0.5; cursor: not-allowed; }
.user-profile { display: flex; align-items: center; gap: 1rem; background: #0f172a; border-radius: 8px; padding: 1rem; border: 1px solid var(--border); margin-top: 1rem; }
.avatar { width: 48px; height: 48px; border-radius: 50%; border: 2px solid var(--primary); object-fit: cover; }
.badge { display: inline-block; padding: 0.2rem 0.5rem; border-radius: 4px; font-size: 0.75rem; font-weight: bold; background: #1e3a8a; color: #93c5fd; }
pre { background: #090d16; border: 1px solid var(--border); border-radius: 8px; padding: 1rem; overflow-x: auto; font-size: 0.85rem; color: #38bdf8; max-height: 350px; }
.status-pill { display: inline-flex; align-items: center; gap: 0.4rem; font-size: 0.8rem; font-weight: 600; padding: 0.25rem 0.6rem; border-radius: 9999px; }
.status-ok { background: rgba(16, 185, 129, 0.2); color: var(--success); }
</style>
</head>
<body>
<div class="container">
<div class="card">
<div style="display: flex; justify-content: space-between; align-items: center;">
<div>
<h1>🔐 Google Auth Backend Tester</h1>
<p class="subtitle">Test live authentication, token issuance, and validation against your Hugging Face Space</p>
</div>
<span class="status-pill status-ok" id="backendStatus">● Checking API...</span>
</div>
<div class="form-group">
<label for="apiUrl">Backend API URL</label>
<input type="text" id="apiUrl" value="https://its-seraj-auth-service.hf.space">
</div>
<div class="form-group">
<label for="clientId">Google OAuth Client ID</label>
<input type="text" id="clientId" placeholder="Paste your Google Client ID here (e.g. 12345...apps.googleusercontent.com)">
</div>
<div style="margin-top: 1rem;">
<button id="initBtn" onclick="initGoogleSignIn()">Initialize Google Button</button>
</div>
<div id="googleBtnContainer" style="margin-top: 1.25rem; min-height: 44px;"></div>
</div>
<div class="card" id="sessionCard" style="display: none;">
<h2>Active Session</h2>
<div id="profileContainer"></div>
<div class="btn-row">
<button onclick="callGetMe()">1. GET /api/auth/me</button>
<button onclick="callVerify()">2. POST /api/auth/verify</button>
<button class="btn-secondary" onclick="callRefresh()">3. POST /api/auth/refresh</button>
<button class="btn-danger" onclick="callLogout()">4. POST /api/auth/logout</button>
</div>
</div>
<div class="card">
<div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5rem;">
<h3>API Response Log</h3>
<button class="btn-secondary" style="padding: 0.35rem 0.75rem; font-size: 0.8rem;" onclick="clearLog()">Clear</button>
</div>
<pre id="logOutput">// API responses will appear here...</pre>
</div>
</div>
<script>
let currentTokens = {
accessToken: null,
refreshToken: null
};
const logOutput = document.getElementById('logOutput');
const backendStatus = document.getElementById('backendStatus');
function log(title, data) {
const timestamp = new Date().toLocaleTimeString();
logOutput.textContent = `=== [${timestamp}] ${title} ===\n` + JSON.stringify(data, null, 2);
}
function clearLog() {
logOutput.textContent = '// Log cleared.';
}
// Health check on load
async function checkHealth() {
const baseUrl = document.getElementById('apiUrl').value.replace(/\/$/, '');
try {
const res = await fetch(`${baseUrl}/health`);
const data = await res.json();
if (res.ok && data.status === 'ok') {
backendStatus.className = 'status-pill status-ok';
backendStatus.textContent = `● Connected (${data.database})`;
} else {
backendStatus.textContent = '● Degraded';
}
} catch (err) {
backendStatus.textContent = '● Offline / Error';
backendStatus.style.color = '#ef4444';
}
}
checkHealth();
function initGoogleSignIn() {
const clientId = document.getElementById('clientId').value.trim();
if (!clientId) {
alert('Please enter your Google Client ID first');
return;
}
if (typeof google === 'undefined') {
alert('Google Identity Services SDK not loaded. Check internet connection.');
return;
}
google.accounts.id.initialize({
client_id: clientId,
callback: handleCredentialResponse
});
google.accounts.id.renderButton(
document.getElementById('googleBtnContainer'),
{ theme: 'outline', size: 'large', type: 'standard', text: 'continue_with', shape: 'pill' }
);
log('Google SDK Initialized', { clientId });
}
async function handleCredentialResponse(response) {
const idToken = response.credential;
log('Google ID Token Received', { idTokenPreview: idToken.substring(0, 30) + '...' });
const baseUrl = document.getElementById('apiUrl').value.replace(/\/$/, '');
try {
const res = await fetch(`${baseUrl}/api/auth/google`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ idToken })
});
const data = await res.json();
log('POST /api/auth/google Response', data);
if (res.ok && data.success) {
currentTokens.accessToken = data.data.accessToken;
currentTokens.refreshToken = data.data.refreshToken;
displayProfile(data.data.user);
} else {
alert('Authentication failed: ' + (data.error?.message || 'Unknown error'));
}
} catch (err) {
log('Network Error on /api/auth/google', { error: err.message });
}
}
function displayProfile(user) {
document.getElementById('sessionCard').style.display = 'block';
const container = document.getElementById('profileContainer');
container.innerHTML = `
<div class="user-profile">
${user.picture ? `<img src="${user.picture}" class="avatar" alt="Avatar">` : ''}
<div>
<div style="font-weight: 700; font-size: 1.1rem;">${user.name}</div>
<div style="color: var(--muted); font-size: 0.9rem;">${user.email}</div>
<div style="margin-top: 0.35rem;">
<span class="badge">${user.roles.join(', ')}</span>
<span style="font-size: 0.8rem; color: var(--muted); margin-left: 0.5rem;">ID: ${user.id}</span>
</div>
</div>
</div>
`;
}
async function callGetMe() {
if (!currentTokens.accessToken) return alert('No access token available. Please sign in first.');
const baseUrl = document.getElementById('apiUrl').value.replace(/\/$/, '');
const res = await fetch(`${baseUrl}/api/auth/me`, {
method: 'GET',
headers: { 'Authorization': `Bearer ${currentTokens.accessToken}` }
});
const data = await res.json();
log('GET /api/auth/me', data);
}
async function callVerify() {
if (!currentTokens.accessToken) return alert('No access token available. Please sign in first.');
const baseUrl = document.getElementById('apiUrl').value.replace(/\/$/, '');
const res = await fetch(`${baseUrl}/api/auth/verify`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${currentTokens.accessToken}`,
'Content-Type': 'application/json'
}
});
const data = await res.json();
log('POST /api/auth/verify', data);
}
async function callRefresh() {
if (!currentTokens.refreshToken) return alert('No refresh token available. Please sign in first.');
const baseUrl = document.getElementById('apiUrl').value.replace(/\/$/, '');
const res = await fetch(`${baseUrl}/api/auth/refresh`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ refreshToken: currentTokens.refreshToken })
});
const data = await res.json();
log('POST /api/auth/refresh', data);
if (res.ok && data.success) {
currentTokens.accessToken = data.data.accessToken;
currentTokens.refreshToken = data.data.refreshToken;
}
}
async function callLogout() {
const baseUrl = document.getElementById('apiUrl').value.replace(/\/$/, '');
const res = await fetch(`${baseUrl}/api/auth/logout`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify({ refreshToken: currentTokens.refreshToken })
});
const data = await res.json();
log('POST /api/auth/logout', data);
currentTokens = { accessToken: null, refreshToken: null };
document.getElementById('sessionCard').style.display = 'none';
alert('Logged out successfully.');
}
</script>
</body>
</html>