feat: add control plane authentication baseline

This commit is contained in:
wlx committed 2026-08-21 15:47:57 +08:00
1 parent a4c93ff1a7
commit 0d10e2d124
21 files changed
+1403 -18

No files matched your search

+137
View File
@@ -0,0 +1,137 @@
export type AuthRole = 'user' | 'admin'
export interface AuthUser {
id: string
account: string
accountKind: 'email' | 'phone'
displayName: string
role: AuthRole
status: 'active' | 'disabled'
createdAt: string
lastLoginAt?: string
}
export interface RegisterInput {
invitationCode: string
account: string
password: string
displayName?: string
}
export interface LoginInput {
account: string
password: string
}
export interface AuthClient {
login(input: LoginInput): Promise<AuthUser>
register(input: RegisterInput): Promise<AuthUser>
currentUser(): Promise<AuthUser | undefined>
logout(): Promise<void>
}
class HttpAuthClient implements AuthClient {
constructor(private readonly baseUrl: string) {}
async login(input: LoginInput) {
const payload = await this.request<{ user: AuthUser }>('/api/auth/login', {
method: 'POST',
body: JSON.stringify(input),
})
return payload.user
}
async register(input: RegisterInput): Promise<AuthUser> {
const payload = await this.request<{ user: AuthUser }>('/api/auth/register', {
method: 'POST',
body: JSON.stringify(input),
})
return payload.user
}
async currentUser() {
try {
const payload = await this.request<{ user: AuthUser }>('/api/auth/me')
return payload.user
} catch (error) {
if (error instanceof AuthApiError && error.status === 401) return undefined
throw error
}
}
async logout() {
await this.request('/api/auth/logout', { method: 'POST' })
}
private async request<T>(path: string, init?: RequestInit): Promise<T> {
let response: Response
try {
response = await fetch(`${this.baseUrl}${path}`, {
...init,
credentials: 'include',
headers: {
'Content-Type': 'application/json',
...init?.headers,
},
})
} catch {
throw new AuthApiError(0, '无法连接 Control Plane,请确认认证服务已启动。')
}
if (response.status === 204) return undefined as T
const payload = await response.json().catch(() => ({})) as { error?: { code?: string; message?: string } }
if (!response.ok) throw new AuthApiError(response.status, payload.error?.message || '认证请求失败', payload.error?.code)
return payload as T
}
}
class DemoAuthClient implements AuthClient {
private readonly sessionKey = 'moyi_demo_session'
private readonly user: AuthUser = {
id: 'demo_admin',
account: 'demo@moyi.ai',
accountKind: 'email',
displayName: '林默',
role: 'admin',
status: 'active',
createdAt: '2026-08-20T00:00:00.000Z',
}
async login(input: LoginInput) {
if (!input.account.trim() || !input.password) throw new AuthApiError(400, '请输入账号和密码')
sessionStorage.setItem(this.sessionKey, '1')
return this.user
}
async register(input: RegisterInput): Promise<AuthUser> {
if (!input.invitationCode.trim()) throw new AuthApiError(400, '第一版内测需要填写邀请码')
if (input.password.length < 8) throw new AuthApiError(400, '密码至少需要 8 位')
sessionStorage.setItem(this.sessionKey, '1')
return { ...this.user, account: input.account, displayName: input.displayName || input.account.split('@')[0] || 'MOYI 用户', role: 'user' }
}
async currentUser() {
return sessionStorage.getItem(this.sessionKey) ? this.user : undefined
}
async logout() {
sessionStorage.removeItem(this.sessionKey)
}
}
export class AuthApiError extends Error {
constructor(
readonly status: number,
message: string,
readonly code?: string,
) {
super(message)
}
}
const authMode = import.meta.env.VITE_AUTH_MODE || 'remote'
const controlPlaneUrl = (import.meta.env.VITE_CONTROL_PLANE_URL || 'http://127.0.0.1:8787').replace(/\/$/, '')
export const authClient: AuthClient = authMode === 'demo'
? new DemoAuthClient()
: new HttpAuthClient(controlPlaneUrl)