Skip to content

feat: add chat config #875

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions app/(auth)/actions.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
'use server';

import { z } from 'zod';

import { createUser, getUser } from '@/lib/db/queries';

import { signIn } from './auth';
import { auth, signIn } from './auth';

const authFormSchema = z.object({
email: z.string().email(),
Expand Down Expand Up @@ -82,3 +80,13 @@ export const register = async (
return { status: 'failed' };
}
};

export const isAuthenticated = async () => {
const session = await auth();
return Boolean(session?.user?.id);
};

export const getUserId = async () => {
const session = await auth();
return session?.user?.id;
};
24 changes: 12 additions & 12 deletions app/(auth)/auth.config.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { chatConfig } from '@/lib/chat-config';
import type { NextAuthConfig } from 'next-auth';

export const authConfig = {
Expand All @@ -12,25 +13,24 @@ export const authConfig = {
callbacks: {
authorized({ auth, request: { nextUrl } }) {
const isLoggedIn = !!auth?.user;
const isOnChat = nextUrl.pathname.startsWith('/');
const isOnRegister = nextUrl.pathname.startsWith('/register');
const isOnLogin = nextUrl.pathname.startsWith('/login');
const isOnRegisterPage = nextUrl.pathname.startsWith('/register');
const isOnLoginPage = nextUrl.pathname.startsWith('/login');
const isOnChatPage = nextUrl.pathname.startsWith('/');

if (isLoggedIn && (isOnLogin || isOnRegister)) {
// If logged in, redirect to home page
if (isLoggedIn && (isOnLoginPage || isOnRegisterPage)) {
return Response.redirect(new URL('/', nextUrl as unknown as URL));
}

if (isOnRegister || isOnLogin) {
return true; // Always allow access to register and login pages
// Always allow access to register and login pages
if (isOnRegisterPage || isOnLoginPage) {
return true;
}

if (isOnChat) {
// Redirect unauthenticated users to login page
if (isOnChatPage && !chatConfig.guestUsage.isEnabled) {
if (isLoggedIn) return true;
return false; // Redirect unauthenticated users to login page
}

if (isLoggedIn) {
return Response.redirect(new URL('/', nextUrl as unknown as URL));
return false;
}

return true;
Expand Down
37 changes: 21 additions & 16 deletions app/(chat)/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { requestSuggestions } from '@/lib/ai/tools/request-suggestions';
import { getWeather } from '@/lib/ai/tools/get-weather';
import { isProductionEnvironment } from '@/lib/constants';
import { myProvider } from '@/lib/ai/providers';
import { chatConfig } from '@/lib/chat-config';

export const maxDuration = 60;

Expand All @@ -42,10 +43,13 @@ export async function POST(request: Request) {

const session = await auth();

if (!session || !session.user || !session.user.id) {
if (!chatConfig.guestUsage.isEnabled && !session?.user?.id) {
return new Response('Unauthorized', { status: 401 });
}

const userId = session?.user?.id;
const isAuthenticated = !!userId;

const userMessage = getMostRecentUserMessage(messages);

if (!userMessage) {
Expand All @@ -59,25 +63,26 @@ export async function POST(request: Request) {
message: userMessage,
});

await saveChat({ id, userId: session.user.id, title });
if (isAuthenticated) await saveChat({ id, userId, title });
} else {
if (chat.userId !== session.user.id) {
if (chat.userId !== userId) {
return new Response('Unauthorized', { status: 401 });
}
}

await saveMessages({
messages: [
{
chatId: id,
id: userMessage.id,
role: 'user',
parts: userMessage.parts,
attachments: userMessage.experimental_attachments ?? [],
createdAt: new Date(),
},
],
});
if (isAuthenticated)
await saveMessages({
messages: [
{
chatId: id,
id: userMessage.id,
role: 'user',
parts: userMessage.parts,
attachments: userMessage.experimental_attachments ?? [],
createdAt: new Date(),
},
],
});

return createDataStreamResponse({
execute: (dataStream) => {
Expand Down Expand Up @@ -107,7 +112,7 @@ export async function POST(request: Request) {
}),
},
onFinish: async ({ response }) => {
if (session.user?.id) {
if (isAuthenticated) {
try {
const assistantId = getTrailingMessageId({
messages: response.messages.filter(
Expand Down
146 changes: 96 additions & 50 deletions app/(chat)/api/document/route.ts
Original file line number Diff line number Diff line change
@@ -1,74 +1,104 @@
import { auth } from '@/app/(auth)/auth';
import { chatConfig } from '@/lib/chat-config';
import { ArtifactKind } from '@/components/artifact';
import {
deleteDocumentsByIdAfterTimestamp,
getDocumentsById,
saveDocument,
} from '@/lib/db/queries';

export async function GET(request: Request) {
export async function POST(request: Request) {
const { searchParams } = new URL(request.url);
const id = searchParams.get('id');

if (!id) {
return new Response('Missing id', { status: 400 });
}

const session = await auth();
const {
content,
title,
kind,
}: { content: string; title: string; kind: ArtifactKind } =
await request.json();

if (!session || !session.user) {
return new Response('Unauthorized', { status: 401 });
}
if (chatConfig.guestUsage.isEnabled) {
const guestUserId = process.env.GUEST_USER_ID;

const documents = await getDocumentsById({ id });
if (!guestUserId) {
throw new Error('Guest user ID is not set!');
}

const [document] = documents;
const document = await saveDocument({
id,
content,
title,
kind,
userId: guestUserId,
});

if (!document) {
return new Response('Not Found', { status: 404 });
}
return Response.json(document, { status: 200 });
} else {
const session = await auth();

if (document.userId !== session.user.id) {
return new Response('Unauthorized', { status: 401 });
}
if (!session?.user?.id) {
return new Response('Unauthorized', { status: 401 });
}

return Response.json(documents, { status: 200 });
const document = await saveDocument({
id,
content,
title,
kind,
userId: session.user.id,
});

return Response.json(document, { status: 200 });
}
}

export async function POST(request: Request) {
export async function GET(request: Request) {
const { searchParams } = new URL(request.url);
const id = searchParams.get('id');

if (!id) {
return new Response('Missing id', { status: 400 });
}

const session = await auth();
if (chatConfig.guestUsage.isEnabled) {
const documents = await getDocumentsById({ id });
const [document] = documents;

if (!session) {
return new Response('Unauthorized', { status: 401 });
}
if (!document) {
return new Response('Not Found', { status: 404 });
}

const {
content,
title,
kind,
}: { content: string; title: string; kind: ArtifactKind } =
await request.json();
if (document.userId !== process.env.GUEST_USER_ID) {
return new Response('Unauthorized', { status: 401 });
}

if (session.user?.id) {
const document = await saveDocument({
id,
content,
title,
kind,
userId: session.user.id,
});
return Response.json(documents, { status: 200 });
} else {
const session = await auth();

return Response.json(document, { status: 200 });
}
if (!session?.user?.id) {
return new Response('Unauthorized', { status: 401 });
}

return new Response('Unauthorized', { status: 401 });
const documents = await getDocumentsById({ id });

const [document] = documents;

if (!document) {
return new Response('Not Found', { status: 404 });
}

if (document.userId !== session.user.id) {
return new Response('Unauthorized', { status: 401 });
}

return Response.json(documents, { status: 200 });
}
}

export async function PATCH(request: Request) {
Expand All @@ -81,24 +111,40 @@ export async function PATCH(request: Request) {
return new Response('Missing id', { status: 400 });
}

const session = await auth();
if (chatConfig.guestUsage.isEnabled) {
const documents = await getDocumentsById({ id });
const [document] = documents;

if (!session || !session.user) {
return new Response('Unauthorized', { status: 401 });
}
if (document.userId !== process.env.GUEST_USER_ID) {
return new Response('Unauthorized', { status: 401 });
}

const documents = await getDocumentsById({ id });
await deleteDocumentsByIdAfterTimestamp({
id,
timestamp: new Date(timestamp),
});

const [document] = documents;
return new Response('Deleted', { status: 200 });
} else {
const session = await auth();

if (document.userId !== session.user.id) {
return new Response('Unauthorized', { status: 401 });
}
if (!session?.user?.id) {
return new Response('Unauthorized', { status: 401 });
}

const documents = await getDocumentsById({ id });

await deleteDocumentsByIdAfterTimestamp({
id,
timestamp: new Date(timestamp),
});
const [document] = documents;

return new Response('Deleted', { status: 200 });
if (document.userId !== session.user.id) {
return new Response('Unauthorized', { status: 401 });
}

await deleteDocumentsByIdAfterTimestamp({
id,
timestamp: new Date(timestamp),
});

return new Response('Deleted', { status: 200 });
}
}
3 changes: 2 additions & 1 deletion app/(chat)/api/files/upload/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { NextResponse } from 'next/server';
import { z } from 'zod';

import { auth } from '@/app/(auth)/auth';
import { chatConfig } from '@/lib/chat-config';

// Use Blob instead of File since File is not available in Node.js environment
const FileSchema = z.object({
Expand All @@ -20,7 +21,7 @@ const FileSchema = z.object({
export async function POST(request: Request) {
const session = await auth();

if (!session) {
if (!session && !chatConfig.guestUsage.isEnabled) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}

Expand Down
Loading
Loading