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 { try {
const { code, state } = req.query; 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"); return res.status(500).send("State isn't matching");
} }
const { token } = await authClient.requestAccessToken(code as string); 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"; import { authClient } from "../../client/twitter";
export default function handler(req: NextApiRequest, res: NextApiResponse) { 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"); return res.status(500).send("No state or code_challenge");
} }
const authUrl = authClient.generateAuthURL({ const authUrl = authClient.generateAuthURL({
state: process.env.STATE, state: process.env.TWITTER_AUTH_STATE,
code_challenge: process.env.CODE_CHALLENGE, code_challenge: process.env.TWITTER_AUTH_CODE_CHALLENGE,
code_challenge_method: "plain", code_challenge_method: "plain",
}); });
res.redirect(authUrl); res.status(200).json({ authUrl });
} }

View File

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

View File

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