-
Notifications
You must be signed in to change notification settings - Fork 0
/
load-context.ts
108 lines (99 loc) · 2.6 KB
/
load-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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import { PrismaD1 } from "@prisma/adapter-d1";
import { PrismaClient } from "@prisma/client";
import {
createCookie,
createWorkersKVSessionStorage,
type SessionStorage,
} from "@remix-run/cloudflare";
import { Authenticator } from "remix-auth";
import { DiscordStrategy } from "remix-auth-discord";
import type { PlatformProxy } from "wrangler";
export type Cloudflare = Omit<PlatformProxy<Env>, "dispose">;
declare module "@remix-run/cloudflare" {
interface AppLoadContext {
cloudflare: Cloudflare;
prisma: PrismaClient;
sessionStorage: SessionStorage;
authenticator: Authenticator<SessionData>;
}
}
interface SessionData {
userId: string;
}
const createAuthenticator = (cloudflare: Cloudflare, prisma: PrismaClient) => {
const sessionStorage = createWorkersKVSessionStorage<SessionData>({
cookie: createCookie("session", {
sameSite: "lax",
secrets: [cloudflare.env.SESSION_COOKIE_SECRET],
secure: cloudflare.env.CF_ENV !== "local",
httpOnly: true,
maxAge: 60 * 60 * 24 * 7,
}),
kv: cloudflare.env.KV_SESSION_STORAGE,
});
const authenticator = new Authenticator<SessionData>(sessionStorage);
authenticator.use(
new DiscordStrategy(
{
clientID: cloudflare.env.DISCORD_CLIENT_ID,
clientSecret: cloudflare.env.DISCORD_CLIENT_SECRET,
callbackURL: "/sign-in/callback/discord",
scope: ["identify"],
prompt: "none",
},
async (params) => {
const user = await prisma.users.findUnique({
select: { id: true },
where: { discordId: params.profile.id },
});
if (!user) {
throw new Error("user not found");
}
return { userId: user.id };
},
),
"discord",
);
authenticator.use(
new DiscordStrategy(
{
clientID: cloudflare.env.DISCORD_CLIENT_ID,
clientSecret: cloudflare.env.DISCORD_CLIENT_SECRET,
callbackURL: "/register/callback/discord",
scope: ["identify"],
prompt: "consent",
},
async (params) => {
const user = await prisma.users.upsert({
create: {
discordId: params.profile.id,
displayName: params.profile.displayName,
},
update: {},
where: { discordId: params.profile.id },
select: { id: true },
});
return { userId: user.id };
},
),
"discord-registration",
);
return { sessionStorage, authenticator };
};
export const getLoadContext = ({
context: { cloudflare },
}: {
context: { cloudflare: Cloudflare };
}) => {
const prisma = new PrismaClient({ adapter: new PrismaD1(cloudflare.env.DB) });
const { authenticator, sessionStorage } = createAuthenticator(
cloudflare,
prisma,
);
return {
cloudflare,
prisma,
sessionStorage,
authenticator,
};
};