Files
NianAIGC/lib/server/auth/current-user.ts

136 lines
4.1 KiB
TypeScript

import { cookies } from "next/headers";
import { SESSION_COOKIE_NAME, getAuthRuntimeConfig } from "@/lib/auth/config";
import { hasAdminSessionAccess, hasSuperAdminAccess } from "@/lib/auth/permissions";
import { parseSessionCookieValue, readChunkedCookieValue, type AuthSession, type AuthUser } from "@/lib/auth/session";
import { DEFAULT_OWNER_ID } from "@/lib/server/runtime";
import { loadPlatformAuthorizationSnapshot } from "@/lib/server/auth/platform-authorization-store";
import { authorizePlatformSession } from "@/lib/server/auth/platform-session";
export class AuthRequiredError extends Error {
status = 401;
constructor(message = "请先登录。") {
super(message);
this.name = "AuthRequiredError";
}
}
export class AuthConfigurationError extends Error {
status = 503;
constructor(message: string) {
super(message);
this.name = "AuthConfigurationError";
}
}
const localUser: AuthUser = {
id: DEFAULT_OWNER_ID,
subject: DEFAULT_OWNER_ID,
username: "13800000000",
phone: "13800000000",
displayName: "智念用户",
clientId: "local-dev",
role: "super_admin",
organizationId: "org-demo",
organizationName: "演示组织",
authorities: ["zhinian_admin"],
scope: []
};
function localSession(): AuthSession {
const now = Math.floor(Date.now() / 1000);
return {
version: 1,
authMode: "admin",
user: localUser,
issuedAt: now,
expiresAt: now + 24 * 60 * 60
};
}
export async function getOptionalAuthSession(): Promise<AuthSession | null> {
const config = getAuthRuntimeConfig();
if (!config.sessionSecret) return null;
const cookieStore = await cookies();
const session = await parseSessionCookieValue(
readChunkedCookieValue(SESSION_COOKIE_NAME, (name) => cookieStore.get(name)?.value),
config.sessionSecret
);
if (!session) return null;
const authorization = await authorizePlatformSession(session, loadPlatformAuthorizationSnapshot);
return authorization.outcome === "authenticated" ? authorization.session : null;
}
export async function requireAppSession(): Promise<AuthSession> {
const session = await getOptionalAuthSession();
if (session) return session;
const config = getAuthRuntimeConfig();
if (!config.required) return localSession();
if (!config.configured) {
throw new AuthConfigurationError(`认证配置不完整:${config.missing.join(", ") || "未知配置"}`);
}
throw new AuthRequiredError();
}
export async function requireAppUser(): Promise<AuthUser> {
return (await requireAppSession()).user;
}
export class AdminRequiredError extends Error {
status = 403;
constructor(message = "需要管理员权限。") {
super(message);
this.name = "AdminRequiredError";
}
}
export async function requireAdminUser(): Promise<AuthUser> {
return (await requireAdminSession()).user;
}
export async function requireAdminSession(): Promise<AuthSession> {
const session = await requireAppSession();
if (!hasAdminSessionAccess(session)) throw new AdminRequiredError();
return session;
}
export class SuperAdminRequiredError extends Error {
status = 403;
constructor(message = "需要超级管理员权限。") {
super(message);
this.name = "SuperAdminRequiredError";
}
}
export async function requireSuperAdminSession(): Promise<AuthSession> {
const session = await requireAppSession();
if (!hasSuperAdminAccess(session.user)) throw new SuperAdminRequiredError();
return session;
}
export async function requireSuperAdminUser(): Promise<AuthUser> {
return (await requireSuperAdminSession()).user;
}
export async function getShellAuthState(): Promise<{
user: AuthUser | null;
authRequired: boolean;
authConfigured: boolean;
isAdmin: boolean;
isSuperAdmin: boolean;
}> {
const config = getAuthRuntimeConfig();
const session = await getOptionalAuthSession();
const shellSession = session || (!config.required ? localSession() : null);
return {
user: shellSession?.user || null,
authRequired: config.required,
authConfigured: config.configured,
isAdmin: hasAdminSessionAccess(shellSession),
isSuperAdmin: hasSuperAdminAccess(shellSession?.user)
};
}