Skip to content

Instantly share code, notes, and snippets.

@daichan4649
Last active May 10, 2022 02:26
Show Gist options
  • Save daichan4649/27c15deae4addff7e9136788eda2f15e to your computer and use it in GitHub Desktop.
Save daichan4649/27c15deae4addff7e9136788eda2f15e to your computer and use it in GitHub Desktop.
Nuxt.js + Firebase Authentication (with FirebaseUI)
// middleware/auth.js
export default async ({ store, redirect }) => {
const loggedIn = await store.dispatch('isLoggedIn')
if (!loggedIn) {
redirect('/login')
}
}
// store/index.js
export const actions = {
async isLoggedIn () {
const user = await this.dispatch("initAuthUser")
return user != null
},
async initAuthUser () {
return new Promise(resolve => {
const unsubscribe = this.$fireModule.auth().onAuthStateChanged((user) => {
resolve(user)
})
unsubscribe()
})
},
async signOut () {
await this.$fire.auth.signOut()
this.$router.push('/login')
},
}
// pages/index.vue
<template>
<div>
<v-btn color="primary" @click="signOut"> signOut </v-btn>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
middleware: ['auth'],
methods: {
...mapActions(['signOut']),
},
}
</script>
// pages/login.vue
<template>
<div>
<div id="firebase-authui"></div>
</div>
</template>
<script>
import 'firebaseui/dist/firebaseui.css'
import { mapActions } from 'vuex'
export default {
async mounted() {
const loggedin = await this.isLoggedIn()
if (loggedin) {
this.$router.push('/')
} else {
this.showFirebaseUi()
}
},
methods: {
...mapActions(['isLoggedIn']),
showFirebaseUi() {
const firebaseui = require('firebaseui')
const uiConfig = {
signInSuccessUrl: '/',
signInOptions: [this.$fireModule.auth.EmailAuthProvider.PROVIDER_ID],
callbacks: {},
}
const ui =
firebaseui.auth.AuthUI.getInstance() ||
new firebaseui.auth.AuthUI(this.$fire.auth)
ui.start('#firebase-authui', uiConfig)
},
},
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment