Refactor auth api routes

This commit is contained in:
delivan 2022-11-30 22:49:09 +09:00
parent 20d66d5731
commit 5572ab5cee
4 changed files with 18 additions and 9 deletions

View File

@ -7,7 +7,7 @@ export default async function handler(
) {
try {
const { code, state } = req.query;
if (state !== process.env.STATE) {
if (state !== process.env.TWITTER_AUTH_STATE) {
return res.status(500).send("State isn't matching");
}
const { token } = await authClient.requestAccessToken(code as string);

View File

@ -2,14 +2,17 @@ import type { NextApiRequest, NextApiResponse } from "next";
import { authClient } from "../../client/twitter";
export default function handler(req: NextApiRequest, res: NextApiResponse) {
if (!process.env.STATE || !process.env.CODE_CHALLENGE) {
if (
!process.env.TWITTER_AUTH_STATE ||
!process.env.TWITTER_AUTH_CODE_CHALLENGE
) {
return res.status(500).send("No state or code_challenge");
}
const authUrl = authClient.generateAuthURL({
state: process.env.STATE,
code_challenge: process.env.CODE_CHALLENGE,
state: process.env.TWITTER_AUTH_STATE,
code_challenge: process.env.TWITTER_AUTH_CODE_CHALLENGE,
code_challenge_method: "plain",
});
res.redirect(authUrl);
res.status(200).json({ authUrl });
}

View File

@ -1,8 +1,8 @@
import { auth } from "twitter-api-sdk";
export const authClient = new auth.OAuth2User({
client_id: process.env.CLIENT_ID as string,
client_secret: process.env.CLIENT_SECRET as string,
callback: "http://localhost:3000/api/auth/callback",
client_id: process.env.TWITTER_CLIENT_ID ?? "",
client_secret: process.env.TWITTER_CLIENT_SECRET,
callback: process.env.TWITTER_AUTH_CALLBACK_URI ?? "",
scopes: ["users.read", "offline.access"],
});

View File

@ -1,9 +1,15 @@
import styles from "../styles/Home.module.css";
export default function Home() {
const handleSigninWithTwitter = async () => {
const { authUrl } = await (await fetch("/api/auth")).json();
window.open(authUrl);
};
return (
<div className={styles.container}>
<a href="/api/auth">login</a>
<button onClick={handleSigninWithTwitter}>Sign in with Twitter</button>
</div>
);
}