feat: add login page and API

This commit is contained in:
2026-03-04 02:04:50 +08:00
parent e2b4105fb6
commit bdb4d0cf32
2 changed files with 107 additions and 0 deletions

23
app/api/login/route.ts Normal file
View File

@@ -0,0 +1,23 @@
// app/api/login/route.ts
import { NextResponse } from 'next/server';
import { AUTH_USERNAME, AUTH_PASSWORD, COOKIE_NAME, COOKIE_MAX_AGE } from '@/lib/constants';
export async function POST(request: Request) {
const body = await request.json();
const { username, password } = body;
if (username === AUTH_USERNAME && password === AUTH_PASSWORD) {
const response = NextResponse.json({ success: true });
response.cookies.set(COOKIE_NAME, 'ok', {
httpOnly: true,
maxAge: COOKIE_MAX_AGE,
path: '/',
});
return response;
}
return NextResponse.json(
{ error: 'Invalid credentials' },
{ status: 401 }
);
}

84
app/login/page.tsx Normal file
View File

@@ -0,0 +1,84 @@
// app/login/page.tsx
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { COOKIE_NAME, COOKIE_MAX_AGE } from '@/lib/constants';
export default function LoginPage() {
const router = useRouter();
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setError('');
// 这里应该调用 API 验证,简化起见直接比对
// 实际项目中应该使用 API route 进行验证
const response = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password }),
});
if (response.ok) {
router.push('/download');
} else {
setError('用户名或密码错误');
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50">
<div className="max-w-md w-full bg-white rounded-lg shadow-md p-8">
<h1 className="text-2xl font-bold text-center mb-6"></h1>
<h2 className="text-lg text-gray-600 text-center mb-6"></h2>
{error && (
<div className="bg-red-50 text-red-600 px-4 py-3 rounded mb-4">
{error}
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label htmlFor="username" className="block text-sm font-medium text-gray-700 mb-2">
</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
/>
</div>
<div>
<label htmlFor="password" className="block text-sm font-medium text-gray-700 mb-2">
</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
required
/>
</div>
<button
type="submit"
className="w-full bg-blue-600 text-white py-2 px-4 rounded-md hover:bg-blue-700 transition-colors"
>
</button>
</form>
</div>
</div>
);
}