nsarrazin HF Staff commited on
Commit
501bbaa
·
unverified ·
1 Parent(s): 5f03c37

Let users access the API using their HF token (#1216)

Browse files
.env CHANGED
@@ -143,6 +143,7 @@ PUBLIC_APP_DISCLAIMER_MESSAGE="Disclaimer: AI is an area of active research with
143
  LLM_SUMMARIZATION=true
144
 
145
  EXPOSE_API=true
 
146
  # PUBLIC_APP_NAME=HuggingChat
147
  # PUBLIC_APP_ASSETS=huggingchat
148
  # PUBLIC_APP_COLOR=yellow
 
143
  LLM_SUMMARIZATION=true
144
 
145
  EXPOSE_API=true
146
+ USE_HF_TOKEN_IN_API=false
147
  # PUBLIC_APP_NAME=HuggingChat
148
  # PUBLIC_APP_ASSETS=huggingchat
149
  # PUBLIC_APP_COLOR=yellow
src/hooks.server.ts CHANGED
@@ -110,8 +110,8 @@ export const handle: Handle = async ({ event, resolve }) => {
110
  ? event.request.headers.get(env.TRUSTED_EMAIL_HEADER)
111
  : null;
112
 
113
- let secretSessionId: string;
114
- let sessionId: string;
115
 
116
  if (email) {
117
  secretSessionId = sessionId = await sha256(email);
@@ -136,8 +136,63 @@ export const handle: Handle = async ({ event, resolve }) => {
136
  if (user) {
137
  event.locals.user = user;
138
  }
139
- } else {
140
- // if the user doesn't have any cookie, we generate one for him
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
141
  secretSessionId = crypto.randomUUID();
142
  sessionId = await sha256(secretSessionId);
143
 
 
110
  ? event.request.headers.get(env.TRUSTED_EMAIL_HEADER)
111
  : null;
112
 
113
+ let secretSessionId: string | null = null;
114
+ let sessionId: string | null = null;
115
 
116
  if (email) {
117
  secretSessionId = sessionId = await sha256(email);
 
136
  if (user) {
137
  event.locals.user = user;
138
  }
139
+ } else if (event.url.pathname.startsWith(`${base}/api/`) && env.USE_HF_TOKEN_IN_API === "true") {
140
+ // if the request goes to the API and no user is available in the header
141
+ // check if a bearer token is available in the Authorization header
142
+
143
+ const authorization = event.request.headers.get("Authorization");
144
+
145
+ if (authorization && authorization.startsWith("Bearer ")) {
146
+ const token = authorization.slice(7);
147
+
148
+ const hash = await sha256(token);
149
+
150
+ sessionId = secretSessionId = hash;
151
+
152
+ // check if the hash is in the DB and get the user
153
+ // else check against https://huggingface.co/api/whoami-v2
154
+
155
+ const cacheHit = await collections.tokenCaches.findOne({ tokenHash: hash });
156
+
157
+ if (cacheHit) {
158
+ const user = await collections.users.findOne({ hfUserId: cacheHit.userId });
159
+
160
+ if (!user) {
161
+ return errorResponse(500, "User not found");
162
+ }
163
+
164
+ event.locals.user = user;
165
+ } else {
166
+ const response = await fetch("https://huggingface.co/api/whoami-v2", {
167
+ headers: {
168
+ Authorization: `Bearer ${token}`,
169
+ },
170
+ });
171
+
172
+ if (!response.ok) {
173
+ return errorResponse(401, "Unauthorized");
174
+ }
175
+
176
+ const data = await response.json();
177
+ const user = await collections.users.findOne({ hfUserId: data.id });
178
+
179
+ if (!user) {
180
+ return errorResponse(500, "User not found");
181
+ }
182
+
183
+ await collections.tokenCaches.insertOne({
184
+ tokenHash: hash,
185
+ userId: data.id,
186
+ createdAt: new Date(),
187
+ updatedAt: new Date(),
188
+ });
189
+
190
+ event.locals.user = user;
191
+ }
192
+ }
193
+ }
194
+
195
+ if (!sessionId || !secretSessionId) {
196
  secretSessionId = crypto.randomUUID();
197
  sessionId = await sha256(secretSessionId);
198
 
src/lib/server/database.ts CHANGED
@@ -17,6 +17,7 @@ import type { CommunityToolDB } from "$lib/types/Tool";
17
 
18
  import { logger } from "$lib/server/logger";
19
  import { building } from "$app/environment";
 
20
  import { onExit } from "./exitHandler";
21
 
22
  export const CONVERSATION_STATS_COLLECTION = "conversations.stats";
@@ -85,6 +86,7 @@ export class Database {
85
  const bucket = new GridFSBucket(db, { bucketName: "files" });
86
  const migrationResults = db.collection<MigrationResult>("migrationResults");
87
  const semaphores = db.collection<Semaphore>("semaphores");
 
88
  const tools = db.collection<CommunityToolDB>("tools");
89
 
90
  return {
@@ -102,6 +104,7 @@ export class Database {
102
  bucket,
103
  migrationResults,
104
  semaphores,
 
105
  tools,
106
  };
107
  }
@@ -124,6 +127,7 @@ export class Database {
124
  sessions,
125
  messageEvents,
126
  semaphores,
 
127
  tools,
128
  } = this.getCollections();
129
 
@@ -217,7 +221,10 @@ export class Database {
217
  semaphores
218
  .createIndex({ createdAt: 1 }, { expireAfterSeconds: 60 })
219
  .catch((e) => logger.error(e));
220
-
 
 
 
221
  tools.createIndex({ createdById: 1, userCount: -1 }).catch((e) => logger.error(e));
222
  tools.createIndex({ userCount: 1 }).catch((e) => logger.error(e));
223
  tools.createIndex({ last24HoursCount: 1 }).catch((e) => logger.error(e));
 
17
 
18
  import { logger } from "$lib/server/logger";
19
  import { building } from "$app/environment";
20
+ import type { TokenCache } from "$lib/types/TokenCache";
21
  import { onExit } from "./exitHandler";
22
 
23
  export const CONVERSATION_STATS_COLLECTION = "conversations.stats";
 
86
  const bucket = new GridFSBucket(db, { bucketName: "files" });
87
  const migrationResults = db.collection<MigrationResult>("migrationResults");
88
  const semaphores = db.collection<Semaphore>("semaphores");
89
+ const tokenCaches = db.collection<TokenCache>("tokens");
90
  const tools = db.collection<CommunityToolDB>("tools");
91
 
92
  return {
 
104
  bucket,
105
  migrationResults,
106
  semaphores,
107
+ tokenCaches,
108
  tools,
109
  };
110
  }
 
127
  sessions,
128
  messageEvents,
129
  semaphores,
130
+ tokenCaches,
131
  tools,
132
  } = this.getCollections();
133
 
 
221
  semaphores
222
  .createIndex({ createdAt: 1 }, { expireAfterSeconds: 60 })
223
  .catch((e) => logger.error(e));
224
+ tokenCaches
225
+ .createIndex({ createdAt: 1 }, { expireAfterSeconds: 5 * 60 })
226
+ .catch((e) => logger.error(e));
227
+ tokenCaches.createIndex({ tokenHash: 1 }).catch((e) => logger.error(e));
228
  tools.createIndex({ createdById: 1, userCount: -1 }).catch((e) => logger.error(e));
229
  tools.createIndex({ userCount: 1 }).catch((e) => logger.error(e));
230
  tools.createIndex({ last24HoursCount: 1 }).catch((e) => logger.error(e));
src/lib/types/TokenCache.ts ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ import type { Timestamps } from "./Timestamps";
2
+
3
+ export interface TokenCache extends Timestamps {
4
+ tokenHash: string; // sha256 of the bearer token
5
+ userId: string; // the matching hf user id
6
+ }