sveltekit firebase 로그인/로그아웃 만들기

Computer 관심/Svelte|2022. 5. 8. 22:37
반응형

firebase 9 버전이다.

 

app.js를 만들기.

import { initializeApp } from "firebase/app";
import { getAuth, GoogleAuthProvider } from "firebase/auth";

const firebaseConfig = {
  apiKey: "xxxxxxxxx-gG2DEYRrdnOx-Jtw7PRoso",
  authDomain: "xxxx.firebaseapp.com",
  projectId: "xxxxx",
  storageBucket: "xxxx.appspot.com",
  messagingSenderId: "xxxx",
  appId: "xxxxxxx",
  measurementId: "xxxxx"
};

//named export를 사용해서 필요한 것들을 내보냄
// Initialize Firebase

export const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);
export const provider = new GoogleAuthProvider();

 

stores.js 만들기

import { writable } from "svelte/store";

export const user = writable({})
export const isLoggedIn = writable(false)

 

 

 

index.svelte

<script>
  import {auth, provider} from '../lib/app.js'
  import {signInWithPopup, onAuthStateChanged, signOut} from "firebase/auth";
  import {user, isLoggedIn} from '../stores'
  
  let isLoading = true

  async function loginInGoogle(){
    await signInWithPopup(auth, provider).then((result)=>{
      console.log(result.user)
      $user = result.user
      $isLoggedIn = true
    }).catch((error) => {

    })

  }
  async function logOut(){
    signOut(auth)
  }
 

  onAuthStateChanged(auth,(currUser) => {
    isLoading = false
    if (currUser) {
      // User is signed in, see docs for a list of available properties
      // https://firebase.google.com/docs/reference/js/firebase.User
      $user = currUser
      $isLoggedIn = true

      
    } else {
      $isLoggedIn = false
      $user = currUser
      // ...
    }
  });

</script>


{#if !isLoading}
  {#if $isLoggedIn}
    {$user.displayName} <button on:click={logOut}>log out</button>
  {:else}
    <button on:click={loginInGoogle}>login</button>
  {/if}
{/if}

 

 

 

 

댓글()