supabase를 이용한 GitHub 소셜 로그인

로이·2024년 7월 9일

Supabase

목록 보기
1/2

Supabase를 이용한 GitHub 소셜 로그인 구현

참조
- https://www.youtube.com/watch?v=FbLzqoENTsg
- https://www.youtube.com/watch?v=yZ89etxVBKs
- https://jsbin.com/gadejefegi/edit?html,console,output
- https://docs.google.com/document/d/1pY4gUe_cIZe-HjouKHUlWoZurhYfPIVAqYW25Fe7D8E/edit
- https://supabase.com/docs/guides/getting-started
- https://supabase.com/dashboard/projects

supabase 와 github 의 연결

1. supabase.com 가입 후, 프로젝트 생성
2. Generate password 버튼으로 password 를 생성하였다면, 따로 메모
3. 사이드 메뉴 > Athentication > Configuration > Providers 에서 GitHub enabled 토글을 켜면 보이는 'Callback URL (for OAuth)' 를 복사
4. github.com 가입 후, 프로필 사진 > settings > Developer settings > OAuth Apps > New OAuth App 버튼 선택 하면 보이는 'Authorization callback URL' 입력란에 붙여넣고, Register application 버튼 선택
5. 4에서 등록된 어플리케이션 화면에서 'Client ID' 를 복사해서 3번의 Client ID 입력란에 붙여넣기
6. 4에서 등록된 어플리케이션 화면에서 'generate a new client secret' 버튼으로 생성한 'Client Secrets' 를 복사 (메모 필요) 해서 3번의 Client Secret 입력란에 붙여넣고 저장

supabase 라이브러리 설치 (React / VSCode 환경)

> npm install @supabase/supabase-js
> npm install @supabase/auth-ui-shared @supabase/auth-ui-react

웹 사이트 제작

웹 사이트 제작 후 도메인 설정 또는 로컬호스트도 웹 사이트 주소로 테스트 가능

supabase 인증 관련 설정

- supabase.com > 사이드 메뉴 > Configuration > URL Configuration > Redirect URLs > Add URL 버튼 선택하고, 인증 성공시 돌아올 웹 사이트 url 입력

supabase key 설정 (VITE 환경)

- .env.local 파일 생성 후, supabase project URL 과 anon key 설정
- .env.local / .env.development / .env.production 세 개의 파일을 만들어서 용도에 맞게 사용하게 됨
- supabase.com > 사이드 메뉴 > Project Settings > API > API Settings 에서 'project URL', 'anon key' 를 얻을 수 있음
// .env.local

VITE_SUPABASE_URL = "[ your project URL ]";
VITE_SUPABASE_ANON_KEY = "[ your anon key ]";

supabase Auth 사용하기

// App.jsx

import { createClient } from "@supabase/supabase-js";
import { Auth } from "@supabase/auth-ui-react";
import { ThemeSupa } from "@supabase/auth-ui-shared";

export const supabase = createClient(
  import.meta.env.VITE_SUPABASE_URL,
  import.meta.env.VITE_SUPABASE_ANON_KEY
);

function App() {
  const [session, setSession] = useState(null);

  useEffect(() => {
    supabase.auth.getSession().then(({ data: { session } }) => {
      setSession(session);
    });

    const {
      data: { subscription },
    } = supabase.auth.onAuthStateChange((_event, session) => {
      setSession(session);
    });

    return () => subscription.unsubscribe();
  }, []);

  return (
    <div className="App">
      <div className="Auth">
        {!session ? (
          <Auth
            supabaseClient={supabase}
            appearance={{
              theme: ThemeSupa,
            }}
            providers={["github"]}
            onlyThirdPartyProviders={true}
          />
        ) : (
          <Logout />
        )}
      </div>
    </div>
  );
}

export default App;
// logout.jsx

import { supabase } from "../App";

const Logout = () => {
  const handleLogout = async () => {
    try {
      const { error } = await supabase.auth.signOut();
    } catch (error) {
      console.error("Error during logout:", error.message);
    }
  };

  return (
    <>
      <div>
        <h1>Supabase Auth</h1>
        <button onClick={handleLogout}>Logout</button>
      </div>
    </>
  );
};

export default Logout;

supabase Auth 버튼 커스터마이징

// supabase-custom-theme.js

export const GithubCustomTheme = {
  default: {
    colors: {
      brand: "red",
      brandAccent: "darkred",
      inputBackground: "white",
      inputText: "black",
      inputPlaceholder: "darkgray",
    },
    fonts: {
      bodyFontFamily: `'Arial', sans-serif`,
      buttonFontFamily: `'Helvetica', sans-serif`,
    },
    radii: {
      borderRadiusButton: "10px",
      inputBorderRadius: "5px",
    },
  },
};
import { GithubCustomTheme } from "./util/supabase-custom-theme";

function App() {
	(...)
    return (
    <div className="App">
      <div className="Auth">
        {!session ? (
          <Auth
            supabaseClient={supabase}
            appearance={{
              theme: GithubCustomTheme,
            }}
            providers={["github"]}
            onlyThirdPartyProviders={true}
          />
        ) : (
          <Logout />
        )}
      </div>
    </div>
  );
}
export default App;

0개의 댓글