LoginSignup
14
16

More than 5 years have passed since last update.

Firebaseの処理をasync/awaitを使って書いてみた

Last updated at Posted at 2019-04-22

これは何?

Firebaseの認可の仕組みをasync/awaitを使って書き換えたときのメモ。ログイン・ログアウト、読込み、書込みのサンプル。

さっそく

認証&認可を有効化

[Develop]>[Authentication]>[Sign-in method] で表示されるリストの中からGoogleを有効化。
Screen Shot 2019-04-22 at 11.24.09 PM.png

firebaseのDatabaseへの読み書きの権限設定

[Develop]>[Database]>[Rules]
{
  "rules": {
    "users": {
      "$uid": {
        ".write": "$uid === auth.uid",
        ".read": "$uid === auth.uid"
      }
    }
  }
}

Screen Shot 2019-04-22 at 11.24.58 PM.png

Databaeの設定

必要なし。

  • 書き込み:Hierarchyを辿りセットされた値で末端を更新。セットされていないと項目から削除される?(現象からの推測)

コードを書く

[アプリのシナリオ] 認証し、認可された上でID、メアド、表示名をDatabaseに書き込みを行い、読み込んで画面に表示する。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Using FirebaseUI Auth, on the Web</title>
    <style>
     .hide {
       display: none;
       visibility: hidden;
       height: 0;
     }
     .flex-center {
       display: flex;
       justify-content: center;
       flex-direction: column;
       align-items: center
     }
    </style>
  </head>
  <body>
    <div id="signin00" class="flex-center hide">
      <h1 align="center">Firebase Auth Quickstart Demo</h1>
      <div id="firebaseui-auth-container"></div>
    </div>

    <div id="signin01" class="flex-center hide">
      <h1 align="center">Singed-In: Firebase Auth Quickstart Demo</h1>
      <h2 id="status"></h2>
      <div id="uid"></div>
      <div id="email"></div>
      <div id="displayName"></div>
    </div>

    <script src="https://www.gstatic.com/firebasejs/5.10.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.10.0/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/5.10.0/firebase-database.js"></script>

    <script src="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.js"></script>
    <link type="text/css" rel="stylesheet" href="https://cdn.firebase.com/libs/firebaseui/3.5.2/firebaseui.css" />

    <script type="text/javascript">
     (async () => {
       let firebaseConfig = {
         apiKey: "xcvbnmhgfdsa1ddbbrr",
         authDomain: "xxxx.firebaseapp.com",
         databaseURL: "https://xxxx.firebaseio.com",
         projectId: "xxxx",
         storageBucket: "xxxx.appspot.com",
         messagingSenderId: "111111000000"
       };
       firebase.initializeApp(firebaseConfig);

       const toggleDisp = dispId => {
         const ids = ["signin00", "signin01"];
         ids.forEach( val => {
           document.getElementById(val).classList.add("hide");
           if(val == dispId) {
             document.getElementById(val).classList.remove("hide");
           }
         });
       }

       const f_auth = firebase.auth();
       const doAuth = async _ => {
         return new Promise( (resolve, reject) => {
           const f_auth = firebase.auth();
           f_auth.onAuthStateChanged( user => {
             resolve(user);
           });
         });
       }

       const readOnce = async userId => {
         return new Promise( async (resolve, reject) => {
           const ref = await firebase.database().ref('/users/' + userId);
           let snapshot = await ref.once('value')
           resolve(snapshot.val());
         });
       }

       const writeUserData = async (userId, displayName, email) => {
         const ref = firebase.database().ref('users/' + userId);
         await ref.set({
           displayName: displayName,
           email: email
         });
         return true;
       }

       // ここからがメインロジック
       let user = await doAuth();
       if(user) {
         toggleDisp("signin01")
         document.querySelector("#status").innerText = 'Singed-in';
         document.querySelector("#uid").innerHTML = "[uid] " + user.uid;

         console.log("--- [ writeUserData ] ---");
         let w_result = await writeUserData(user.uid, "TEST_" + user.displayName, "TEST_" + user.email);
         console.log("[Write Result] " + w_result);

         console.log("--- [ readOnce ] ---");
         let w_value = await readOnce(user.uid);
         console.log("[Wrote Value]", w_value);
         document.querySelector("#email").innerHTML = "[email] " + w_value.email;
         document.querySelector("#displayName").innerHTML = "[displayName] " + w_value.displayName;
       } else {
         toggleDisp("signin00")
         let uiConfig = {
           signInSuccessUrl: window.location,
           signInFlow: 'popup',
           signInOptions: [
             firebase.auth.GoogleAuthProvider.PROVIDER_ID,
           ]
         };

         var ui = new firebaseui.auth.AuthUI(firebase.auth());
         ui.start('#firebaseui-auth-container', uiConfig);
       }
     })();
    </script>
  </body>
</html>

その他

前にも同じようなこと書いてたみたい、、、、。
- Firebaseの基本:Authentication

14
16
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
16