3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Firebaseの匿名認証をvuexで実装してみる。

Posted at

vuexでFirebaseの匿名認証を実装したので、サンプルとして投稿してみます。

最終的に、「$store.getters.uid」で、
いつでもどこでもuidを出せるようにすることが目的です。

環境・VueCLI3.0

store.js
state: {
    login_user: null
},
mutations: {
    setLoginUser (state, user) {
      state.login_user = user
    },
    deleteLoginUser (state) {
      state.login_user = null
    },
},

actions: {
    setLoginUser ( { commit }, user) {
      commit('setLoginUser', user)
    },
    deleteLoginUser ( { commit } ){
      commit('deleteLoginUser')
    },
    logout(){
      firebase.auth().signOut()
    },
    login(){
      firebase.auth().signInAnonymously().catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        // ...
      });
    },
},

getters: {
    uid: state => state.login_user ? state.login_user.uid : null
}


app.vue
<template>
    <v-icon @click="login">mdi-square-edit-outline</v-icon>
</template>

<script>
import firebase from 'firebase'
import { mapActions } from 'vuex'
import { mapGetters } from 'vuex'

export default {
  created() {
    firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setLoginUser(user)
      } else {
        this.deleteLoginUser()
      }
    })
  },
  methods: {
    ...mapActions(['login','setLoginUser','logout','deleteLoginUser']),
    ...mapGetters(['uid'])
  },
}
</script>

ほぼコピペで使えると思います!

あとは、Firebaseのコンソールでログイン方法の有効にすれば認証してくれます!

スクリーンショット 2019-09-26 2.26.48.png

若干解説をすると、

actionで定義したloginを着火させると、

app.vueのcreatedにある firebase.auth().onAuthStateChanged

が発動してuserオブジェクトからデータを取得し、ミューテーション等を介して最終的にgettersでuidをどこでも取得できるようになります。

なぜ発動するのかというと、公式に「発動するよ☆」って書いてあるので発動します(体育会系の思考)

以上です!

参考・https://firebase.google.com/docs/auth/web/anonymous-auth?hl=ja

3
1
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?