forked from lobehub/lobe-chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext.ts
70 lines (58 loc) · 2.07 KB
/
context.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { User } from 'next-auth';
import { NextRequest } from 'next/server';
import { JWTPayload, LOBE_CHAT_AUTH_HEADER, enableClerk, enableNextAuth } from '@/const/auth';
import { ClerkAuth, IClerkAuth } from '@/libs/clerk-auth';
export interface AuthContext {
authorizationHeader?: string | null;
clerkAuth?: IClerkAuth;
jwtPayload?: JWTPayload | null;
nextAuth?: User;
userId?: string | null;
}
/**
* Inner function for `createContext` where we create the context.
* This is useful for testing when we don't want to mock Next.js' request/response
*/
export const createContextInner = async (params?: {
authorizationHeader?: string | null;
clerkAuth?: IClerkAuth;
nextAuth?: User;
userId?: string | null;
}): Promise<AuthContext> => ({
authorizationHeader: params?.authorizationHeader,
clerkAuth: params?.clerkAuth,
nextAuth: params?.nextAuth,
userId: params?.userId,
});
export type Context = Awaited<ReturnType<typeof createContextInner>>;
/**
* Creates context for an incoming request
* @link https://trpc.io/docs/v11/context
*/
export const createContext = async (request: NextRequest): Promise<Context> => {
// for API-response caching see https://trpc.io/docs/v11/caching
const authorization = request.headers.get(LOBE_CHAT_AUTH_HEADER);
let userId;
let auth;
if (enableClerk) {
const clerkAuth = new ClerkAuth();
const result = clerkAuth.getAuthFromRequest(request);
auth = result.clerkAuth;
userId = result.userId;
return createContextInner({ authorizationHeader: authorization, clerkAuth: auth, userId });
}
if (enableNextAuth) {
try {
const { default: NextAuthEdge } = await import('@/libs/next-auth/edge');
const session = await NextAuthEdge.auth();
if (session && session?.user?.id) {
auth = session.user;
userId = session.user.id;
}
return createContextInner({ authorizationHeader: authorization, nextAuth: auth, userId });
} catch (e) {
console.error('next auth err', e);
}
}
return createContextInner({ authorizationHeader: authorization, userId });
};