Q58Connect/src/actions/add-client.ts
wood chen bd6b2b747d feat: Add user allowlist and improve client creation validation
- Implement user allowlist feature for client applications
- Add input validation for client creation form
- Handle parsing of allowed users list
- Improve error handling and user feedback during client creation
- Update authorization process to check client enabled status and user permissions
2025-02-20 02:13:06 +08:00

63 lines
1.8 KiB
TypeScript

"use server";
import { createClient, getClientByClientId } from "@/lib/dto/client";
import { getCurrentUser } from "@/lib/session";
import { generateRandomKey, generateSecretWords } from "@/lib/utils";
export async function AddClientAction(formData: FormData) {
const name = formData.get("name") as string;
const home = formData.get("home") as string;
const logo = formData.get("logo") as string;
const redirectUri = formData.get("redirectUri") as string;
const description = formData.get("description") as string;
const allowedUsersStr = formData.get("allowedUsers") as string;
const user = await getCurrentUser();
if (!user?.id) {
return { success: false, error: "未登录" };
}
// 验证必填字段
if (!name || !home || !redirectUri) {
return { success: false, error: "请填写所有必填字段" };
}
// 解析允许的用户列表
let allowedUsers: string[] = [];
if (allowedUsersStr) {
try {
allowedUsers = JSON.parse(allowedUsersStr);
} catch (error) {
console.error("Error parsing allowedUsers:", error);
return { success: false, error: "允许用户列表格式错误" };
}
}
// Generate a unique client ID and secret
let clientId = generateRandomKey();
while (await getClientByClientId(clientId)) {
clientId = generateRandomKey();
}
const clientSecret = generateSecretWords();
try {
const newClient = await createClient({
name,
home,
logo,
redirectUri,
description,
clientId,
clientSecret,
userId: user.id,
allowedUsers,
});
console.log("New client created:", newClient);
return { success: true, client: newClient };
} catch (error) {
console.error("Error creating client:", error);
return { success: false, error: "创建应用失败" };
}
}