initial commit

This commit is contained in:
Zacharias-Brohn
2026-01-14 06:12:55 +01:00
commit d702390660
46 changed files with 21386 additions and 0 deletions
+53
View File
@@ -0,0 +1,53 @@
import { NextRequest, NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import { SignJWT } from 'jose';
import { prisma } from '@/lib/prisma';
const JWT_SECRET = new TextEncoder().encode(
process.env.JWT_SECRET || 'your-secret-key-at-least-32-chars-long'
);
export async function POST(request: NextRequest) {
try {
const { username, password } = await request.json();
if (!username || !password) {
return NextResponse.json({ error: 'Username and password are required' }, { status: 400 });
}
const user = await prisma.user.findUnique({
where: { username },
});
if (!user) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return NextResponse.json({ error: 'Invalid credentials' }, { status: 401 });
}
const token = await new SignJWT({ userId: user.id, username: user.username })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('30d')
.sign(JWT_SECRET);
const response = NextResponse.json({ message: 'Login successful' }, { status: 200 });
response.cookies.set('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 30 * 24 * 60 * 60, // 30 days
path: '/',
});
return response;
} catch (error) {
console.error('Login error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
+15
View File
@@ -0,0 +1,15 @@
import { NextResponse } from 'next/server';
export async function POST() {
const response = NextResponse.json({ message: 'Logged out successfully' }, { status: 200 });
response.cookies.set('token', '', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 0, // Expire immediately
path: '/',
});
return response;
}
+21
View File
@@ -0,0 +1,21 @@
import { NextRequest, NextResponse } from 'next/server';
import { jwtVerify } from 'jose';
const JWT_SECRET = new TextEncoder().encode(
process.env.JWT_SECRET || 'your-secret-key-at-least-32-chars-long'
);
export async function GET(request: NextRequest) {
const token = request.cookies.get('token')?.value;
if (!token) {
return NextResponse.json({ user: null }, { status: 200 });
}
try {
const { payload } = await jwtVerify(token, JWT_SECRET);
return NextResponse.json({ user: payload }, { status: 200 });
} catch (error) {
return NextResponse.json({ user: null }, { status: 200 });
}
}
+64
View File
@@ -0,0 +1,64 @@
import { NextRequest, NextResponse } from 'next/server';
import bcrypt from 'bcryptjs';
import { prisma } from '@/lib/prisma';
export async function POST(request: NextRequest) {
try {
const { username, password } = await request.json();
if (!username || !password) {
return NextResponse.json({ error: 'Username and password are required' }, { status: 400 });
}
const existingUser = await prisma.user.findUnique({
where: { username },
});
if (existingUser) {
return NextResponse.json({ error: 'Username already exists' }, { status: 400 });
}
const hashedPassword = await bcrypt.hash(password, 10);
const user = await prisma.user.create({
data: {
username,
password: hashedPassword,
},
});
// Automatically login after register
const JWT_SECRET = new TextEncoder().encode(
process.env.JWT_SECRET || 'your-secret-key-at-least-32-chars-long'
);
// Import SignJWT dynamically to avoid top-level import if it causes issues, though it should be fine.
// Better yet, let's keep it consistent with login.
const { SignJWT } = await import('jose');
const token = await new SignJWT({ userId: user.id, username: user.username })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('30d')
.sign(JWT_SECRET);
const response = NextResponse.json(
{ message: 'User created successfully', userId: user.id },
{ status: 201 }
);
// Set cookie on response
await response.cookies.set('token', token, {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
maxAge: 30 * 24 * 60 * 60, // 30 days
path: '/',
});
return response;
} catch (error: any) {
console.error('Registration error:', error);
return NextResponse.json({ error: error.message || 'Internal server error' }, { status: 500 });
}
}
+101
View File
@@ -0,0 +1,101 @@
import { NextRequest, NextResponse } from 'next/server';
import { jwtVerify } from 'jose';
import { prisma } from '@/lib/prisma';
const JWT_SECRET = new TextEncoder().encode(
process.env.JWT_SECRET || 'your-secret-key-at-least-32-chars-long'
);
export async function GET(request: NextRequest) {
const token = request.cookies.get('token')?.value;
if (!token) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const { payload } = await jwtVerify(token, JWT_SECRET);
const userId = payload.userId as string;
const chats = await prisma.chat.findMany({
where: { userId },
orderBy: { updatedAt: 'desc' },
include: {
messages: {
orderBy: { createdAt: 'asc' },
},
},
});
return NextResponse.json(chats, { status: 200 });
} catch (error) {
console.error('Fetch chats error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
export async function POST(request: NextRequest) {
const token = request.cookies.get('token')?.value;
if (!token) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
try {
const { payload } = await jwtVerify(token, JWT_SECRET);
const userId = payload.userId as string;
const { messages, chatId } = await request.json();
if (!messages || !Array.isArray(messages) || messages.length === 0) {
return NextResponse.json({ error: 'Messages are required' }, { status: 400 });
}
// Determine chat ID or create new
let currentChatId = chatId;
// Use the last message in the array, assuming it's the one to be saved
const messageToSave = messages[messages.length - 1];
if (!currentChatId) {
// Create new chat
const firstMessageContent = messageToSave.content;
const title =
firstMessageContent.length > 30
? `${firstMessageContent.substring(0, 30)}...`
: firstMessageContent;
const newChat = await prisma.chat.create({
data: {
userId,
title,
},
});
currentChatId = newChat.id;
}
const { content, role } = messageToSave;
if (!content || !role) {
return NextResponse.json({ error: 'Invalid message format' }, { status: 400 });
}
const message = await prisma.message.create({
data: {
content,
role,
chatId: currentChatId,
},
});
// Update chat updated_at
await prisma.chat.update({
where: { id: currentChatId },
data: { updatedAt: new Date() },
});
return NextResponse.json({ message, chatId: currentChatId }, { status: 200 });
} catch (error) {
console.error('Save chat error:', error);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}