import { Hono } from 'hono'; import type { Context } from 'hono'; import { tokenService } from './token-service'; // Authentication API routes // Endpoints for frontend to check auth status, get tokens, logout // Depends on: tokenService singleton (centralized token management) export function createAuthRoutes(): Hono { const router = new Hono(); // PERMANENT: Check if user is authenticated // Returns current auth status and which tokens are available router.get('/status', async (c: Context) => { const tokens = await tokenService.getTokens(); const hasToken = !!tokens?.pbToken; return c.json({ authenticated: hasToken, pbTokenValid: hasToken, assumedFresh: hasToken, message: hasToken ? 'Assuming tokens are valid (auto-refresh running)' : 'No PB token yet; login once' }); }); // PERMANENT: Get current tokens // Frontend/backend can call this to get fresh token state // Only returns tokens if PB token is valid (auth required) router.get('/tokens', async (c: Context) => { const tokens = await tokenService.getTokens(); return c.json({ pbToken: tokens?.pbToken || null, graphToken: tokens?.graphToken || null, pbTokenExpiry: tokens?.pbTokenExpiry || null, graphTokenExpiry: tokens?.graphTokenExpiry || null, lastRefresh: tokens?.lastRefresh || null, assumedFresh: !!tokens?.pbToken }); }); // PERMANENT: Handle login callback from OAuth2 // Frontend sends back the PB auth response after successful login // Stores both PB and Graph tokens router.post('/login', async (c: Context) => { try { const body = await c.req.json() as any; const pbToken = body.pbToken; const graphToken = body.graphToken; if (!pbToken) { return c.json({ error: 'Missing pbToken' }, 400); } await tokenService.saveTokens(pbToken, graphToken); return c.json({ success: true, message: 'Login successful', authenticated: true }); } catch (err) { console.log('[AuthAndToken] Login error:', (err as Error)?.message); return c.json({ error: 'Login failed' }, 500); } }); // PERMANENT: Logout - clear all tokens // Called when user clicks logout router.post('/logout', async (c: Context) => { try { await tokenService.clearTokens(); return c.json({ success: true, message: 'Logged out', authenticated: false }); } catch (err) { console.log('[AuthAndToken] Logout error:', (err as Error)?.message); return c.json({ error: 'Logout failed' }, 500); } }); return router; }