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,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');
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user