coyotte508 HF staff commited on
Commit
2e28042
1 Parent(s): d71f92c

✨ Backend preparation for "Sign in with HF" (#190)

Browse files
.env CHANGED
@@ -5,6 +5,11 @@ MONGODB_URL=#your mongodb URL here
5
  MONGODB_DB_NAME=chat-ui
6
  COOKIE_NAME=hf-chat
7
  HF_ACCESS_TOKEN=#hf_<token> from from https://huggingface.co/settings/token
 
 
 
 
 
8
  # 'name', 'userMessageToken', 'assistantMessageToken', 'parameters' are required
9
  MODELS=`[
10
  {
 
5
  MONGODB_DB_NAME=chat-ui
6
  COOKIE_NAME=hf-chat
7
  HF_ACCESS_TOKEN=#hf_<token> from from https://huggingface.co/settings/token
8
+
9
+ # Parameters to enable "Sign in with HF"
10
+ HF_CLIENT_ID=
11
+ HF_CLIENT_SECRET=
12
+
13
  # 'name', 'userMessageToken', 'assistantMessageToken', 'parameters' are required
14
  MODELS=`[
15
  {
src/app.d.ts CHANGED
@@ -1,6 +1,8 @@
1
  /// <reference types="@sveltejs/kit" />
2
  /// <reference types="unplugin-icons/types/svelte" />
3
 
 
 
4
  // See https://kit.svelte.dev/docs/types#app
5
  // for information about these interfaces
6
  declare global {
@@ -8,6 +10,7 @@ declare global {
8
  // interface Error {}
9
  interface Locals {
10
  sessionId: string;
 
11
  }
12
  // interface PageData {}
13
  // interface Platform {}
 
1
  /// <reference types="@sveltejs/kit" />
2
  /// <reference types="unplugin-icons/types/svelte" />
3
 
4
+ import type { ObjectId } from "mongodb";
5
+
6
  // See https://kit.svelte.dev/docs/types#app
7
  // for information about these interfaces
8
  declare global {
 
10
  // interface Error {}
11
  interface Locals {
12
  sessionId: string;
13
+ userId?: ObjectId;
14
  }
15
  // interface PageData {}
16
  // interface Platform {}
src/hooks.server.ts CHANGED
@@ -8,38 +8,61 @@ import {
8
  import { addYears } from "date-fns";
9
  import { collections } from "$lib/server/database";
10
  import { base } from "$app/paths";
 
11
 
12
  export const handle: Handle = async ({ event, resolve }) => {
13
  const token = event.cookies.get(COOKIE_NAME);
14
 
15
  event.locals.sessionId = token || crypto.randomUUID();
16
 
 
 
 
 
 
 
17
  if (
18
- event.request.method === "POST" &&
19
- !event.url.pathname.startsWith(`${base}/settings`) &&
20
- !event.url.pathname.startsWith(`${base}/admin`)
21
  ) {
22
- const hasAcceptedEthicsModal = await collections.settings.countDocuments({
23
- sessionId: event.locals.sessionId,
24
- ethicsModalAcceptedAt: { $exists: true },
25
- });
26
 
27
- if (!hasAcceptedEthicsModal) {
28
- const sendJson =
29
- event.request.headers.get("accept")?.includes("application/json") ||
30
- event.request.headers.get("content-type")?.includes("application/json");
31
  return new Response(
32
  sendJson
33
- ? JSON.stringify({ error: "You need to accept the welcome modal first" })
34
- : "You need to accept the welcome modal first",
35
  {
36
- status: 405,
37
  headers: {
38
  "content-type": sendJson ? "application/json" : "text/plain",
39
  },
40
  }
41
  );
42
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  }
44
 
45
  // Refresh cookie expiration date
 
8
  import { addYears } from "date-fns";
9
  import { collections } from "$lib/server/database";
10
  import { base } from "$app/paths";
11
+ import { requiresUser } from "$lib/server/auth";
12
 
13
  export const handle: Handle = async ({ event, resolve }) => {
14
  const token = event.cookies.get(COOKIE_NAME);
15
 
16
  event.locals.sessionId = token || crypto.randomUUID();
17
 
18
+ const user = await collections.users.findOne({ sessionId: event.locals.sessionId });
19
+
20
+ if (user) {
21
+ event.locals.userId = user._id;
22
+ }
23
+
24
  if (
25
+ !event.url.pathname.startsWith(`${base}/admin`) &&
26
+ !["GET", "OPTIONS", "HEAD"].includes(event.request.method)
 
27
  ) {
28
+ const sendJson =
29
+ event.request.headers.get("accept")?.includes("application/json") ||
30
+ event.request.headers.get("content-type")?.includes("application/json");
 
31
 
32
+ if (!user && requiresUser) {
 
 
 
33
  return new Response(
34
  sendJson
35
+ ? JSON.stringify({ error: "You need to be logged in first" })
36
+ : "You need to be logged in first",
37
  {
38
+ status: 401,
39
  headers: {
40
  "content-type": sendJson ? "application/json" : "text/plain",
41
  },
42
  }
43
  );
44
  }
45
+
46
+ if (!event.url.pathname.startsWith(`${base}/settings`)) {
47
+ const hasAcceptedEthicsModal = await collections.settings.countDocuments({
48
+ sessionId: event.locals.sessionId,
49
+ ethicsModalAcceptedAt: { $exists: true },
50
+ });
51
+
52
+ if (!hasAcceptedEthicsModal) {
53
+ return new Response(
54
+ sendJson
55
+ ? JSON.stringify({ error: "You need to accept the welcome modal first" })
56
+ : "You need to accept the welcome modal first",
57
+ {
58
+ status: 405,
59
+ headers: {
60
+ "content-type": sendJson ? "application/json" : "text/plain",
61
+ },
62
+ }
63
+ );
64
+ }
65
+ }
66
  }
67
 
68
  // Refresh cookie expiration date
src/lib/server/auth.ts ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ import { HF_CLIENT_ID, HF_CLIENT_SECRET } from "$env/static/private";
2
+
3
+ export const requiresUser = !!HF_CLIENT_ID && !!HF_CLIENT_SECRET;
4
+
5
+ export const authCondition = (locals: App.Locals) => {
6
+ return locals.userId
7
+ ? { userId: locals.userId }
8
+ : { sessionId: locals.sessionId, userId: { $exists: false } };
9
+ };
src/lib/server/database.ts CHANGED
@@ -4,6 +4,7 @@ import type { Conversation } from "$lib/types/Conversation";
4
  import type { SharedConversation } from "$lib/types/SharedConversation";
5
  import type { AbortedGeneration } from "$lib/types/AbortedGeneration";
6
  import type { Settings } from "$lib/types/Settings";
 
7
 
8
  const client = new MongoClient(MONGODB_URL, {
9
  // directConnection: true
@@ -17,15 +18,35 @@ const conversations = db.collection<Conversation>("conversations");
17
  const sharedConversations = db.collection<SharedConversation>("sharedConversations");
18
  const abortedGenerations = db.collection<AbortedGeneration>("abortedGenerations");
19
  const settings = db.collection<Settings>("settings");
 
20
 
21
  export { client, db };
22
- export const collections = { conversations, sharedConversations, abortedGenerations, settings };
 
 
 
 
 
 
23
 
24
  client.on("open", () => {
25
- conversations.createIndex({ sessionId: 1, updatedAt: -1 });
26
- abortedGenerations.createIndex({ updatedAt: 1 }, { expireAfterSeconds: 30 });
27
- abortedGenerations.createIndex({ conversationId: 1 }, { unique: true });
28
- sharedConversations.createIndex({ hash: 1 }, { unique: true });
29
- // Sparse so that we can have settings on userId later
30
- settings.createIndex({ sessionId: 1 }, { unique: true, sparse: true });
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  });
 
4
  import type { SharedConversation } from "$lib/types/SharedConversation";
5
  import type { AbortedGeneration } from "$lib/types/AbortedGeneration";
6
  import type { Settings } from "$lib/types/Settings";
7
+ import type { User } from "$lib/types/User";
8
 
9
  const client = new MongoClient(MONGODB_URL, {
10
  // directConnection: true
 
18
  const sharedConversations = db.collection<SharedConversation>("sharedConversations");
19
  const abortedGenerations = db.collection<AbortedGeneration>("abortedGenerations");
20
  const settings = db.collection<Settings>("settings");
21
+ const users = db.collection<User>("users");
22
 
23
  export { client, db };
24
+ export const collections = {
25
+ conversations,
26
+ sharedConversations,
27
+ abortedGenerations,
28
+ settings,
29
+ users,
30
+ };
31
 
32
  client.on("open", () => {
33
+ conversations
34
+ .createIndex(
35
+ { sessionId: 1, updatedAt: -1 },
36
+ { partialFilterExpression: { sessionId: { $exists: true } } }
37
+ )
38
+ .catch(console.error);
39
+ conversations
40
+ .createIndex(
41
+ { userId: 1, updatedAt: -1 },
42
+ { partialFilterExpression: { userId: { $exists: true } } }
43
+ )
44
+ .catch(console.error);
45
+ abortedGenerations.createIndex({ updatedAt: 1 }, { expireAfterSeconds: 30 }).catch(console.error);
46
+ abortedGenerations.createIndex({ conversationId: 1 }, { unique: true }).catch(console.error);
47
+ sharedConversations.createIndex({ hash: 1 }, { unique: true }).catch(console.error);
48
+ settings.createIndex({ sessionId: 1 }, { unique: true, sparse: true }).catch(console.error);
49
+ settings.createIndex({ userId: 1 }, { unique: true, sparse: true }).catch(console.error);
50
+ users.createIndex({ hfUserId: 1 }, { unique: true }).catch(console.error);
51
+ users.createIndex({ sessionId: 1 }, { unique: true, sparse: true }).catch(console.error);
52
  });
src/lib/types/Conversation.ts CHANGED
@@ -1,12 +1,13 @@
1
  import type { ObjectId } from "mongodb";
2
  import type { Message } from "./Message";
3
  import type { Timestamps } from "./Timestamps";
 
4
 
5
  export interface Conversation extends Timestamps {
6
  _id: ObjectId;
7
 
8
- // Can be undefined for shared convo then deleted
9
- sessionId: string;
10
 
11
  model: string;
12
 
 
1
  import type { ObjectId } from "mongodb";
2
  import type { Message } from "./Message";
3
  import type { Timestamps } from "./Timestamps";
4
+ import type { User } from "./User";
5
 
6
  export interface Conversation extends Timestamps {
7
  _id: ObjectId;
8
 
9
+ sessionId?: string;
10
+ userId?: User["_id"];
11
 
12
  model: string;
13
 
src/lib/types/Settings.ts CHANGED
@@ -1,7 +1,9 @@
1
  import type { Timestamps } from "./Timestamps";
 
2
 
3
  export interface Settings extends Timestamps {
4
- sessionId: string;
 
5
 
6
  /**
7
  * Note: Only conversations with this settings explictly set to true should be shared.
 
1
  import type { Timestamps } from "./Timestamps";
2
+ import type { User } from "./User";
3
 
4
  export interface Settings extends Timestamps {
5
+ userId?: User["_id"];
6
+ sessionId?: string;
7
 
8
  /**
9
  * Note: Only conversations with this settings explictly set to true should be shared.
src/lib/types/User.ts ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { ObjectId } from "mongodb";
2
+ import type { Timestamps } from "./Timestamps";
3
+
4
+ export interface User extends Timestamps {
5
+ _id: ObjectId;
6
+
7
+ username: string;
8
+ name: string;
9
+ avatarUrl: string;
10
+ hfUserId: string;
11
+
12
+ // Session identifier, stored in the cookie
13
+ sessionId?: string;
14
+ }
src/routes/+layout.server.ts CHANGED
@@ -5,6 +5,7 @@ import type { Conversation } from "$lib/types/Conversation";
5
  import { UrlDependency } from "$lib/types/UrlDependency";
6
  import { defaultModel, models } from "$lib/server/models";
7
  import { validateModel } from "$lib/utils/models";
 
8
 
9
  export const load: LayoutServerLoad = async ({ locals, depends, url }) => {
10
  const { conversations } = collections;
@@ -17,7 +18,7 @@ export const load: LayoutServerLoad = async ({ locals, depends, url }) => {
17
 
18
  if (isValidModel) {
19
  await collections.settings.updateOne(
20
- { sessionId: locals.sessionId },
21
  { $set: { activeModel: urlModel } },
22
  { upsert: true }
23
  );
@@ -26,13 +27,11 @@ export const load: LayoutServerLoad = async ({ locals, depends, url }) => {
26
  throw redirect(302, url.pathname);
27
  }
28
 
29
- const settings = await collections.settings.findOne({ sessionId: locals.sessionId });
30
 
31
  return {
32
  conversations: await conversations
33
- .find({
34
- sessionId: locals.sessionId,
35
- })
36
  .sort({ updatedAt: -1 })
37
  .project<Pick<Conversation, "title" | "model" | "_id" | "updatedAt" | "createdAt">>({
38
  title: 1,
 
5
  import { UrlDependency } from "$lib/types/UrlDependency";
6
  import { defaultModel, models } from "$lib/server/models";
7
  import { validateModel } from "$lib/utils/models";
8
+ import { authCondition } from "$lib/server/auth";
9
 
10
  export const load: LayoutServerLoad = async ({ locals, depends, url }) => {
11
  const { conversations } = collections;
 
18
 
19
  if (isValidModel) {
20
  await collections.settings.updateOne(
21
+ authCondition(locals),
22
  { $set: { activeModel: urlModel } },
23
  { upsert: true }
24
  );
 
27
  throw redirect(302, url.pathname);
28
  }
29
 
30
+ const settings = await collections.settings.findOne(authCondition(locals));
31
 
32
  return {
33
  conversations: await conversations
34
+ .find(authCondition(locals))
 
 
35
  .sort({ updatedAt: -1 })
36
  .project<Pick<Conversation, "title" | "model" | "_id" | "updatedAt" | "createdAt">>({
37
  title: 1,
src/routes/+page.svelte CHANGED
@@ -4,7 +4,7 @@
4
  import ChatWindow from "$lib/components/chat/ChatWindow.svelte";
5
  import { ERROR_MESSAGES, error } from "$lib/stores/errors";
6
  import { pendingMessage } from "$lib/stores/pendingMessage";
7
- import { findCurrentModel } from "$lib/utils/models.js";
8
 
9
  export let data;
10
  let loading = false;
 
4
  import ChatWindow from "$lib/components/chat/ChatWindow.svelte";
5
  import { ERROR_MESSAGES, error } from "$lib/stores/errors";
6
  import { pendingMessage } from "$lib/stores/pendingMessage";
7
+ import { findCurrentModel } from "$lib/utils/models";
8
 
9
  export let data;
10
  let loading = false;
src/routes/admin/export/+server.ts CHANGED
@@ -3,8 +3,8 @@ import {
3
  PARQUET_EXPORT_HF_TOKEN,
4
  PARQUET_EXPORT_SECRET,
5
  } from "$env/static/private";
6
- import { collections } from "$lib/server/database.js";
7
- import type { Message } from "$lib/types/Message.js";
8
  import { error } from "@sveltejs/kit";
9
  import { pathToFileURL } from "node:url";
10
  import { unlink } from "node:fs/promises";
 
3
  PARQUET_EXPORT_HF_TOKEN,
4
  PARQUET_EXPORT_SECRET,
5
  } from "$env/static/private";
6
+ import { collections } from "$lib/server/database";
7
+ import type { Message } from "$lib/types/Message";
8
  import { error } from "@sveltejs/kit";
9
  import { pathToFileURL } from "node:url";
10
  import { unlink } from "node:fs/promises";
src/routes/conversation/+server.ts CHANGED
@@ -7,9 +7,10 @@ import { z } from "zod";
7
  import type { Message } from "$lib/types/Message";
8
  import { models } from "$lib/server/models";
9
  import { validateModel } from "$lib/utils/models";
 
10
 
11
- export const POST: RequestHandler = async (input) => {
12
- const body = await input.request.text();
13
 
14
  let title = "";
15
  let messages: Message[] = [];
@@ -39,14 +40,12 @@ export const POST: RequestHandler = async (input) => {
39
  _id: new ObjectId(),
40
  title:
41
  title ||
42
- "Untitled " +
43
- ((await collections.conversations.countDocuments({ sessionId: input.locals.sessionId })) +
44
- 1),
45
  messages,
46
  model: values.model,
47
  createdAt: new Date(),
48
  updatedAt: new Date(),
49
- sessionId: input.locals.sessionId,
50
  ...(values.fromShare ? { meta: { fromShareId: values.fromShare } } : {}),
51
  });
52
 
 
7
  import type { Message } from "$lib/types/Message";
8
  import { models } from "$lib/server/models";
9
  import { validateModel } from "$lib/utils/models";
10
+ import { authCondition } from "$lib/server/auth";
11
 
12
+ export const POST: RequestHandler = async ({ locals, request }) => {
13
+ const body = await request.text();
14
 
15
  let title = "";
16
  let messages: Message[] = [];
 
40
  _id: new ObjectId(),
41
  title:
42
  title ||
43
+ "Untitled " + ((await collections.conversations.countDocuments(authCondition(locals))) + 1),
 
 
44
  messages,
45
  model: values.model,
46
  createdAt: new Date(),
47
  updatedAt: new Date(),
48
+ ...(locals.userId ? { userId: locals.userId } : { sessionId: locals.sessionId }),
49
  ...(values.fromShare ? { meta: { fromShareId: values.fromShare } } : {}),
50
  });
51
 
src/routes/conversation/[id]/+page.server.ts CHANGED
@@ -1,19 +1,19 @@
1
- import type { PageServerLoad } from "./$types";
2
  import { collections } from "$lib/server/database";
3
  import { ObjectId } from "mongodb";
4
  import { error } from "@sveltejs/kit";
 
5
 
6
- export const load: PageServerLoad = async (event) => {
7
  // todo: add validation on params.id
8
  const conversation = await collections.conversations.findOne({
9
- _id: new ObjectId(event.params.id),
10
- sessionId: event.locals.sessionId,
11
  });
12
 
13
  if (!conversation) {
14
  const conversationExists =
15
  (await collections.conversations.countDocuments({
16
- _id: new ObjectId(event.params.id),
17
  })) !== 0;
18
 
19
  if (conversationExists) {
 
 
1
  import { collections } from "$lib/server/database";
2
  import { ObjectId } from "mongodb";
3
  import { error } from "@sveltejs/kit";
4
+ import { authCondition } from "$lib/server/auth";
5
 
6
+ export const load = async ({ params, locals }) => {
7
  // todo: add validation on params.id
8
  const conversation = await collections.conversations.findOne({
9
+ _id: new ObjectId(params.id),
10
+ ...authCondition(locals),
11
  });
12
 
13
  if (!conversation) {
14
  const conversationExists =
15
  (await collections.conversations.countDocuments({
16
+ _id: new ObjectId(params.id),
17
  })) !== 0;
18
 
19
  if (conversationExists) {
src/routes/conversation/[id]/+page.svelte CHANGED
@@ -11,7 +11,7 @@
11
  import { UrlDependency } from "$lib/types/UrlDependency";
12
  import { ERROR_MESSAGES, error } from "$lib/stores/errors";
13
  import { randomUUID } from "$lib/utils/randomUuid";
14
- import { findCurrentModel } from "$lib/utils/models.js";
15
 
16
  export let data;
17
 
 
11
  import { UrlDependency } from "$lib/types/UrlDependency";
12
  import { ERROR_MESSAGES, error } from "$lib/stores/errors";
13
  import { randomUUID } from "$lib/utils/randomUuid";
14
+ import { findCurrentModel } from "$lib/utils/models";
15
 
16
  export let data;
17
 
src/routes/conversation/[id]/+server.ts CHANGED
@@ -1,14 +1,15 @@
1
- import { buildPrompt } from "$lib/buildPrompt.js";
2
- import { PUBLIC_SEP_TOKEN } from "$lib/constants/publicSepToken.js";
3
- import { abortedGenerations } from "$lib/server/abortedGenerations.js";
4
- import { collections } from "$lib/server/database.js";
5
- import { modelEndpoint } from "$lib/server/modelEndpoint.js";
6
- import { models } from "$lib/server/models.js";
7
- import type { Message } from "$lib/types/Message.js";
8
- import { concatUint8Arrays } from "$lib/utils/concatUint8Arrays.js";
 
9
  import { streamToAsyncIterable } from "$lib/utils/streamToAsyncIterable";
10
- import { trimPrefix } from "$lib/utils/trimPrefix.js";
11
- import { trimSuffix } from "$lib/utils/trimSuffix.js";
12
  import type { TextGenerationStreamOutput } from "@huggingface/inference";
13
  import { error } from "@sveltejs/kit";
14
  import { ObjectId } from "mongodb";
@@ -21,7 +22,7 @@ export async function POST({ request, fetch, locals, params }) {
21
 
22
  const conv = await collections.conversations.findOne({
23
  _id: convId,
24
- sessionId: locals.sessionId,
25
  });
26
 
27
  if (!conv) {
@@ -139,7 +140,7 @@ export async function DELETE({ locals, params }) {
139
 
140
  const conv = await collections.conversations.findOne({
141
  _id: convId,
142
- sessionId: locals.sessionId,
143
  });
144
 
145
  if (!conv) {
@@ -228,7 +229,7 @@ export async function PATCH({ request, locals, params }) {
228
 
229
  const conv = await collections.conversations.findOne({
230
  _id: convId,
231
- sessionId: locals.sessionId,
232
  });
233
 
234
  if (!conv) {
 
1
+ import { buildPrompt } from "$lib/buildPrompt";
2
+ import { PUBLIC_SEP_TOKEN } from "$lib/constants/publicSepToken";
3
+ import { abortedGenerations } from "$lib/server/abortedGenerations";
4
+ import { authCondition } from "$lib/server/auth";
5
+ import { collections } from "$lib/server/database";
6
+ import { modelEndpoint } from "$lib/server/modelEndpoint";
7
+ import { models } from "$lib/server/models";
8
+ import type { Message } from "$lib/types/Message";
9
+ import { concatUint8Arrays } from "$lib/utils/concatUint8Arrays";
10
  import { streamToAsyncIterable } from "$lib/utils/streamToAsyncIterable";
11
+ import { trimPrefix } from "$lib/utils/trimPrefix";
12
+ import { trimSuffix } from "$lib/utils/trimSuffix";
13
  import type { TextGenerationStreamOutput } from "@huggingface/inference";
14
  import { error } from "@sveltejs/kit";
15
  import { ObjectId } from "mongodb";
 
22
 
23
  const conv = await collections.conversations.findOne({
24
  _id: convId,
25
+ ...authCondition(locals),
26
  });
27
 
28
  if (!conv) {
 
140
 
141
  const conv = await collections.conversations.findOne({
142
  _id: convId,
143
+ ...authCondition(locals),
144
  });
145
 
146
  if (!conv) {
 
229
 
230
  const conv = await collections.conversations.findOne({
231
  _id: convId,
232
+ ...authCondition(locals),
233
  });
234
 
235
  if (!conv) {
src/routes/conversation/[id]/message/[messageId]/prompt/+server.ts CHANGED
@@ -1,6 +1,7 @@
1
- import { buildPrompt } from "$lib/buildPrompt.js";
 
2
  import { collections } from "$lib/server/database";
3
- import { models } from "$lib/server/models.js";
4
  import { error } from "@sveltejs/kit";
5
  import { ObjectId } from "mongodb";
6
 
@@ -9,7 +10,7 @@ export async function GET({ params, locals }) {
9
 
10
  const conv = await collections.conversations.findOne({
11
  _id: convId,
12
- sessionId: locals.sessionId,
13
  });
14
 
15
  if (!conv) {
 
1
+ import { buildPrompt } from "$lib/buildPrompt";
2
+ import { authCondition } from "$lib/server/auth";
3
  import { collections } from "$lib/server/database";
4
+ import { models } from "$lib/server/models";
5
  import { error } from "@sveltejs/kit";
6
  import { ObjectId } from "mongodb";
7
 
 
10
 
11
  const conv = await collections.conversations.findOne({
12
  _id: convId,
13
+ ...authCondition(locals),
14
  });
15
 
16
  if (!conv) {
src/routes/conversation/[id]/share/+server.ts CHANGED
@@ -1,8 +1,9 @@
1
  import { base } from "$app/paths";
2
  import { PUBLIC_ORIGIN } from "$env/static/public";
3
- import { collections } from "$lib/server/database.js";
4
- import type { SharedConversation } from "$lib/types/SharedConversation.js";
5
- import { sha256 } from "$lib/utils/sha256.js";
 
6
  import { error } from "@sveltejs/kit";
7
  import { ObjectId } from "mongodb";
8
  import { nanoid } from "nanoid";
@@ -10,7 +11,7 @@ import { nanoid } from "nanoid";
10
  export async function POST({ params, url, locals }) {
11
  const conversation = await collections.conversations.findOne({
12
  _id: new ObjectId(params.id),
13
- sessionId: locals.sessionId,
14
  });
15
 
16
  if (!conversation) {
 
1
  import { base } from "$app/paths";
2
  import { PUBLIC_ORIGIN } from "$env/static/public";
3
+ import { authCondition } from "$lib/server/auth";
4
+ import { collections } from "$lib/server/database";
5
+ import type { SharedConversation } from "$lib/types/SharedConversation";
6
+ import { sha256 } from "$lib/utils/sha256";
7
  import { error } from "@sveltejs/kit";
8
  import { ObjectId } from "mongodb";
9
  import { nanoid } from "nanoid";
 
11
  export async function POST({ params, url, locals }) {
12
  const conversation = await collections.conversations.findOne({
13
  _id: new ObjectId(params.id),
14
+ ...authCondition(locals),
15
  });
16
 
17
  if (!conversation) {
src/routes/conversation/[id]/stop-generating/+server.ts CHANGED
@@ -1,3 +1,4 @@
 
1
  import { collections } from "$lib/server/database";
2
  import { error } from "@sveltejs/kit";
3
  import { ObjectId } from "mongodb";
@@ -10,7 +11,7 @@ export async function POST({ params, locals }) {
10
 
11
  const conversation = await collections.conversations.findOne({
12
  _id: conversationId,
13
- sessionId: locals.sessionId,
14
  });
15
 
16
  if (!conversation) {
 
1
+ import { authCondition } from "$lib/server/auth";
2
  import { collections } from "$lib/server/database";
3
  import { error } from "@sveltejs/kit";
4
  import { ObjectId } from "mongodb";
 
11
 
12
  const conversation = await collections.conversations.findOne({
13
  _id: conversationId,
14
+ ...authCondition(locals),
15
  });
16
 
17
  if (!conversation) {
src/routes/conversation/[id]/summarize/+server.ts CHANGED
@@ -1,10 +1,11 @@
1
  import { buildPrompt } from "$lib/buildPrompt";
2
- import { PUBLIC_SEP_TOKEN } from "$lib/constants/publicSepToken.js";
3
- import { collections } from "$lib/server/database.js";
4
- import { modelEndpoint } from "$lib/server/modelEndpoint.js";
5
- import { defaultModel } from "$lib/server/models.js";
6
- import { trimPrefix } from "$lib/utils/trimPrefix.js";
7
- import { trimSuffix } from "$lib/utils/trimSuffix.js";
 
8
  import { textGeneration } from "@huggingface/inference";
9
  import { error } from "@sveltejs/kit";
10
  import { ObjectId } from "mongodb";
@@ -14,7 +15,7 @@ export async function POST({ params, locals, fetch }) {
14
 
15
  const conversation = await collections.conversations.findOne({
16
  _id: convId,
17
- sessionId: locals.sessionId,
18
  });
19
 
20
  if (!conversation) {
@@ -56,7 +57,7 @@ export async function POST({ params, locals, fetch }) {
56
  await collections.conversations.updateOne(
57
  {
58
  _id: convId,
59
- sessionId: locals.sessionId,
60
  },
61
  {
62
  $set: { title: generated_text },
 
1
  import { buildPrompt } from "$lib/buildPrompt";
2
+ import { PUBLIC_SEP_TOKEN } from "$lib/constants/publicSepToken";
3
+ import { authCondition } from "$lib/server/auth";
4
+ import { collections } from "$lib/server/database";
5
+ import { modelEndpoint } from "$lib/server/modelEndpoint";
6
+ import { defaultModel } from "$lib/server/models";
7
+ import { trimPrefix } from "$lib/utils/trimPrefix";
8
+ import { trimSuffix } from "$lib/utils/trimSuffix";
9
  import { textGeneration } from "@huggingface/inference";
10
  import { error } from "@sveltejs/kit";
11
  import { ObjectId } from "mongodb";
 
15
 
16
  const conversation = await collections.conversations.findOne({
17
  _id: convId,
18
+ ...authCondition(locals),
19
  });
20
 
21
  if (!conversation) {
 
57
  await collections.conversations.updateOne(
58
  {
59
  _id: convId,
60
+ ...authCondition(locals),
61
  },
62
  {
63
  $set: { title: generated_text },
src/routes/r/[id]/message/[messageId]/prompt/+server.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { buildPrompt } from "$lib/buildPrompt.js";
2
  import { collections } from "$lib/server/database";
3
- import { models } from "$lib/server/models.js";
4
  import { error } from "@sveltejs/kit";
5
 
6
  export async function GET({ params }) {
 
1
+ import { buildPrompt } from "$lib/buildPrompt";
2
  import { collections } from "$lib/server/database";
3
+ import { models } from "$lib/server/models";
4
  import { error } from "@sveltejs/kit";
5
 
6
  export async function GET({ params }) {
src/routes/settings/+page.server.ts CHANGED
@@ -3,7 +3,8 @@ import { collections } from "$lib/server/database";
3
  import { redirect } from "@sveltejs/kit";
4
  import { z } from "zod";
5
  import { defaultModel, models } from "$lib/server/models";
6
- import { validateModel } from "$lib/utils/models.js";
 
7
 
8
  export const actions = {
9
  default: async function ({ request, locals }) {
@@ -22,9 +23,7 @@ export const actions = {
22
  });
23
 
24
  await collections.settings.updateOne(
25
- {
26
- sessionId: locals.sessionId,
27
- },
28
  {
29
  $set: {
30
  ...settings,
 
3
  import { redirect } from "@sveltejs/kit";
4
  import { z } from "zod";
5
  import { defaultModel, models } from "$lib/server/models";
6
+ import { validateModel } from "$lib/utils/models";
7
+ import { authCondition } from "$lib/server/auth";
8
 
9
  export const actions = {
10
  default: async function ({ request, locals }) {
 
23
  });
24
 
25
  await collections.settings.updateOne(
26
+ authCondition(locals),
 
 
27
  {
28
  $set: {
29
  ...settings,