login.post.ts
1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { z } from 'zod'
import { authenticateMockUser, createMockSession, toPublicUser } from '../../utils/mock-auth'
const loginPayloadSchema = z.object({
username: z.string().trim().min(1),
password: z.string().trim().min(1)
})
export default eventHandler(async (event) => {
const body = await readBody(event)
const parsed = loginPayloadSchema.safeParse(body)
if (!parsed.success) {
return {
success: false,
state: 'failed',
nextAction: 'retry',
errorCode: 'VALIDATION_ERROR',
message: '用户名和密码不能为空。'
}
}
const user = authenticateMockUser(parsed.data.username, parsed.data.password)
if (!user) {
return {
success: false,
state: 'failed',
nextAction: 'retry',
errorCode: 'INVALID_CREDENTIALS',
message: '用户名或密码错误。'
}
}
const session = createMockSession(user.username)
return {
success: true,
state: 'authenticated',
nextAction: 'enter_dashboard',
errorCode: null,
message: '登录成功。',
token: session.token,
expiresAt: new Date(session.expiresAt).toISOString(),
user: toPublicUser(user)
}
})