require api auth token
This commit is contained in:
@@ -51,6 +51,7 @@ const apiPort = Number(process.env.API_PORT || 3002);
|
||||
const defaultImageModel = process.env.GEMINI_IMAGE_MODEL || 'gemini-3.1-flash-image-preview';
|
||||
const defaultTextModel = process.env.GEMINI_TEXT_MODEL || 'gemini-2.5-flash';
|
||||
const apiAuthToken = process.env.API_AUTH_TOKEN || '';
|
||||
const apiAuthDisabled = process.env.API_AUTH_DISABLED === 'true';
|
||||
|
||||
if (!runtimeApiKey) {
|
||||
console.warn('GEMINI_API_KEY/API_KEY is not set. API calls will fail until it is configured.');
|
||||
@@ -70,11 +71,19 @@ app.use((req, res, next) => {
|
||||
app.use(express.json({ limit: process.env.API_JSON_LIMIT || '50mb' }));
|
||||
|
||||
function requireAuth(req: express.Request, res: express.Response, next: express.NextFunction) {
|
||||
if (!apiAuthToken) {
|
||||
if (apiAuthDisabled) {
|
||||
next();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!apiAuthToken) {
|
||||
res.status(503).json({
|
||||
ok: false,
|
||||
error: 'API_AUTH_TOKEN is required. Set it in .env.local, or set API_AUTH_DISABLED=true for local-only development.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const authHeader = req.header('authorization') || '';
|
||||
const bearerToken = authHeader.startsWith('Bearer ') ? authHeader.slice(7) : '';
|
||||
const headerToken = req.header('x-api-key') || '';
|
||||
@@ -86,7 +95,7 @@ function requireAuth(req: express.Request, res: express.Response, next: express.
|
||||
|
||||
res.status(401).json({
|
||||
ok: false,
|
||||
error: 'Unauthorized. Send Authorization: Bearer <API_AUTH_TOKEN> or x-api-key.',
|
||||
error: 'Unauthorized. Send Authorization: Bearer YOUR_API_AUTH_TOKEN or x-api-key.',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -323,7 +332,8 @@ app.get('/api/health', (_req, res) => {
|
||||
ok: true,
|
||||
apiPort,
|
||||
hasGeminiApiKey: Boolean(runtimeApiKey),
|
||||
authEnabled: Boolean(apiAuthToken),
|
||||
authEnabled: Boolean(apiAuthToken) && !apiAuthDisabled,
|
||||
authRequired: !apiAuthDisabled,
|
||||
acceptsPerRequestApiKey: true,
|
||||
defaultImageModel,
|
||||
defaultTextModel,
|
||||
@@ -336,7 +346,8 @@ app.get('/api/config', requireAuth, (_req, res) => {
|
||||
apiPort,
|
||||
hasGeminiApiKey: Boolean(runtimeApiKey),
|
||||
apiKeyPreview: runtimeApiKey ? `${runtimeApiKey.slice(0, 6)}...${runtimeApiKey.slice(-4)}` : '',
|
||||
authEnabled: Boolean(apiAuthToken),
|
||||
authEnabled: Boolean(apiAuthToken) && !apiAuthDisabled,
|
||||
authRequired: !apiAuthDisabled,
|
||||
defaultImageModel,
|
||||
defaultTextModel,
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user