98 lines
2.7 KiB
TypeScript
98 lines
2.7 KiB
TypeScript
'use server';
|
|
|
|
import { getOrCreateOrgAndProject } from './orgProjectActions';
|
|
import { listApiKeys as listApiKeysQuery } from '../db/queries/apiKeys';
|
|
|
|
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';
|
|
|
|
interface BootstrapResponse {
|
|
apiKey: string;
|
|
type: string;
|
|
name: string;
|
|
expiresAt: string | null;
|
|
message: string;
|
|
}
|
|
|
|
interface CreateKeyResponse {
|
|
apiKey: string;
|
|
metadata: {
|
|
id: string;
|
|
type: string;
|
|
projectId: string;
|
|
name: string;
|
|
expiresAt: string | null;
|
|
scopes: string[];
|
|
createdAt: string;
|
|
};
|
|
message: string;
|
|
}
|
|
|
|
export async function bootstrapMasterKey(): Promise<{ success: boolean; apiKey?: string; error?: string }> {
|
|
try {
|
|
const response = await fetch(`${API_BASE_URL}/api/bootstrap/initial-key`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json();
|
|
return { success: false, error: error.message || 'Failed to bootstrap master key' };
|
|
}
|
|
|
|
const data: BootstrapResponse = await response.json();
|
|
return { success: true, apiKey: data.apiKey };
|
|
} catch (error) {
|
|
console.error('Bootstrap error:', error);
|
|
return { success: false, error: 'Network error while bootstrapping master key' };
|
|
}
|
|
}
|
|
|
|
export async function createProjectApiKey(
|
|
masterKey: string,
|
|
email: string,
|
|
orgName: string,
|
|
projectName: string
|
|
): Promise<{ success: boolean; apiKey?: string; error?: string }> {
|
|
try {
|
|
// First, ensure organization and project exist in DB
|
|
const { organization, project } = await getOrCreateOrgAndProject(email, orgName, projectName);
|
|
|
|
// Then call API service to create the project key
|
|
const response = await fetch(`${API_BASE_URL}/api/admin/keys`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'X-API-Key': masterKey,
|
|
},
|
|
body: JSON.stringify({
|
|
type: 'project',
|
|
projectId: project.id,
|
|
organizationId: organization.id,
|
|
name: `${orgName} - ${projectName}`,
|
|
}),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const error = await response.json();
|
|
return { success: false, error: error.message || 'Failed to create API key' };
|
|
}
|
|
|
|
const data: CreateKeyResponse = await response.json();
|
|
return { success: true, apiKey: data.apiKey };
|
|
} catch (error) {
|
|
console.error('Create key error:', error);
|
|
return { success: false, error: 'Network error while creating API key' };
|
|
}
|
|
}
|
|
|
|
export async function listApiKeys() {
|
|
try {
|
|
return await listApiKeysQuery();
|
|
} catch (error) {
|
|
console.error('List keys error:', error);
|
|
return [];
|
|
}
|
|
}
|