feat: 去除basic auth认证,添加登录和登出 API,更新中间件以支持 cookie 验证
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
import { NextRequest, NextResponse } from 'next/server'
|
||||
import { config } from '@/lib/config'
|
||||
import { createToken, AUTH_COOKIE_NAME } from '@/lib/auth'
|
||||
|
||||
export async function POST(req: NextRequest) {
|
||||
try {
|
||||
const body = await req.json()
|
||||
const { username, password } = body
|
||||
|
||||
if (!username || !password) {
|
||||
return NextResponse.json(
|
||||
{ error: '用户名和密码不能为空' },
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (username === config.auth.username && password === config.auth.password) {
|
||||
const token = await createToken(username)
|
||||
|
||||
const response = NextResponse.json({ success: true })
|
||||
|
||||
response.cookies.set(AUTH_COOKIE_NAME, token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 60 * 60 * 24, // 1 day
|
||||
path: '/'
|
||||
})
|
||||
|
||||
return response
|
||||
} else {
|
||||
return NextResponse.json(
|
||||
{ error: '用户名或密码错误' },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error)
|
||||
return NextResponse.json(
|
||||
{ error: '服务器内部错误' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
|
||||
export async function POST() {
|
||||
const response = NextResponse.json({ success: true });
|
||||
response.cookies.delete('auth_token');
|
||||
return response;
|
||||
}
|
||||
Reference in New Issue
Block a user