- 新增许可证服务器 (license-server/) - 新增 Agent 部署模块 (flnxi-agent/) - 添加许可证验证和激活页面 - 添加 Harbor 镜像同步脚本 - 更新素材系统支持许可证验证
123 lines
2.7 KiB
TypeScript
123 lines
2.7 KiB
TypeScript
import { cookies } from 'next/headers';
|
|
import { prisma } from './db';
|
|
import bcrypt from 'bcryptjs';
|
|
import jwt from 'jsonwebtoken';
|
|
|
|
const JWT_SECRET = process.env.JWT_SECRET || 'license-server-secret-key';
|
|
const TOKEN_EXPIRY = '24h';
|
|
|
|
export interface AdminSession {
|
|
id: string;
|
|
username: string;
|
|
}
|
|
|
|
/**
|
|
* 验证管理员登录
|
|
*/
|
|
export async function verifyAdmin(
|
|
username: string,
|
|
password: string
|
|
): Promise<{ success: boolean; token?: string; error?: string }> {
|
|
try {
|
|
const admin = await prisma.admin.findUnique({
|
|
where: { username },
|
|
});
|
|
|
|
if (!admin) {
|
|
return { success: false, error: '用户名或密码错误' };
|
|
}
|
|
|
|
const isValid = await bcrypt.compare(password, admin.passwordHash);
|
|
if (!isValid) {
|
|
return { success: false, error: '用户名或密码错误' };
|
|
}
|
|
|
|
const token = jwt.sign(
|
|
{ id: admin.id, username: admin.username },
|
|
JWT_SECRET,
|
|
{ expiresIn: TOKEN_EXPIRY }
|
|
);
|
|
|
|
return { success: true, token };
|
|
} catch (error) {
|
|
console.error('验证失败:', error);
|
|
return { success: false, error: '服务器错误' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 验证 JWT token
|
|
*/
|
|
export function verifyToken(token: string): AdminSession | null {
|
|
try {
|
|
const decoded = jwt.verify(token, JWT_SECRET) as AdminSession;
|
|
return decoded;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 从请求中获取当前管理员会话
|
|
*/
|
|
export async function getAdminSession(): Promise<AdminSession | null> {
|
|
const cookieStore = await cookies();
|
|
const token = cookieStore.get('admin_token')?.value;
|
|
|
|
if (!token) {
|
|
return null;
|
|
}
|
|
|
|
return verifyToken(token);
|
|
}
|
|
|
|
/**
|
|
* 创建管理员账号(用于初始化)
|
|
*/
|
|
export async function createAdmin(
|
|
username: string,
|
|
password: string
|
|
): Promise<{ success: boolean; error?: string }> {
|
|
try {
|
|
const existing = await prisma.admin.findUnique({
|
|
where: { username },
|
|
});
|
|
|
|
if (existing) {
|
|
return { success: false, error: '用户名已存在' };
|
|
}
|
|
|
|
const passwordHash = await bcrypt.hash(password, 10);
|
|
|
|
await prisma.admin.create({
|
|
data: {
|
|
username,
|
|
passwordHash,
|
|
},
|
|
});
|
|
|
|
return { success: true };
|
|
} catch (error) {
|
|
console.error('创建管理员失败:', error);
|
|
return { success: false, error: '服务器错误' };
|
|
}
|
|
}
|
|
|
|
/**
|
|
* 生成许可证密钥
|
|
*/
|
|
export function generateLicenseKey(): string {
|
|
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
|
|
const segments: string[] = [];
|
|
|
|
for (let i = 0; i < 4; i++) {
|
|
let segment = '';
|
|
for (let j = 0; j < 4; j++) {
|
|
segment += chars.charAt(Math.floor(Math.random() * chars.length));
|
|
}
|
|
segments.push(segment);
|
|
}
|
|
|
|
return segments.join('-');
|
|
}
|