Skip to content

Commit

Permalink
ログインボタンのコンポーネントを分ける
Browse files Browse the repository at this point in the history
GoogleLoginコンポーネントだとユーザー情報のcredentialsが返却されるが、デコードするとユーザー情報が簡単に閲覧できてしまうので、コードのみを返却する形に変更
バックエンドでこのコードを利用してユーザー情報を取得する

ref.
 - MomenSherif/react-oauth#9 (comment)
 - MomenSherif/react-oauth#91 (comment)
  • Loading branch information
dak2 committed Jul 2, 2023
1 parent dcad874 commit 622130e
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 24 deletions.
26 changes: 2 additions & 24 deletions pages/components/GoogleLoginButton.tsx
@@ -1,34 +1,12 @@
import { GoogleLogin, GoogleOAuthProvider } from "@react-oauth/google";
import LoginButton from "./LoginButton";

export default function GoogleLoginButton() {
const sendCredentials = async (credential: string) => {
const login_url = process.env.NEXT_PUBLIC_API_URL + "/login";
try {
const response = await fetch(login_url, {
method: "POST",
mode: "cors",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ credential: btoa(credential) }),
});
console.log(await response.json());
} catch (error) {
console.error(error);
}
};

return (
<GoogleOAuthProvider
clientId={process.env.NEXT_PUBLIC_GOOGLE_CLIENT_ID ?? ""}
>
<GoogleLogin
onSuccess={(credentialResponse) =>
void sendCredentials(credentialResponse.credential ?? "")
}
onError={() => console.error("Login Failed")}
/>
<LoginButton />
</GoogleOAuthProvider>
);
}
33 changes: 33 additions & 0 deletions pages/components/LoginButton.tsx
@@ -0,0 +1,33 @@
import { useGoogleLogin } from '@react-oauth/google';

export default function LoginButton() {
const login = useGoogleLogin({
flow: 'auth-code',
onSuccess: async (codeResponse) => sendToken(codeResponse.code),
onError: errorResponse => console.log(errorResponse),
});

const sendToken = async (code: string) => {
const login_url = process.env.NEXT_PUBLIC_API_URL + "/login";
try {
const response = await fetch(login_url, {
method: "POST",
mode: "cors",
credentials: "same-origin",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ code: btoa(code) }),
});
console.log(await response.json());
} catch (error) {
console.error(error);
}
};

return (
<button onClick={() => login()}>
Login with Google
</button>
);
}

0 comments on commit 622130e

Please sign in to comment.