Initial production setup with dual-token auth
This commit is contained in:
Binary file not shown.
|
After Width: | Height: | Size: 166 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.6 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 2.0 MiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.6 MiB |
@@ -0,0 +1,181 @@
|
||||
// PocketBase auth bootstrap shared by pages
|
||||
(function (global) {
|
||||
const pb = new PocketBase('https://pocketbase.ccllc.pro');
|
||||
const GRAPH_TOKEN_KEY = 'graphAccessToken';
|
||||
const USER_ID_KEY = 'userId';
|
||||
|
||||
function authHeaders() {
|
||||
if (pb.authStore.isValid && pb.authStore.token) {
|
||||
return { Authorization: `Bearer ${pb.authStore.token}` };
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
function getDisplayName() {
|
||||
const model = pb.authStore.model || {};
|
||||
return (
|
||||
model.display_name ||
|
||||
model.name ||
|
||||
model.email ||
|
||||
model.username ||
|
||||
'Unknown'
|
||||
);
|
||||
}
|
||||
|
||||
function getEmail() {
|
||||
const model = pb.authStore.model || {};
|
||||
return model.email || model.username || null;
|
||||
}
|
||||
|
||||
function getUserId() {
|
||||
return pb.authStore.model?.id || localStorage.getItem(USER_ID_KEY) || null;
|
||||
}
|
||||
|
||||
// Get Graph token - first from localStorage, then try to refresh from backend
|
||||
async function getGraphToken() {
|
||||
// First check localStorage
|
||||
let token = localStorage.getItem(GRAPH_TOKEN_KEY);
|
||||
|
||||
// If we have a valid PB session but no graph token, try to get from backend
|
||||
if (!token && pb.authStore.isValid) {
|
||||
try {
|
||||
const response = await fetch('/api/auth/refresh-token?type=graph', {
|
||||
headers: authHeaders()
|
||||
});
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.token) {
|
||||
token = data.token;
|
||||
localStorage.setItem(GRAPH_TOKEN_KEY, token);
|
||||
console.log('[Auth] Got Graph token from backend cache');
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[Auth] Could not get Graph token from backend:', err);
|
||||
}
|
||||
}
|
||||
|
||||
return token;
|
||||
}
|
||||
|
||||
// Synchronous version for backwards compatibility
|
||||
function getGraphTokenSync() {
|
||||
return localStorage.getItem(GRAPH_TOKEN_KEY);
|
||||
}
|
||||
|
||||
async function ensureAuth() {
|
||||
if (pb.authStore.isValid) {
|
||||
// Try to refresh tokens from backend on page load
|
||||
try {
|
||||
await refreshTokensFromBackend();
|
||||
} catch (err) {
|
||||
console.warn('[Auth] Token refresh failed:', err);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
const path = new URL(window.location.href).pathname;
|
||||
if (!path.endsWith('signin.html')) {
|
||||
window.location.href = 'signin.html';
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Refresh tokens from backend cache
|
||||
async function refreshTokensFromBackend() {
|
||||
if (!pb.authStore.isValid) return;
|
||||
|
||||
const userId = getUserId();
|
||||
if (!userId) return;
|
||||
|
||||
try {
|
||||
// Get fresh Graph token from backend
|
||||
const response = await fetch('/api/auth/refresh-token?type=graph', {
|
||||
headers: authHeaders()
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.token) {
|
||||
localStorage.setItem(GRAPH_TOKEN_KEY, data.token);
|
||||
console.log('[Auth] Refreshed Graph token from backend, source:', data.source);
|
||||
}
|
||||
} else if (response.status === 401) {
|
||||
// Token expired or invalid in backend, but we might still have a valid PB session
|
||||
// Try to re-store our current tokens
|
||||
console.log('[Auth] Backend token expired, attempting to re-store');
|
||||
await restoreTokensToBackend();
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[Auth] Token refresh error:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// Re-store tokens to backend (in case backend cache was cleared)
|
||||
async function restoreTokensToBackend() {
|
||||
if (!pb.authStore.isValid) return;
|
||||
|
||||
try {
|
||||
// Refresh PocketBase auth to potentially get a new Graph token
|
||||
const authData = await pb.collection('users').authRefresh();
|
||||
|
||||
const graphToken = extractGraphToken(authData) || localStorage.getItem(GRAPH_TOKEN_KEY);
|
||||
|
||||
if (graphToken) {
|
||||
const response = await fetch('/api/auth/login-callback', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
...authHeaders()
|
||||
},
|
||||
body: JSON.stringify({
|
||||
pbToken: pb.authStore.token,
|
||||
graphToken: graphToken,
|
||||
refreshTokenPb: '',
|
||||
refreshTokenGraph: authData?.meta?.refreshToken || '',
|
||||
user: {
|
||||
id: pb.authStore.model?.id,
|
||||
email: pb.authStore.model?.email,
|
||||
name: pb.authStore.model?.name || pb.authStore.model?.display_name
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
console.log('[Auth] Re-stored tokens in backend');
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[Auth] Failed to re-store tokens:', err);
|
||||
}
|
||||
}
|
||||
|
||||
function extractGraphToken(authData) {
|
||||
return (
|
||||
authData?.meta?.graphAccessToken ||
|
||||
authData?.meta?.graph_token ||
|
||||
authData?.meta?.graphToken ||
|
||||
authData?.meta?.accessToken ||
|
||||
authData?.meta?.access_token ||
|
||||
authData?.meta?.token ||
|
||||
authData?.meta?.rawToken ||
|
||||
authData?.meta?.authData?.access_token ||
|
||||
''
|
||||
);
|
||||
}
|
||||
|
||||
global.Auth = {
|
||||
pb,
|
||||
authHeaders,
|
||||
ensureAuth,
|
||||
getDisplayName,
|
||||
getEmail,
|
||||
getUserId,
|
||||
getGraphToken,
|
||||
getGraphTokenSync,
|
||||
refreshTokensFromBackend,
|
||||
restoreTokensToBackend,
|
||||
extractGraphToken,
|
||||
GRAPH_TOKEN_KEY,
|
||||
USER_ID_KEY
|
||||
};
|
||||
})(window);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,5 @@
|
||||
/* Generated Tailwind CSS - Basic version */
|
||||
/* This will be updated by tailwind CLI on dev */
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
@@ -0,0 +1,176 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Sign In - Job Info</title>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<script src="https://cdn.jsdelivr.net/npm/pocketbase@0.26.5/dist/pocketbase.umd.js"></script>
|
||||
</head>
|
||||
<body class="font-sans bg-gradient-to-br from-indigo-500 to-purple-600 min-h-screen flex items-center justify-center">
|
||||
<div class="bg-white p-12 rounded-2xl shadow-2xl text-center max-w-md w-[90%]">
|
||||
<h1 class="text-gray-800 mb-2 text-3xl font-bold">Job Info</h1>
|
||||
<p class="text-gray-600 mb-8">Sign in with your Microsoft account</p>
|
||||
|
||||
<button id="loginBtn" onclick="login()"
|
||||
class="bg-purple-600 text-white border-none py-3.5 px-8 text-base rounded-lg cursor-pointer transition-all duration-200 font-medium hover:bg-purple-700 hover:shadow-lg disabled:bg-gray-400 disabled:cursor-not-allowed w-full">
|
||||
Sign in with Microsoft
|
||||
</button>
|
||||
|
||||
<div class="text-red-600 mt-4 hidden text-sm" id="error"></div>
|
||||
|
||||
<div class="hidden mt-8 text-left bg-gray-50 p-6 rounded-lg" id="userInfo">
|
||||
<h2 class="text-lg mb-4 text-gray-800 font-semibold">✓ Signed In</h2>
|
||||
<p class="mb-3 text-gray-600"><strong class="text-gray-800">Name:</strong> <span id="displayName"></span></p>
|
||||
<p class="mb-3 text-gray-600"><strong class="text-gray-800">Email:</strong> <span id="email"></span></p>
|
||||
|
||||
<button onclick="goToApp()"
|
||||
class="mt-4 bg-purple-600 text-white border-none py-3 px-6 text-base rounded-lg cursor-pointer transition-all duration-200 font-medium hover:bg-purple-700 hover:shadow-lg w-full">
|
||||
Continue to App →
|
||||
</button>
|
||||
|
||||
<button onclick="logout()"
|
||||
class="mt-3 bg-gray-200 text-gray-700 border-none py-2.5 px-6 text-sm rounded-lg cursor-pointer transition-all duration-200 hover:bg-gray-300 w-full">
|
||||
Sign out
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const pb = new PocketBase('https://pocketbase.ccllc.pro');
|
||||
|
||||
const loginBtn = document.getElementById('loginBtn');
|
||||
const errorEl = document.getElementById('error');
|
||||
const userInfo = document.getElementById('userInfo');
|
||||
|
||||
function goToApp() {
|
||||
window.location.href = 'index.html';
|
||||
}
|
||||
|
||||
function showError(msg) {
|
||||
errorEl.textContent = msg;
|
||||
errorEl.classList.remove('hidden');
|
||||
}
|
||||
|
||||
function hideError() {
|
||||
errorEl.classList.add('hidden');
|
||||
}
|
||||
|
||||
// Extract Graph token from OAuth response
|
||||
function extractGraphToken(authData) {
|
||||
return authData?.meta?.accessToken ||
|
||||
authData?.meta?.access_token ||
|
||||
authData?.meta?.graphAccessToken ||
|
||||
authData?.meta?.token ||
|
||||
'';
|
||||
}
|
||||
|
||||
// Store tokens in backend Redis cache
|
||||
async function storeTokensInBackend(authData, graphToken) {
|
||||
const userId = pb.authStore.model?.id;
|
||||
if (!userId) return false;
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/auth/login-callback', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${pb.authStore.token}`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
pbToken: pb.authStore.token,
|
||||
graphToken: graphToken,
|
||||
refreshTokenPb: '',
|
||||
refreshTokenGraph: authData?.meta?.refreshToken || '',
|
||||
user: {
|
||||
id: userId,
|
||||
email: pb.authStore.model?.email || '',
|
||||
name: pb.authStore.model?.name || pb.authStore.model?.display_name || ''
|
||||
}
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
console.log('[Auth] Tokens stored in backend');
|
||||
return true;
|
||||
} else {
|
||||
console.warn('[Auth] Backend storage failed:', response.status);
|
||||
return false;
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[Auth] Backend error:', err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function showAuthedUI() {
|
||||
const model = pb.authStore.model;
|
||||
loginBtn.classList.add('hidden');
|
||||
userInfo.classList.remove('hidden');
|
||||
document.getElementById('displayName').textContent = model?.name || model?.display_name || 'User';
|
||||
document.getElementById('email').textContent = model?.email || '';
|
||||
}
|
||||
|
||||
async function login() {
|
||||
loginBtn.disabled = true;
|
||||
loginBtn.textContent = 'Signing in...';
|
||||
hideError();
|
||||
|
||||
try {
|
||||
const authData = await pb.collection('users').authWithOAuth2({ provider: 'microsoft' });
|
||||
const graphToken = extractGraphToken(authData);
|
||||
|
||||
// Store in backend cache for persistence
|
||||
// Store in localStorage for index.html to find
|
||||
if (graphToken) localStorage.setItem('graphAccessToken', graphToken);
|
||||
await storeTokensInBackend(authData, graphToken);
|
||||
|
||||
showAuthedUI();
|
||||
} catch (error) {
|
||||
console.error('Login failed:', error);
|
||||
showError(error.message || 'Authentication failed');
|
||||
loginBtn.disabled = false;
|
||||
loginBtn.textContent = 'Sign in with Microsoft';
|
||||
}
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
try {
|
||||
await fetch('/api/auth/logout', {
|
||||
method: 'POST',
|
||||
headers: { 'Authorization': `Bearer ${pb.authStore.token}` }
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn('[Auth] Logout error:', err);
|
||||
}
|
||||
|
||||
pb.authStore.clear();
|
||||
loginBtn.classList.remove('hidden');
|
||||
loginBtn.disabled = false;
|
||||
loginBtn.textContent = 'Sign in with Microsoft';
|
||||
userInfo.classList.add('hidden');
|
||||
}
|
||||
|
||||
// Check existing session on load
|
||||
async function checkSession() {
|
||||
if (!pb.authStore.isValid) return;
|
||||
|
||||
try {
|
||||
await pb.collection('users').authRefresh();
|
||||
showAuthedUI();
|
||||
|
||||
// Check if coming from reauth flow
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (params.get('reauth') === '1') {
|
||||
goToApp();
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('[Auth] Session expired');
|
||||
pb.authStore.clear();
|
||||
}
|
||||
}
|
||||
|
||||
checkSession();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user