feat: 城中村租房平台 - 租客浏览、房东发布房源、图片上传
This commit is contained in:
66
app/api/auth/login/route.ts
Normal file
66
app/api/auth/login/route.ts
Normal file
@@ -0,0 +1,66 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const USERS_FILE = path.join(process.cwd(), 'data/users.json');
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
passwordHash: string;
|
||||
token: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
async function readUsers(): Promise<User[]> {
|
||||
try {
|
||||
const data = await fs.readFile(USERS_FILE, 'utf-8');
|
||||
return JSON.parse(data);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function hashPassword(password: string): string {
|
||||
return crypto.createHash('sha256').update(password).digest('hex');
|
||||
}
|
||||
|
||||
function generateToken(): string {
|
||||
return crypto.randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { username, password } = await request.json();
|
||||
|
||||
if (!username || !password) {
|
||||
return NextResponse.json({ error: '用户名和密码不能为空' }, { status: 400 });
|
||||
}
|
||||
|
||||
const users = await readUsers();
|
||||
const user = users.find(u => u.username === username);
|
||||
|
||||
if (!user || user.passwordHash !== hashPassword(password)) {
|
||||
return NextResponse.json({ error: '用户名或密码错误' }, { status: 401 });
|
||||
}
|
||||
|
||||
const newToken = generateToken();
|
||||
user.token = newToken;
|
||||
await fs.writeFile(USERS_FILE, JSON.stringify(users, null, 2));
|
||||
|
||||
const response = NextResponse.json({ success: true, username: user.username });
|
||||
response.cookies.set('auth_token', newToken, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
path: '/'
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
return NextResponse.json({ error: '登录失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
48
app/api/auth/me/route.ts
Normal file
48
app/api/auth/me/route.ts
Normal file
@@ -0,0 +1,48 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
const USERS_FILE = path.join(process.cwd(), 'data/users.json');
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
async function readUsers(): Promise<User[]> {
|
||||
try {
|
||||
const data = await fs.readFile(USERS_FILE, 'utf-8');
|
||||
return JSON.parse(data);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const token = request.cookies.get('auth_token')?.value;
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ user: null });
|
||||
}
|
||||
|
||||
const users = await readUsers();
|
||||
const user = users.find(u => u.token === token);
|
||||
|
||||
if (!user) {
|
||||
return NextResponse.json({ user: null });
|
||||
}
|
||||
|
||||
return NextResponse.json({ user: { username: user.username } });
|
||||
} catch (error) {
|
||||
console.error('Get user error:', error);
|
||||
return NextResponse.json({ user: null });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: NextRequest) {
|
||||
const response = NextResponse.json({ success: true });
|
||||
response.cookies.delete('auth_token');
|
||||
return response;
|
||||
}
|
||||
82
app/api/auth/register/route.ts
Normal file
82
app/api/auth/register/route.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const DATA_DIR = path.join(process.cwd(), 'data');
|
||||
const USERS_FILE = path.join(DATA_DIR, 'users.json');
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
passwordHash: string;
|
||||
token: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
async function readUsers(): Promise<User[]> {
|
||||
try {
|
||||
const data = await fs.readFile(USERS_FILE, 'utf-8');
|
||||
return JSON.parse(data);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function writeUsers(users: User[]): Promise<void> {
|
||||
await fs.writeFile(USERS_FILE, JSON.stringify(users, null, 2));
|
||||
}
|
||||
|
||||
function hashPassword(password: string): string {
|
||||
return crypto.createHash('sha256').update(password).digest('hex');
|
||||
}
|
||||
|
||||
function generateToken(): string {
|
||||
return crypto.randomBytes(32).toString('hex');
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const { username, password } = await request.json();
|
||||
|
||||
if (!username || !password) {
|
||||
return NextResponse.json({ error: '用户名和密码不能为空' }, { status: 400 });
|
||||
}
|
||||
|
||||
if (username.length < 3 || password.length < 6) {
|
||||
return NextResponse.json({ error: '用户名至少3位,密码至少6位' }, { status: 400 });
|
||||
}
|
||||
|
||||
const users = await readUsers();
|
||||
|
||||
if (users.find(u => u.username === username)) {
|
||||
return NextResponse.json({ error: '用户名已存在' }, { status: 400 });
|
||||
}
|
||||
|
||||
const token = generateToken();
|
||||
const newUser: User = {
|
||||
id: crypto.randomUUID(),
|
||||
username,
|
||||
passwordHash: hashPassword(password),
|
||||
token,
|
||||
createdAt: new Date().toISOString()
|
||||
};
|
||||
|
||||
users.push(newUser);
|
||||
await writeUsers(users);
|
||||
|
||||
const response = NextResponse.json({ success: true, username });
|
||||
response.cookies.set('auth_token', token, {
|
||||
httpOnly: true,
|
||||
secure: process.env.NODE_ENV === 'production',
|
||||
sameSite: 'lax',
|
||||
maxAge: 60 * 60 * 24 * 7,
|
||||
path: '/'
|
||||
});
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
console.error('Register error:', error);
|
||||
return NextResponse.json({ error: '注册失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
17
app/api/districts/route.ts
Normal file
17
app/api/districts/route.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
const DATA_DIR = path.join(process.cwd(), 'data');
|
||||
const DISTRICTS_FILE = path.join(DATA_DIR, 'districts.json');
|
||||
|
||||
export async function GET() {
|
||||
try {
|
||||
const data = await fs.readFile(DISTRICTS_FILE, 'utf-8');
|
||||
const districts = JSON.parse(data);
|
||||
return NextResponse.json({ districts });
|
||||
} catch (error) {
|
||||
console.error('Get districts error:', error);
|
||||
return NextResponse.json({ districts: [] });
|
||||
}
|
||||
}
|
||||
157
app/api/houses/[id]/route.ts
Normal file
157
app/api/houses/[id]/route.ts
Normal file
@@ -0,0 +1,157 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
const DATA_DIR = path.join(process.cwd(), 'data');
|
||||
const HOUSES_FILE = path.join(DATA_DIR, 'houses.json');
|
||||
const USERS_FILE = path.join(DATA_DIR, 'users.json');
|
||||
|
||||
interface House {
|
||||
id: string;
|
||||
owner: string;
|
||||
title: string;
|
||||
description: string;
|
||||
price: number;
|
||||
district: string;
|
||||
address: string;
|
||||
phone: string;
|
||||
images: string[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
async function readFile<T>(filePath: string, defaultValue: T): Promise<T> {
|
||||
try {
|
||||
const data = await fs.readFile(filePath, 'utf-8');
|
||||
return JSON.parse(data);
|
||||
} catch {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
async function getUserFromToken(token: string): Promise<User | null> {
|
||||
const users = await readFile<User[]>(USERS_FILE, []);
|
||||
return users.find(u => u.token === token) || null;
|
||||
}
|
||||
|
||||
async function readHouses(): Promise<House[]> {
|
||||
return readFile<House[]>(HOUSES_FILE, []);
|
||||
}
|
||||
|
||||
async function writeHouses(houses: House[]): Promise<void> {
|
||||
await fs.writeFile(HOUSES_FILE, JSON.stringify(houses, null, 2));
|
||||
}
|
||||
|
||||
export async function GET(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const { id } = await params;
|
||||
const houses = await readHouses();
|
||||
const house = houses.find(h => h.id === id);
|
||||
|
||||
if (!house) {
|
||||
return NextResponse.json({ error: '房屋不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({ house });
|
||||
} catch (error) {
|
||||
console.error('Get house error:', error);
|
||||
return NextResponse.json({ error: '获取房屋信息失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function PUT(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const token = request.cookies.get('auth_token')?.value;
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
|
||||
const user = await getUserFromToken(token);
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: '用户不存在' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const houses = await readHouses();
|
||||
const houseIndex = houses.findIndex(h => h.id === id);
|
||||
|
||||
if (houseIndex === -1) {
|
||||
return NextResponse.json({ error: '房屋不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (houses[houseIndex].owner !== user.username) {
|
||||
return NextResponse.json({ error: '无权修改此房屋' }, { status: 403 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { title, description, price, district, address, phone, images } = body;
|
||||
|
||||
houses[houseIndex] = {
|
||||
...houses[houseIndex],
|
||||
title: title || houses[houseIndex].title,
|
||||
description: description ?? houses[houseIndex].description,
|
||||
price: price !== undefined ? Number(price) : houses[houseIndex].price,
|
||||
district: district || houses[houseIndex].district,
|
||||
address: address || houses[houseIndex].address,
|
||||
phone: phone || houses[houseIndex].phone,
|
||||
images: images || houses[houseIndex].images
|
||||
};
|
||||
|
||||
await writeHouses(houses);
|
||||
|
||||
return NextResponse.json({ success: true, house: houses[houseIndex] });
|
||||
} catch (error) {
|
||||
console.error('Update house error:', error);
|
||||
return NextResponse.json({ error: '更新房屋失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(
|
||||
request: NextRequest,
|
||||
{ params }: { params: Promise<{ id: string }> }
|
||||
) {
|
||||
try {
|
||||
const token = request.cookies.get('auth_token')?.value;
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
|
||||
const user = await getUserFromToken(token);
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: '用户不存在' }, { status: 401 });
|
||||
}
|
||||
|
||||
const { id } = await params;
|
||||
const houses = await readHouses();
|
||||
const house = houses.find(h => h.id === id);
|
||||
|
||||
if (!house) {
|
||||
return NextResponse.json({ error: '房屋不存在' }, { status: 404 });
|
||||
}
|
||||
|
||||
if (house.owner !== user.username) {
|
||||
return NextResponse.json({ error: '无权删除此房屋' }, { status: 403 });
|
||||
}
|
||||
|
||||
const newHouses = houses.filter(h => h.id !== id);
|
||||
await writeHouses(newHouses);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Delete house error:', error);
|
||||
return NextResponse.json({ error: '删除房屋失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
123
app/api/houses/route.ts
Normal file
123
app/api/houses/route.ts
Normal file
@@ -0,0 +1,123 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
import crypto from 'crypto';
|
||||
|
||||
const DATA_DIR = path.join(process.cwd(), 'data');
|
||||
const HOUSES_FILE = path.join(DATA_DIR, 'houses.json');
|
||||
const USERS_FILE = path.join(DATA_DIR, 'users.json');
|
||||
|
||||
interface House {
|
||||
id: string;
|
||||
owner: string;
|
||||
title: string;
|
||||
description: string;
|
||||
price: number;
|
||||
district: string;
|
||||
address: string;
|
||||
phone: string;
|
||||
images: string[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
async function readFile<T>(filePath: string, defaultValue: T): Promise<T> {
|
||||
try {
|
||||
const data = await fs.readFile(filePath, 'utf-8');
|
||||
return JSON.parse(data);
|
||||
} catch {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
async function getUserFromToken(token: string): Promise<User | null> {
|
||||
const users = await readFile<User[]>(USERS_FILE, []);
|
||||
return users.find(u => u.token === token) || null;
|
||||
}
|
||||
|
||||
async function readHouses(): Promise<House[]> {
|
||||
return readFile<House[]>(HOUSES_FILE, []);
|
||||
}
|
||||
|
||||
async function writeHouses(houses: House[]): Promise<void> {
|
||||
await fs.writeFile(HOUSES_FILE, JSON.stringify(houses, null, 2));
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const district = searchParams.get('district');
|
||||
const keyword = searchParams.get('keyword');
|
||||
|
||||
let houses = await readHouses();
|
||||
|
||||
if (district && district !== '全部') {
|
||||
houses = houses.filter(h => h.district === district);
|
||||
}
|
||||
|
||||
if (keyword) {
|
||||
const kw = keyword.toLowerCase();
|
||||
houses = houses.filter(h =>
|
||||
h.title.toLowerCase().includes(kw) ||
|
||||
h.address.toLowerCase().includes(kw) ||
|
||||
h.description.toLowerCase().includes(kw)
|
||||
);
|
||||
}
|
||||
|
||||
houses.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
|
||||
return NextResponse.json({ houses });
|
||||
} catch (error) {
|
||||
console.error('Get houses error:', error);
|
||||
return NextResponse.json({ error: '获取房屋列表失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const token = request.cookies.get('auth_token')?.value;
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
|
||||
const user = await getUserFromToken(token);
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: '用户不存在' }, { status: 401 });
|
||||
}
|
||||
|
||||
const body = await request.json();
|
||||
const { title, description, price, district, address, phone, images } = body;
|
||||
|
||||
if (!title || !price || !district || !address || !phone) {
|
||||
return NextResponse.json({ error: '请填写完整信息' }, { status: 400 });
|
||||
}
|
||||
|
||||
const house: House = {
|
||||
id: crypto.randomUUID(),
|
||||
owner: user.username,
|
||||
title,
|
||||
description: description || '',
|
||||
price: Number(price),
|
||||
district,
|
||||
address,
|
||||
phone,
|
||||
images: images || [],
|
||||
createdAt: new Date().toISOString()
|
||||
};
|
||||
|
||||
const houses = await readHouses();
|
||||
houses.push(house);
|
||||
await writeHouses(houses);
|
||||
|
||||
return NextResponse.json({ success: true, house });
|
||||
} catch (error) {
|
||||
console.error('Create house error:', error);
|
||||
return NextResponse.json({ error: '创建房屋失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
69
app/api/owner/houses/route.ts
Normal file
69
app/api/owner/houses/route.ts
Normal file
@@ -0,0 +1,69 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
const DATA_DIR = path.join(process.cwd(), 'data');
|
||||
const HOUSES_FILE = path.join(DATA_DIR, 'houses.json');
|
||||
const USERS_FILE = path.join(DATA_DIR, 'users.json');
|
||||
|
||||
interface House {
|
||||
id: string;
|
||||
owner: string;
|
||||
title: string;
|
||||
description: string;
|
||||
price: number;
|
||||
district: string;
|
||||
address: string;
|
||||
phone: string;
|
||||
images: string[];
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
token: string;
|
||||
}
|
||||
|
||||
async function readFile<T>(filePath: string, defaultValue: T): Promise<T> {
|
||||
try {
|
||||
const data = await fs.readFile(filePath, 'utf-8');
|
||||
return JSON.parse(data);
|
||||
} catch {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
||||
|
||||
async function getUserFromToken(token: string): Promise<User | null> {
|
||||
const users = await readFile<User[]>(USERS_FILE, []);
|
||||
return users.find(u => u.token === token) || null;
|
||||
}
|
||||
|
||||
async function readHouses(): Promise<House[]> {
|
||||
return readFile<House[]>(HOUSES_FILE, []);
|
||||
}
|
||||
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
const token = request.cookies.get('auth_token')?.value;
|
||||
|
||||
if (!token) {
|
||||
return NextResponse.json({ error: '请先登录' }, { status: 401 });
|
||||
}
|
||||
|
||||
const user = await getUserFromToken(token);
|
||||
if (!user) {
|
||||
return NextResponse.json({ error: '用户不存在' }, { status: 401 });
|
||||
}
|
||||
|
||||
const houses = await readHouses();
|
||||
const myHouses = houses
|
||||
.filter(h => h.owner === user.username)
|
||||
.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime());
|
||||
|
||||
return NextResponse.json({ houses: myHouses });
|
||||
} catch (error) {
|
||||
console.error('Get my houses error:', error);
|
||||
return NextResponse.json({ error: '获取房屋列表失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
53
app/api/upload/route.ts
Normal file
53
app/api/upload/route.ts
Normal file
@@ -0,0 +1,53 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
import fs from 'fs/promises';
|
||||
import path from 'path';
|
||||
|
||||
const UPLOAD_DIR = path.join(process.cwd(), 'public/uploads');
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
try {
|
||||
const formData = await request.formData();
|
||||
const file = formData.get('file') as File | null;
|
||||
|
||||
if (!file) {
|
||||
return NextResponse.json({ error: '请选择图片' }, { status: 400 });
|
||||
}
|
||||
|
||||
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
return NextResponse.json({ error: '仅支持 JPG、PNG、GIF、WebP 格式' }, { status: 400 });
|
||||
}
|
||||
|
||||
const ext = file.name.split('.').pop() || 'jpg';
|
||||
const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
|
||||
const filepath = path.join(UPLOAD_DIR, filename);
|
||||
|
||||
const buffer = await file.arrayBuffer();
|
||||
await fs.writeFile(filepath, Buffer.from(buffer));
|
||||
|
||||
const url = `/uploads/${filename}`;
|
||||
return NextResponse.json({ url });
|
||||
} catch (error) {
|
||||
console.error('Upload error:', error);
|
||||
return NextResponse.json({ error: '上传失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function DELETE(request: NextRequest) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url);
|
||||
const filename = searchParams.get('filename');
|
||||
|
||||
if (!filename) {
|
||||
return NextResponse.json({ error: '缺少文件名' }, { status: 400 });
|
||||
}
|
||||
|
||||
const filepath = path.join(UPLOAD_DIR, path.basename(filename));
|
||||
await fs.unlink(filepath);
|
||||
|
||||
return NextResponse.json({ success: true });
|
||||
} catch (error) {
|
||||
console.error('Delete error:', error);
|
||||
return NextResponse.json({ error: '删除失败' }, { status: 500 });
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user