dock config to postgres, auto-add /email on google oauth, improved email empty state
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,12 +1,21 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { ChevronLeft, ChevronRight, Loader2, Mail, Paperclip, RefreshCw } from 'lucide-react';
|
||||
import { toast } from 'sonner';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { useClient } from 'hooks/useClient';
|
||||
import { useGlobal } from 'hooks/useGlobal';
|
||||
import { useJobs } from 'hooks/useJobs';
|
||||
import type { EmailSummary } from 'types';
|
||||
|
||||
type GoogleStatus = {
|
||||
configured: boolean;
|
||||
connected: boolean;
|
||||
email: string | null;
|
||||
picture: string | null;
|
||||
};
|
||||
|
||||
const LIMIT = 50;
|
||||
|
||||
const formatDate = (iso: string) => {
|
||||
@@ -27,6 +36,11 @@ export const EmailList = () => {
|
||||
const { jobs, createJob } = useJobs({ type: 'gmail-sync' });
|
||||
const isSyncing = jobs.some((j) => j.status === 'queued' || j.status === 'running');
|
||||
|
||||
const { data: googleStatus } = useQuery({
|
||||
queryKey: ['google-status'],
|
||||
queryFn: () => client.get<GoogleStatus>('/integrations/google/status'),
|
||||
});
|
||||
|
||||
const { data, isLoading } = useQuery({
|
||||
queryKey: ['email-messages', page],
|
||||
queryFn: () =>
|
||||
@@ -65,9 +79,26 @@ export const EmailList = () => {
|
||||
|
||||
if (messages.length === 0 && page === 1) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-2 text-sm opacity-50">
|
||||
<div className="flex h-full flex-col items-center justify-center gap-3 text-sm opacity-50">
|
||||
<Mail className="h-8 w-8" />
|
||||
No emails found
|
||||
{googleStatus && !googleStatus.configured ? (
|
||||
<span>Google integration not configured. Contact your administrator.</span>
|
||||
) : googleStatus && !googleStatus.connected ? (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<span>Connect your Google account to sync emails</span>
|
||||
<Button variant="outline" size="sm" asChild>
|
||||
<Link to="/settings/integrations">Connect Google</Link>
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col items-center gap-2">
|
||||
<span>No emails synced yet</span>
|
||||
<Button variant="outline" size="sm" onClick={handleSync} disabled={isSyncing}>
|
||||
{isSyncing ? <Loader2 className="mr-2 h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="mr-2 h-3.5 w-3.5" />}
|
||||
Sync Now
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
export {
|
||||
initAuthStore,
|
||||
getUsers,
|
||||
getUserById,
|
||||
getUserByEmail,
|
||||
@@ -7,8 +6,8 @@ export {
|
||||
createUser,
|
||||
updateUser,
|
||||
deleteUser,
|
||||
getPasskeysByEmail,
|
||||
getPasskeysByEmailAndOrigin,
|
||||
getPasskeysByUserId,
|
||||
getPasskeysByUserIdAndOrigin,
|
||||
getPasskeyByCredentialId,
|
||||
createPasskey,
|
||||
updatePasskey,
|
||||
@@ -17,4 +16,22 @@ export {
|
||||
blacklistToken,
|
||||
isTokenBlacklisted,
|
||||
cleanupExpiredTokens,
|
||||
} from './store';
|
||||
} from './queries/auth';
|
||||
|
||||
export { readServerSettings, writeServerSettings } from './queries/server-config';
|
||||
|
||||
export { getUserSettings, setUserSettings, getUserState, patchUserState, getDockPaths, setDockPaths } from './queries/user-data';
|
||||
|
||||
export {
|
||||
getServerIntegrations,
|
||||
getServerIntegration,
|
||||
upsertServerIntegration,
|
||||
deleteServerIntegration,
|
||||
getUserIntegrations,
|
||||
getUserIntegration,
|
||||
upsertUserIntegration,
|
||||
deleteUserIntegration,
|
||||
} from './queries/integrations';
|
||||
|
||||
export { db } from './db';
|
||||
export * as schema from './schema';
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
import { eq } from 'drizzle-orm';
|
||||
import { db } from '../db';
|
||||
import { dockConfigs, userSettings, userState } from '../schema';
|
||||
|
||||
// ── User Settings ──
|
||||
|
||||
export async function getUserSettings(userId: number): Promise<Record<string, unknown>> {
|
||||
const [row] = await db.select().from(userSettings).where(eq(userSettings.userId, userId));
|
||||
return (row?.settings as Record<string, unknown>) ?? {};
|
||||
}
|
||||
|
||||
export async function setUserSettings(userId: number, settings: Record<string, unknown>): Promise<void> {
|
||||
await db
|
||||
.insert(userSettings)
|
||||
.values({ userId, settings, updatedAt: new Date() })
|
||||
.onConflictDoUpdate({
|
||||
target: userSettings.userId,
|
||||
set: { settings, updatedAt: new Date() },
|
||||
});
|
||||
}
|
||||
|
||||
// ── User State ──
|
||||
|
||||
export async function getUserState(userId: number): Promise<Record<string, unknown>> {
|
||||
const [row] = await db.select().from(userState).where(eq(userState.userId, userId));
|
||||
return (row?.state as Record<string, unknown>) ?? {};
|
||||
}
|
||||
|
||||
export async function patchUserState(userId: number, patch: Record<string, unknown>): Promise<Record<string, unknown>> {
|
||||
const current = await getUserState(userId);
|
||||
const merged = { ...current, ...patch };
|
||||
await db
|
||||
.insert(userState)
|
||||
.values({ userId, state: merged, updatedAt: new Date() })
|
||||
.onConflictDoUpdate({
|
||||
target: userState.userId,
|
||||
set: { state: merged, updatedAt: new Date() },
|
||||
});
|
||||
return merged;
|
||||
}
|
||||
|
||||
// ── Dock Config ──
|
||||
|
||||
export async function getDockPaths(userId: number): Promise<string[] | null> {
|
||||
const [row] = await db.select().from(dockConfigs).where(eq(dockConfigs.userId, userId));
|
||||
return (row?.paths as string[]) ?? null;
|
||||
}
|
||||
|
||||
export async function setDockPaths(userId: number, paths: string[]): Promise<void> {
|
||||
await db
|
||||
.insert(dockConfigs)
|
||||
.values({ userId, paths, updatedAt: new Date() })
|
||||
.onConflictDoUpdate({
|
||||
target: dockConfigs.userId,
|
||||
set: { paths, updatedAt: new Date() },
|
||||
});
|
||||
}
|
||||
@@ -1,36 +1,19 @@
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import { createRouter } from '../../create-router';
|
||||
import { getUserDockFile } from '@@/data-path';
|
||||
|
||||
const ensureDir = (filePath: string) => mkdir(dirname(filePath), { recursive: true });
|
||||
import { getDockPaths, setDockPaths } from 'officerdb';
|
||||
|
||||
export const dockRouter = createRouter();
|
||||
|
||||
// GET / — return dock.json, or null if it doesn't exist (frontend uses defaults)
|
||||
// GET / — return dock paths, or null if none saved (frontend uses defaults)
|
||||
dockRouter.get('/', async (ctx) => {
|
||||
const email = ctx.get('user').email;
|
||||
const filePath = getUserDockFile(email);
|
||||
const file = Bun.file(filePath);
|
||||
|
||||
if (await file.exists()) {
|
||||
try {
|
||||
return ctx.json(await file.json());
|
||||
} catch {
|
||||
// corrupted file — treat as missing
|
||||
}
|
||||
}
|
||||
|
||||
return ctx.json(null);
|
||||
const userId = ctx.get('user').id;
|
||||
const paths = await getDockPaths(userId);
|
||||
return ctx.json(paths);
|
||||
});
|
||||
|
||||
// PUT / — full replacement of dock paths array
|
||||
dockRouter.put('/', async (ctx) => {
|
||||
const email = ctx.get('user').email;
|
||||
const body = ctx.get('body');
|
||||
const filePath = getUserDockFile(email);
|
||||
|
||||
await ensureDir(filePath);
|
||||
await Bun.write(filePath, JSON.stringify(body, null, 2));
|
||||
return ctx.json(body);
|
||||
const userId = ctx.get('user').id;
|
||||
const paths = ctx.get('body') as string[];
|
||||
await setDockPaths(userId, paths);
|
||||
return ctx.json(paths);
|
||||
});
|
||||
|
||||
@@ -1,10 +1,15 @@
|
||||
import { mkdir } from 'node:fs/promises';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { createRouter } from '../../create-router';
|
||||
import { DATA_PATH, SERVER_CONFIG_DIR } from '@@/data-path';
|
||||
import { CustomError } from '../../custom-errors';
|
||||
|
||||
const googleConfigPath = join(SERVER_CONFIG_DIR, 'google-oauth.json');
|
||||
import { FORBIDDEN, BAD_REQUEST } from '../../custom-errors';
|
||||
import {
|
||||
getServerIntegration,
|
||||
upsertServerIntegration,
|
||||
getUserByEmail,
|
||||
getUserIntegration,
|
||||
upsertUserIntegration,
|
||||
deleteUserIntegration,
|
||||
getDockPaths,
|
||||
setDockPaths,
|
||||
} from 'officerdb';
|
||||
|
||||
const GOOGLE_SCOPES = [
|
||||
'https://www.googleapis.com/auth/gmail.readonly',
|
||||
@@ -12,30 +17,14 @@ const GOOGLE_SCOPES = [
|
||||
'https://www.googleapis.com/auth/userinfo.email',
|
||||
];
|
||||
|
||||
const ensureDir = (filePath: string) => mkdir(dirname(filePath), { recursive: true });
|
||||
type GoogleConfig = { clientId: string; clientSecret: string };
|
||||
|
||||
export const readGoogleConfig = async () => {
|
||||
try {
|
||||
return await Bun.file(googleConfigPath).json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const getUserGoogleFile = (email: string) => join(DATA_PATH, email, 'integrations', 'google.json');
|
||||
|
||||
const readUserGoogle = async (email: string) => {
|
||||
try {
|
||||
return await Bun.file(getUserGoogleFile(email)).json();
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const writeUserGoogle = async (email: string, data: Record<string, unknown>) => {
|
||||
const filePath = getUserGoogleFile(email);
|
||||
await ensureDir(filePath);
|
||||
await Bun.write(filePath, JSON.stringify(data, null, 2));
|
||||
export const readGoogleConfig = async (): Promise<GoogleConfig | null> => {
|
||||
const integration = await getServerIntegration('google');
|
||||
if (!integration) return null;
|
||||
const config = integration.config as Record<string, unknown>;
|
||||
if (!config.clientId || !config.clientSecret) return null;
|
||||
return config as unknown as GoogleConfig;
|
||||
};
|
||||
|
||||
export const integrationsRouter = createRouter();
|
||||
@@ -48,33 +37,30 @@ integrationsRouter.get('/', async (ctx) => {
|
||||
|
||||
integrationsRouter.get('/google/config', async (ctx) => {
|
||||
const user = ctx.get('user');
|
||||
if (user.role !== 'Super Admin') throw new CustomError('Forbidden', 403);
|
||||
if (user.role !== 'Super Admin') throw FORBIDDEN();
|
||||
return ctx.json(await readGoogleConfig());
|
||||
});
|
||||
|
||||
integrationsRouter.put('/google/config', async (ctx) => {
|
||||
const user = ctx.get('user');
|
||||
if (user.role !== 'Super Admin') throw new CustomError('Forbidden', 403);
|
||||
if (user.role !== 'Super Admin') throw FORBIDDEN();
|
||||
|
||||
const body = ctx.get('body') as { clientId?: string; clientSecret?: string };
|
||||
const config = { clientId: body.clientId ?? '', clientSecret: body.clientSecret ?? '' };
|
||||
|
||||
await ensureDir(googleConfigPath);
|
||||
await Bun.write(googleConfigPath, JSON.stringify(config, null, 2));
|
||||
await upsertServerIntegration('google', config);
|
||||
return ctx.json(config);
|
||||
});
|
||||
|
||||
integrationsRouter.get('/google/verify', async (ctx) => {
|
||||
const user = ctx.get('user');
|
||||
if (user.role !== 'Super Admin') throw new CustomError('Forbidden', 403);
|
||||
if (user.role !== 'Super Admin') throw FORBIDDEN();
|
||||
|
||||
const config = await readGoogleConfig();
|
||||
if (!config?.clientId || !config?.clientSecret) {
|
||||
return ctx.json({ valid: false, error: 'Missing credentials' });
|
||||
}
|
||||
|
||||
// Send a dummy token exchange — valid credentials return "invalid_grant",
|
||||
// invalid credentials return "invalid_client"
|
||||
const res = await fetch('https://oauth2.googleapis.com/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
@@ -96,27 +82,22 @@ integrationsRouter.get('/google/verify', async (ctx) => {
|
||||
// --- Personal: Google account connection status ---
|
||||
|
||||
integrationsRouter.get('/google/status', async (ctx) => {
|
||||
const email = ctx.get('user').email;
|
||||
const user = ctx.get('user');
|
||||
const config = await readGoogleConfig();
|
||||
const connection = await readUserGoogle(email);
|
||||
const connection = await getUserIntegration(user.id, 'google');
|
||||
const connConfig = connection?.config as Record<string, unknown> | undefined;
|
||||
|
||||
return ctx.json({
|
||||
configured: !!(config?.clientId && config?.clientSecret),
|
||||
connected: !!connection?.accessToken,
|
||||
email: connection?.email ?? null,
|
||||
picture: connection?.picture ?? null,
|
||||
connected: !!connConfig?.accessToken,
|
||||
email: connConfig?.email ?? null,
|
||||
picture: connConfig?.picture ?? null,
|
||||
});
|
||||
});
|
||||
|
||||
integrationsRouter.delete('/google/connection', async (ctx) => {
|
||||
const email = ctx.get('user').email;
|
||||
const filePath = getUserGoogleFile(email);
|
||||
|
||||
const file = Bun.file(filePath);
|
||||
if (await file.exists()) {
|
||||
await Bun.write(filePath, '{}');
|
||||
}
|
||||
|
||||
const user = ctx.get('user');
|
||||
await deleteUserIntegration(user.id, 'google');
|
||||
return ctx.json({ ok: true });
|
||||
});
|
||||
|
||||
@@ -125,12 +106,12 @@ integrationsRouter.delete('/google/connection', async (ctx) => {
|
||||
integrationsRouter.get('/google/authorize', async (ctx) => {
|
||||
const config = await readGoogleConfig();
|
||||
if (!config?.clientId || !config?.clientSecret) {
|
||||
throw new CustomError('Google OAuth not configured', 400);
|
||||
throw BAD_REQUEST('Google OAuth not configured');
|
||||
}
|
||||
|
||||
const email = ctx.get('user').email;
|
||||
const origin = ctx.req.query('origin');
|
||||
if (!origin) throw new CustomError('Missing origin parameter', 400);
|
||||
if (!origin) throw BAD_REQUEST('Missing origin parameter');
|
||||
const redirectUri = `${origin}/api/integrations/google/callback`;
|
||||
|
||||
const state = Buffer.from(JSON.stringify({ email, redirectUri })).toString('base64url');
|
||||
@@ -174,7 +155,6 @@ export const googleCallbackHandler = async (ctx: any) => {
|
||||
return ctx.redirect('/settings/integrations?google=error');
|
||||
}
|
||||
|
||||
// Exchange code for tokens
|
||||
const tokenResponse = await fetch('https://oauth2.googleapis.com/token', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
@@ -194,7 +174,6 @@ export const googleCallbackHandler = async (ctx: any) => {
|
||||
|
||||
const tokens = await tokenResponse.json();
|
||||
|
||||
// Fetch the user's Google email
|
||||
const userinfoResponse = await fetch('https://www.googleapis.com/oauth2/v2/userinfo', {
|
||||
headers: { Authorization: `Bearer ${tokens.access_token}` },
|
||||
});
|
||||
@@ -207,14 +186,39 @@ export const googleCallbackHandler = async (ctx: any) => {
|
||||
picture = userinfo.picture ?? null;
|
||||
}
|
||||
|
||||
await writeUserGoogle(email, {
|
||||
accessToken: tokens.access_token,
|
||||
refreshToken: tokens.refresh_token,
|
||||
expiresAt: Date.now() + tokens.expires_in * 1000,
|
||||
email: googleEmail,
|
||||
picture,
|
||||
scope: tokens.scope,
|
||||
const dbUser = await getUserByEmail(email);
|
||||
if (!dbUser) {
|
||||
return ctx.redirect('/settings/integrations?google=error');
|
||||
}
|
||||
|
||||
const serverIntegration = await getServerIntegration('google');
|
||||
|
||||
await upsertUserIntegration({
|
||||
userId: dbUser.id,
|
||||
provider: 'google',
|
||||
serverIntegrationId: serverIntegration?.id,
|
||||
config: {
|
||||
accessToken: tokens.access_token,
|
||||
refreshToken: tokens.refresh_token,
|
||||
expiresAt: Date.now() + tokens.expires_in * 1000,
|
||||
email: googleEmail,
|
||||
picture,
|
||||
scope: tokens.scope,
|
||||
},
|
||||
});
|
||||
|
||||
// Auto-add /email to dock
|
||||
try {
|
||||
const existing = await getDockPaths(dbUser.id);
|
||||
const paths = existing ?? ['/', '/files', '/automation', '/projects', '/workspaces', '/chat'];
|
||||
|
||||
if (!paths.includes('/email')) {
|
||||
paths.push('/email');
|
||||
await setDockPaths(dbUser.id, paths);
|
||||
}
|
||||
} catch {
|
||||
// Non-critical — don't block the OAuth flow
|
||||
}
|
||||
|
||||
return ctx.redirect('/settings/integrations?google=success');
|
||||
};
|
||||
|
||||
@@ -89,6 +89,5 @@ export const getTmpAttachmentsDir = (email: string) => join(DATA_PATH, email, 'c
|
||||
export const getAttachmentsDir = (email: string, provider: 'claude' | 'opencode' | 'pi-mono', sessionId: string) =>
|
||||
join(DATA_PATH, email, 'chat_sessions', provider, sessionId, 'attachments');
|
||||
|
||||
export const getUserDockFile = (email: string) => join(DATA_PATH, email, 'dock', 'dock.json');
|
||||
|
||||
export const getUserEmailDir = (email: string) => join(DATA_PATH, email, 'Gmail', 'emails');
|
||||
|
||||
Reference in New Issue
Block a user