2022-11-30 09:58:19 +00:00
|
|
|
import type { NextApiRequest, NextApiResponse } from "next";
|
2022-12-05 10:50:13 +00:00
|
|
|
import { withIronSessionApiRoute } from "iron-session/next";
|
2022-12-05 11:01:24 +00:00
|
|
|
import { request } from "../../utils/url";
|
|
|
|
import { ironOptions } from "../../iron.config";
|
|
|
|
import { twitterApiBaseUrl } from "../../constants/twitter";
|
2022-11-30 09:58:19 +00:00
|
|
|
|
2022-12-05 10:50:13 +00:00
|
|
|
interface TwitterOAuth2TokenData {
|
|
|
|
token_type: string;
|
|
|
|
expires_in: number;
|
|
|
|
access_token: string;
|
|
|
|
scope: string;
|
|
|
|
refresh_token: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default withIronSessionApiRoute(async function handler(
|
2022-11-30 09:58:19 +00:00
|
|
|
req: NextApiRequest,
|
2022-11-30 14:55:17 +00:00
|
|
|
res: NextApiResponse,
|
2022-11-30 09:58:19 +00:00
|
|
|
) {
|
2022-12-05 11:01:24 +00:00
|
|
|
if (
|
|
|
|
!process.env.TWITTER_CLIENT_ID ||
|
|
|
|
!process.env.TWITTER_CLIENT_SECRET ||
|
|
|
|
!process.env.TWITTER_AUTH_CALLBACK_URI
|
|
|
|
) {
|
|
|
|
return res
|
|
|
|
.status(500)
|
|
|
|
.send(
|
|
|
|
"Twitter app client id or client secret or callback URI is not set",
|
|
|
|
);
|
|
|
|
}
|
2022-12-05 10:50:13 +00:00
|
|
|
|
2022-12-05 11:01:24 +00:00
|
|
|
if (!req.session.code_verifier) {
|
|
|
|
return res.status(401).send("No OAuth2.0 code verifier");
|
|
|
|
}
|
2022-12-05 10:50:13 +00:00
|
|
|
|
2022-12-05 11:01:24 +00:00
|
|
|
try {
|
2022-11-30 09:58:19 +00:00
|
|
|
const { code, state } = req.query;
|
2022-11-30 13:49:09 +00:00
|
|
|
if (state !== process.env.TWITTER_AUTH_STATE) {
|
2022-12-05 10:50:13 +00:00
|
|
|
return res.status(401).send("State isn't matching");
|
2022-11-30 09:58:19 +00:00
|
|
|
}
|
2022-12-05 10:50:13 +00:00
|
|
|
|
|
|
|
const params = new URLSearchParams();
|
|
|
|
params.append("grant_type", "authorization_code");
|
|
|
|
params.append("code", code as string);
|
|
|
|
params.append("redirect_uri", process.env.TWITTER_AUTH_CALLBACK_URI);
|
|
|
|
params.append("code_verifier", req.session.code_verifier);
|
|
|
|
const tokenData = await request<TwitterOAuth2TokenData>(
|
|
|
|
`${twitterApiBaseUrl}/oauth2/token`,
|
|
|
|
{
|
|
|
|
method: "post",
|
|
|
|
headers: {
|
|
|
|
"Content-Type": "application/x-www-form-urlencoded",
|
|
|
|
Authorization: `Basic ${Buffer.from(
|
|
|
|
`${process.env.TWITTER_CLIENT_ID}:${process.env.TWITTER_CLIENT_SECRET}`,
|
|
|
|
).toString("base64")}`,
|
|
|
|
},
|
|
|
|
body: params,
|
|
|
|
},
|
|
|
|
);
|
|
|
|
res.status(200).json({
|
|
|
|
accessToken: tokenData.access_token,
|
|
|
|
});
|
2022-11-30 09:58:19 +00:00
|
|
|
} catch (error) {
|
|
|
|
console.log(error);
|
2022-12-05 11:01:24 +00:00
|
|
|
res.status(500).send("Internal server error ");
|
2022-11-30 09:58:19 +00:00
|
|
|
}
|
2022-12-05 10:50:13 +00:00
|
|
|
},
|
|
|
|
ironOptions);
|