-
Notifications
You must be signed in to change notification settings - Fork 12.1k
Expand file tree
/
Copy pathroute.ts
More file actions
62 lines (55 loc) · 2.04 KB
/
route.ts
File metadata and controls
62 lines (55 loc) · 2.04 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
import process from "node:process";
import { getOAuthService } from "@calcom/features/oauth/di/OAuthService.container";
import { OAUTH_ERROR_REASONS } from "@calcom/features/oauth/services/OAuthService";
import { ErrorWithCode } from "@calcom/lib/errors";
import { getHttpStatusCode } from "@calcom/lib/server/getServerErrorFromUnknown";
import { defaultResponderForAppDir } from "app/api/defaultResponderForAppDir";
import { parseUrlFormData } from "app/api/parseRequestData";
import type { NextRequest } from "next/server";
import { NextResponse } from "next/server";
async function handler(req: NextRequest) {
const { code, client_id, client_secret, grant_type, redirect_uri, code_verifier } =
await parseUrlFormData(req);
if (!process.env.CALENDSO_ENCRYPTION_KEY) {
return NextResponse.json({ message: OAUTH_ERROR_REASONS["encryption_key_missing"] }, { status: 500 });
}
if (!client_id || !code || !redirect_uri) {
return NextResponse.json({ error: "invalid_request" }, { status: 400 });
}
if (grant_type !== "authorization_code") {
return NextResponse.json({ error: "invalid_request" }, { status: 400 });
}
try {
const oAuthService = getOAuthService();
const tokens = await oAuthService.exchangeCodeForTokens(
client_id,
code,
client_secret,
redirect_uri,
code_verifier
);
return NextResponse.json(
{
access_token: tokens.accessToken,
token_type: "bearer",
refresh_token: tokens.refreshToken,
expires_in: tokens.expiresIn,
scope: tokens.scope,
},
{
status: 200,
headers: {
"Content-Type": "application/json;charset=UTF-8",
"Cache-Control": "no-store",
Pragma: "no-cache",
},
}
);
} catch (err) {
if (err instanceof ErrorWithCode) {
return NextResponse.json({ error: err.message }, { status: getHttpStatusCode(err) });
}
}
return NextResponse.json({ error: "error_code_exchange" }, { status: 500 });
}
export const POST = defaultResponderForAppDir(handler);