MCPcopy Index your code
hub / github.com/sourcebot-dev/sourcebot / getAuthenticatedUser

Function getAuthenticatedUser

packages/web/src/middleware/withAuth.ts:134–230  ·  view source on GitHub ↗
()

Source from the content-addressed store, hash-verified

132type AuthSource = 'session' | 'oauth' | 'api_key';
133
134export const getAuthenticatedUser = async (): Promise<{ user: UserWithAccounts, source: AuthSource } | undefined> => {
135 // First, check if we have a valid JWT session.
136 const session = await auth();
137 if (session) {
138 const userId = session.user.id;
139 const user = await __unsafePrisma.user.findUnique({
140 where: {
141 id: userId,
142 },
143 include: {
144 accounts: true,
145 }
146 });
147
148 return user ? { user, source: 'session' } : undefined;
149 }
150
151 // If not, check for a Bearer token in the Authorization header.
152 const authorizationHeader = (await headers()).get("Authorization") ?? undefined;
153 if (authorizationHeader?.startsWith("Bearer ")) {
154 const bearerToken = authorizationHeader.slice(7);
155
156 // OAuth access token
157 if (bearerToken.startsWith(OAUTH_ACCESS_TOKEN_PREFIX)) {
158 if (!await hasEntitlement('oauth')) {
159 return undefined;
160 }
161
162 const secret = bearerToken.slice(OAUTH_ACCESS_TOKEN_PREFIX.length);
163 const hash = hashSecret(secret);
164 const oauthToken = await __unsafePrisma.oAuthToken.findUnique({
165 where: { hash },
166 include: { user: { include: { accounts: true } } },
167 });
168 if (oauthToken && oauthToken.expiresAt > new Date()) {
169 await __unsafePrisma.oAuthToken.update({
170 where: { hash },
171 data: { lastUsedAt: new Date() },
172 });
173 return { user: oauthToken.user, source: 'oauth' };
174 }
175 }
176
177 // API key Bearer token (sourcebot-<hex>)
178 const apiKey = await getVerifiedApiObject(bearerToken);
179 if (apiKey) {
180 const user = await __unsafePrisma.user.findUnique({
181 where: { id: apiKey.createdById },
182 include: { accounts: true },
183 });
184 if (user) {
185 await __unsafePrisma.apiKey.update({
186 where: { hash: apiKey.hash },
187 data: { lastUsedAt: new Date() },
188 });
189 return { user, source: 'api_key' };
190 }
191 }

Callers 7

createAccountRequestFunction · 0.90
withAuth.test.tsFile · 0.90
tryGetPostHogDistinctIdFunction · 0.90
joinOrganizationFunction · 0.90
redeemInviteFunction · 0.90
getInviteInfoFunction · 0.90
getAuthContextFunction · 0.85

Calls 3

hasEntitlementFunction · 0.90
hashSecretFunction · 0.90
getVerifiedApiObjectFunction · 0.85

Tested by

no test coverage detected