前回は概要とRealtime Databaseにデータを入れてみるところまでやったので今回は認証をしてみる。
サインアップとサインインとサインアウトを作ろう
これはfirebaseのここに書いてあるのでそのまま使ってみる。
サインアップしている状態としていない状態で書き込める箇所にルールを設定してみる
- usersの配下に書き込む時はログインしていないと書き込めない。
- roomsの配下に書き込む時はログインしていると書き込めない。
という謎のルールを設定してみた。
1 2 3 4 5 6 7 8 9 10 11 12 |
{ "rules": { "users": { ".read": "auth != null", ".write": "auth != null" }, "rooms": { ".read": "auth == null", ".write": "auth == null" } } } |
こんなルールはイレギュラーだがまぁ気にしないで。
ソースコード
今回もメモ帳に以下コードを貼り付けてindex.htmlで保存して実行できるようにしておいた。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
<!DOCTYPE html> <html> <head> <script src="https://www.gstatic.com/firebasejs/live/3.0/firebase.js"></script> <script> // Initialize Firebase var config = { apiKey: "<API_KEY>", authDomain: "<API NAME>.firebaseapp.com", databaseURL: "https://<API NAME>.firebaseio.com/" }; firebase.initializeApp(config); </script> </head> <body> <div> <h1>Firebase確認</h1> <p>signup</p> <p>email:<input type="text" id="email"></p> <p>password:<input type="text" id="password"></p> <p><button onclick="signup()">signup</button></p> <p><button onclick="signin()">signin</button></p> <p><button onclick="signout()">signout</button></p> <br> <p>ログインpush:<input type="text" id="text_id" onchange="push_ok()"></p> <p>ログインしてないpush:<input type="text" id="text_id2" onchange="push_error()"></p> </div> <script> function signup() { var email = document.getElementById('email').value, password = document.getElementById('password').value; firebase.auth().createUserWithEmailAndPassword(email, password).catch(function (error) { console.log(error.message); }); } function signin() { var email = document.getElementById('email').value, password = document.getElementById('password').value; firebase.auth().signInWithEmailAndPassword(email, password).catch(function(error) { console.log(error.message); }); } function signout() { firebase.auth().signOut().catch(function(error) { console.log(error.message); }); } function push_ok() { firebase.database().ref('users').push({ username: document.getElementById('text_id').value }).catch(function (error) { console.log(error.message); }); } function push_error() { firebase.database().ref('rooms').push({ username: document.getElementById('text_id').value }).catch(function (error) { console.log(error.message); }); } </script> </body> </html> |
サインアップする前した後でテキストボックスにデータを入力しRealtime Databaseを確認してみるとよくわかる。
ブラウザのコンソールを開いておくと書き込み権限がない時は「PERMISSION_DENIED: Permission denied」と表示されていることがわかる。
今回はこんな感じでした。
次回はいろんなサービスでログインしてみる!
参考
スポンサードリンク