-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.ts
90 lines (69 loc) · 2.77 KB
/
route.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
import { CONFIG } from "@/config";
import { OAuth2CrendialsResponse, OAuthTokenExchangeRequestParams } from '@/types/auth';
import { encryptTokens } from '@/utils/encrypt';
import {
createUser,
getUserDetails
} from "@/utils/parseUser";
import axios, { AxiosRequestConfig } from 'axios';
import { serialize } from "cookie";
import { sign } from "jsonwebtoken";
import { cookies } from "next/headers";
import { NextResponse } from 'next/server';
const axiosConfig: AxiosRequestConfig = {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
}
}
const buildOAuth2RequestPayload = (data: OAuthTokenExchangeRequestParams) => new URLSearchParams(data).toString();
const scope = ["identify"].join(" ");
const OAUTH_QS = new URLSearchParams({
client_id: CONFIG.VALUES.CLIENT_ID,
redirect_uri: CONFIG.URLS.REDIRECT_URI,
response_type: "code",
scope
}).toString();
const OAUTH_URL = `https://discord.com/api/oauth2/authorize?${OAUTH_QS}`;
export async function GET(req: Request) {
const urlParams = new URL(req.url).searchParams;
const code = urlParams.get("code");
const error = urlParams.get("error");
if (error) {
console.log(`Error authorizing user: ${error}`);
return NextResponse.json(JSON.stringify(error), { status: 500 });
}
if (!code) {
return NextResponse.redirect(OAUTH_URL);
}
const body = buildOAuth2RequestPayload({
client_id: CONFIG.VALUES.CLIENT_ID,
client_secret: CONFIG.VALUES.CLIENT_SECRET,
grant_type: "authorization_code",
code,
redirect_uri: CONFIG.URLS.REDIRECT_URI,
scope
}).toString();
try {
const { data } = await axios.post<OAuth2CrendialsResponse>(CONFIG.URLS.OAUTH2_TOKEN, body, axiosConfig);
const { access_token, refresh_token } = data;
const user = await getUserDetails(access_token);
const encryptedTokens = encryptTokens(access_token, refresh_token);
await createUser({
userId: user.data.id,
accessToken: encryptedTokens.accessToken,
refreshToken: encryptedTokens.refreshToken
});
if (!("id" in user.data)) return NextResponse.json(JSON.stringify("User not found"), { status: 404 });
const token = sign(user.data, process.env.JWT_SECRET!, { expiresIn: "72h" });
cookies().set(CONFIG.VALUES.COOKIE_NAME, serialize(CONFIG.VALUES.COOKIE_NAME, token, {
httpOnly: true,
secure: process.env.NODE_ENV === "production",
sameSite: "lax",
path: "/"
}));
return NextResponse.redirect(CONFIG.URLS.BASE_URL);
} catch (e) {
console.log(`Error exchanging code for token: ${e}`);
return NextResponse.json(JSON.stringify(e), { status: 500 });
}
}