[supabase] supabase로 간단한 auth 기능 구현해보기

박소정·2023년 3월 26일
5
post-thumbnail

supabase

새로운 프로젝트를 시작할 때마다 나의 가장 큰 고민을 해결해준 친구는 firebase였다. docs가 친절하진 않지만 간단한 함수로 auth, db를 사용할 수 있었기 때문이다. 그런데 최근 supabase를 발견했다.

supabase의 메인 화면에는 firebase를 대체할 오픈소스라는 것을 당당히 내걸고 있다.

직접 사용해본 supabase는 firebase와 비교했을때 훨씬 사용하기 쉬웠고, 문서 정리도 잘 되어있어 따라서 구현해보기 좋았다 👍

어떤 프로젝트를 시작할지 아직 구체적인 계획은 없지만 어떤걸 만들든 auth쪽은 필요하겠지 싶어 이 부분을 먼저 구현해보았다.

회원가입

  const signupHandler = async (e: FormEvent) => {
    e.preventDefault();
    try {
      const { data, error } = await supabase.auth.signUp({
        email,
        password,
      });
      if (error) console.error(error);
      console.log(data);
    } catch (error) {
      console.error(error);
    }
  };

docs: https://supabase.com/docs/reference/javascript/auth-signup

회원가입을 하면 가입한 메일로 인증 메일을 받게되고, 그 메일에 있는 링크로 접속을 하면 인증이 완료된다

해당 프로젝트 > Authentication > Email Templates에 들어가면 이메일 양식도 수정할 수 있음!

로그인

로그인을 하는 방법은 크게 3가지였다.

  • email + password (email 대신 핸드폰 번호도 가능)
  • 이메일이나 문자로 otp를 발급받아 로그인하는 방법
  • OAuth를 통해 로그인하는 방법!
    개인적으로는 OAuth를 통해 로그인하는 방법이 신기해서 어느정도 구현이 되면 추가시켜볼 예정이다.

가장 기본적인 형태의 로그인을 구현해보고 싶었기에 email과 password를 통해 로그인 하는 방법을 선택했다. 사실 인자를 전달하는 함수만 다를뿐, 로직은 회원가입과 동일하게 작성했다.

const loginHandler = async (e: FormEvent) => {
    e.preventDefault();
    try {
      const { data, error } = await supabase.auth.signInWithPassword({
        email,
        password,
      });
      if (error) console.error(error);
      if (data) {
        dispatch({
          type: "LOGIN",
          payload: { email: data.user?.email, id: data.user?.id },
        });
        router.push("/");
      }
    } catch (error) {
      console.error(error);
    }
  };

입력된 이메일과 비밀번호를 객체로 담아 signInWithPassword함수에 전달해주면 쉽게 로그인 기능을 구현할 수 있다✨

docs: https://supabase.com/docs/reference/javascript/auth-signinwithpassword

로그아웃

로그아웃은 간단했다


const { error } = await supabase.auth.signOut()

이 함수만 사용하면 브라우저 세션에 저장된 로그인한 유저의 정보를 지우게 된다.

docs: https://supabase.com/docs/reference/javascript/auth-signout

비밀번호 찾기

비밀번호 찾기 페이지에 접속하면 비밀번호를 찾고싶은 이메일을 입력하는 form을 짜두면, 입력받은 이메일로 비밀번호를 재설정할 수 있는 링크를 보내준다.

  const resetPasswordHandler = async () => {
    try {
      const { data, error } = await supabase.auth.resetPasswordForEmail(email, {
        redirectTo: "http://localhost:3001/resetPassword",
      });
      console.log(data);
      if (!error) {
        alert("Please check your email");
        setEmail("");
      }
    } catch (error) {
      console.error(error);
    }
  };

redirectTo에 비밀번호를 재설정 할 수 있는 링크를 넣어둠!

메일로 받은 비밀번호 재설정 페이지 (redirectTo 링크)로 들어오면

  useEffect(() => {
    supabase.auth.onAuthStateChange(async (event, session) => {
      if (event === "PASSWORD_RECOVERY") {
        setShowResetForm(true);
      }
    });
  }, []);

해당 이벤트가 PASSWORD_RECOVERY 인지를 확인하고, 새로운 비밀번호를 설정할 수 있는 폼을 보여준다.

비밀번호를 업데이트하는 함수는 이전의 로그인이나 회원가입 함수와 비슷하다

const updatePasswordHandler = async () => {
    const { data, error } = await supabase.auth.updateUser({
      password: newPassword,
    });
    if (data) {
      alert("Password updated successfully!");
      setNewPassword("");
      router.push("/");
    }
    if (error) alert("There was an error updating your password.");
  };

docs: https://supabase.com/docs/reference/javascript/auth-resetpasswordforemail


파이어베이스로 프로젝트를 만들어 본 적이 있지만 파이어베이스보다 익히고 구현하는데 훨씬 덜 헤맸고, 공식문서가 잘 정리가 되어있는데다가 함수들이 간단해서 토이프로젝트를 만든다거나 빠르게 만들어야할 필요가 있을때 사용하면 좋을듯 하다!

https://supabase.com/docs/reference/javascript/start

0개의 댓글