스벨트로그인에 해당하는 글 2

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}

 

 

 

 

반응형

댓글()

스벨트 파이어베이스 로그인 하기

Computer 관심/Svelte|2021. 11. 11. 16:58
반응형

파이어베이스 로그인 구현이 새롭게 바뀌면서 기존에 있던 튜토리얼과 예제들이 작동되지 않아서 약간 애를 먹었다.

그러므로 파이어베이스 로그인을 구현할때 예전의 예제를 보기보단 파이어베이스 사이트에서 새로운 버전으로 보는것이 좋다.

 

스벨트에서 구현은 다음과 같이 했다. 맞는지 아닌지는 모르겠지만... 물론 추가로 수정해야 할 부분들이 있다.

 

 

 

로그인 하기전

 

로그인 버튼 클릭했을때 팝업

 

 

파이어베이스로 방금 가입된 유저

 

 

로그인 되면 보인는 화면

 

1. 파이어베이스 사이트에 들어간 뒤 새로운 프로젝트를 만든다.

 

2. config 정보를 복사

 

3. __layout.svelte 파일에서 파이어베이스 init를 한다.

import { initializeApp } from 'firebase/app';
import { getAuth, onAuthStateChanged } from "firebase/auth";
import {isLogin} from '../store'


onMount(()=>{
    const firebaseConfig = {
        #config들어갈 정보 복사
        };
        // Initialize Firebase
        initializeApp(firebaseConfig);
        
        
        // 로그인 정보가 체인지가 될때 실행되는 리스너 함수
        const auth = getAuth();
        onAuthStateChanged(auth, (user) => {
        if (user) {
            // User is signed in, see docs for a list of available properties
            // https://firebase.google.com/docs/reference/js/firebase.User
            const uid = user.uid;
            console.log(user)
            $isLogin = true
        } else {
            // User is signed out
            // ...
        }
   });
})

 

4. 스토어에 등록한 isLogin 변수를 사용하여 로그인상태를 변경함

//store.js

import { writable } from 'svelte/store';
export const isLogin = writable(false);

 

5. 로그인로그아웃 필요한 페이지에서 구글로그인 로그아웃 함수 사용

import { getAuth, signInWithPopup, GoogleAuthProvider, signOut } from "firebase/auth";
import {isLogin} from '../store';

  async function loginWithGoogle() {
    const auth = getAuth();
    const provider = new GoogleAuthProvider();
    signInWithPopup(auth, provider)
    .then((result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
       console.log(user)
    }).catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
    });
  }
  
 async function signOutGoogle(){
    const auth = getAuth();
    console.log(auth)
    signOut(auth).then(() => {
        $isLogin = false
        }).catch((error) => {
        // An error happened.
        });
   }
반응형

댓글()