From 5572ab5ceea942aa7a6c967dfffe567ae0169010 Mon Sep 17 00:00:00 2001 From: delivan Date: Wed, 30 Nov 2022 22:49:09 +0900 Subject: [PATCH] Refactor auth api routes --- pages/api/auth/{callback.ts => access-token.ts} | 2 +- pages/api/auth/index.ts | 11 +++++++---- pages/client/twitter.ts | 6 +++--- pages/index.tsx | 8 +++++++- 4 files changed, 18 insertions(+), 9 deletions(-) rename pages/api/auth/{callback.ts => access-token.ts} (90%) diff --git a/pages/api/auth/callback.ts b/pages/api/auth/access-token.ts similarity index 90% rename from pages/api/auth/callback.ts rename to pages/api/auth/access-token.ts index 1b101eb..f358d45 100644 --- a/pages/api/auth/callback.ts +++ b/pages/api/auth/access-token.ts @@ -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); diff --git a/pages/api/auth/index.ts b/pages/api/auth/index.ts index 7d9a060..ae5f705 100644 --- a/pages/api/auth/index.ts +++ b/pages/api/auth/index.ts @@ -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 }); } diff --git a/pages/client/twitter.ts b/pages/client/twitter.ts index 9d22f41..f37fbec 100644 --- a/pages/client/twitter.ts +++ b/pages/client/twitter.ts @@ -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"], }); diff --git a/pages/index.tsx b/pages/index.tsx index 6627103..b16b43f 100644 --- a/pages/index.tsx +++ b/pages/index.tsx @@ -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 (
- login +
); }