83 lines
2.5 KiB
TypeScript
83 lines
2.5 KiB
TypeScript
import { Hono } from 'hono';
|
|
import type { Context } from 'hono';
|
|
import { getTokens, saveTokens, clearTokens, hasValidPbToken } from './token-service';
|
|
|
|
// Authentication API routes
|
|
// Endpoints for frontend to check auth status, get tokens, logout
|
|
|
|
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 hasValid = await hasValidPbToken();
|
|
return c.json({
|
|
authenticated: hasValid,
|
|
pbTokenValid: hasValid,
|
|
message: hasValid ? 'User authenticated' : 'User not authenticated'
|
|
});
|
|
});
|
|
|
|
// 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 hasValid = await hasValidPbToken();
|
|
if (!hasValid) {
|
|
return c.json({ error: 'Not authenticated' }, 401);
|
|
}
|
|
|
|
const tokens = await getTokens();
|
|
return c.json({
|
|
pbToken: tokens?.pbToken || null,
|
|
graphToken: tokens?.graphToken || null,
|
|
pbTokenExpiry: tokens?.pbTokenExpiry || null,
|
|
graphTokenExpiry: tokens?.graphTokenExpiry || null
|
|
});
|
|
});
|
|
|
|
// 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 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 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;
|
|
}
|