Skip to content
Snippets Groups Projects
GoogleLoginButton.js 2.01 KiB
Newer Older
  • Learn to ignore specific revisions
  • Gwangbin's avatar
    Gwangbin committed
    import { GoogleLogin } from "@react-oauth/google";
    import { GoogleOAuthProvider } from "@react-oauth/google";
    
    import { useNavigate, Navigate } from "react-router-dom";
    
    
    import base64 from 'base-64';
    
    import axios from 'axios';
    
    const GoogleLoginButton = () => {
    
    Gwangbin's avatar
    Gwangbin committed
      const clientId = '716858812522-rb0pfisq317unkh4so5hvbu16p19kqp8.apps.googleusercontent.com'
      const navigate = useNavigate();
      const goMain = () => {
        navigate("/main");
      }
      return (
        <>
          <GoogleOAuthProvider clientId={clientId}>
            <GoogleLogin
              onSuccess={(res) => {
                /* 발급받은 토큰은 . 을 기준으로 3 개로 나뉜다.
                aaaa.bbbb.cccc
              	
                [base64]aaaa: 헤더
                [base64]bbbb: 페이로드 (실질적인 데이터)
                [RS256]cccc: 서명
              	
                RS256 : 암호화 알고리즘, JWT 서명할 때 사용한다고 함
                */
    
                console.log(res);
    
                let datas = res.credential.split('.')
                const obj = JSON.parse(b64DecodeUnicode(datas[1]));
                console.log(obj);
                let response = commuTest(obj);
                console.log(response);
                if (response) {
                  goMain();
                }
              }}
              onFailure={(err) => {
                console.log("Login Failed");
                console.log(err);
              }}
            />
          </GoogleOAuthProvider>
        </>
      );
    
    function b64DecodeUnicode(str) {
    
    Gwangbin's avatar
    Gwangbin committed
      // Going backwards: from bytestream, to percent-encoding, to original string.
      return decodeURIComponent(atob(str)
        .split('').map(function (c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    
        }).join(''));
    }
    
    
    async function commuTest(payloadObj) {
    
    Gwangbin's avatar
    Gwangbin committed
      const response = await axios({
        url: 'http://localhost:8080/login', // 통신할 웹문서
        method: 'post', // 통신할 방식
        data: payloadObj
      });
    
      console.log(response)
    
      if (response.status === 200) {
        return response.data;
      }
      else {
        return null;
      }
    
    
    
    export default GoogleLoginButton