-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Expand file tree
/
Copy pathintegrations.$serviceName.callback.ts
More file actions
78 lines (62 loc) · 2.27 KB
/
Copy pathintegrations.$serviceName.callback.ts
File metadata and controls
78 lines (62 loc) · 2.27 KB
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
import type { LoaderFunctionArgs } from "@remix-run/server-runtime";
import z from "zod";
import { OrgIntegrationRepository } from "~/models/orgIntegration.server";
import { requireUserId } from "~/services/session.server";
import { requestUrl } from "~/utils/requestUrl.server";
import { CreateOrgIntegrationService } from "~/v3/services/createOrgIntegration.server";
const URLSearchSchema = z
.object({
code: z.string().optional(),
state: z.string().optional(),
error: z.string().optional(),
})
.passthrough();
const ParamsSchema = z.object({
serviceName: z.string(),
});
export async function loader({ request, params }: LoaderFunctionArgs) {
if (request.method.toUpperCase() !== "GET") {
return { status: 405, body: "Method Not Allowed" };
}
const userId = await requireUserId(request);
const url = requestUrl(request);
const parsedSearchParams = URLSearchSchema.safeParse(Object.fromEntries(url.searchParams));
if (!parsedSearchParams.success) {
// TODO: this needs to lookup the redirect url in the cookies
throw new Response("Invalid params", { status: 400 });
}
if (parsedSearchParams.data.error) {
// TODO: this needs to lookup the redirect url in the cookies
throw new Response(parsedSearchParams.data.error, { status: 400 });
}
if (!parsedSearchParams.data.code || !parsedSearchParams.data.state) {
throw new Response("Invalid params", { status: 400 });
}
const parsedParams = ParamsSchema.safeParse(params);
if (!parsedParams.success || parsedParams.data.serviceName !== "slack") {
throw new Response("Invalid params", { status: 400 });
}
const oauthState = await OrgIntegrationRepository.consumeSlackOAuthState(
request,
parsedSearchParams.data.state,
userId
);
if (!oauthState) {
throw new Response("Invalid state", { status: 400 });
}
const service = new CreateOrgIntegrationService();
const integration = await service.call(
userId,
oauthState.organizationId,
oauthState.service,
parsedSearchParams.data.code
);
if (integration) {
return await OrgIntegrationRepository.redirectAfterAuth(request, oauthState.redirectTo);
}
return await OrgIntegrationRepository.redirectAfterAuth(
request,
oauthState.redirectTo,
"Failed to connect to the service"
);
}