---
# System prepended metadata

title: Firebase 登入系統

---

# Firebase 登入系統
參考文章：[點這邊](https://medium.com/@anas.mammeri/vue-2-firebase-how-to-build-a-vue-app-with-firebase-authentication-system-in-15-minutes-fdce6f289c3c)


## Install & Import Firebase
```javascript
npm install ——save firebase
```
    

>  創建 firebase.js (放置登入按鈕的地方)[color=black]

:baby_chick: 首先一樣需要 **import firebase**
```javascript
import firebase from 'firebase'
require('firebase/firestore')

var firebaseConfig = {
  apiKey: "AIzaSyBKivYrmxjj_8QjCsmoiUJECAGITOREot4",
  authDomain: "tianyuan-ae158.firebaseapp.com",
  databaseURL: "https://tianyuan-ae158.firebaseio.com",
  projectId: "tianyuan-ae158",
  storageBucket: "tianyuan-ae158.appspot.com",
  messagingSenderId: "266027599129",
  appId: "1:266027599129:web:53341b5e076f5807ec3188"
};

// Initialize & export Firebase
export const fb = firebase.initializeApp(firebaseConfig);
export const db = firebase.firestore();
```

>  進入 main.js、Login.vue[color=blue]

:baby_chick: **import firebase**
```javascript
import { fb } from './firebase.js'
``` 



##  綁定輸入資料v-model
>  進入 Login.vue[color=coral]
>  
:baby_chick: 將每個input綁定v-model
```vue=
<md-tabs md-dynamic-height>
    <md-tab md-label="LOGIN">
        <input v-model="loginEmail" type="email" placeholder="Email">
        <input v-model="loginPwd" type="password" placeholder="Passwrod">
        <button @click="login" @keyup.enter="login">登入</button>
    </md-tab>

    <md-tab md-label="SIGNUP">
        <input v-model="email" type="email" placeholder="Email">
        <input v-model="password" type="password" placeholder="Passwrod">
        <button @click="signUp" @keyup.enter="signUp">Sign up</button>
    </md-tab>
</md-tabs>
```
:baby_chick: 將綁定的v-model對應到data(){}
```javascript=
data(){
      return {
        showDialog: false,
        email: '',
        password: '',
        loginEmail:'',
        loginPwd:'',
      }
```

##  title
>  進入 Login.vue[color=coral]

:baby_chick: **fb.auth().signInWithEmailAndPassword(email, pwd)** 處理登入，並將其中的 email 和 pwd 替換成 data 中的 **v-model** 綁定資料。
:baby_chick: **this.$router.replace('admin')** 設定在登入後自動跳轉至後台  
:baby_chick: **this.showDialog = false**在登入後關閉此登入視窗
```javascript=
methods:{
  login(){
    fb.auth().signInWithEmailAndPassword(this.loginEmail, this.loginPwd)
    .then( (user) => {
      alert('登入成功')
      this.$router.replace('admin')
      this.showDialog = false
    }, (err) => {
      alert(err.message)
      } )
  },
  signUp(){
    fb.auth().createUserWithEmailAndPassword(this.email, this.password)
    .then( (user) => {
      alert('成功創好帳號囉')
      this.showDialog = false
      this.$router.replace('admin')
    }, (err) => {
      alert(err.message)
      } )}
}
```

##  Firebase User Auth Guard
>  進入 router.js[color=pink]
>  
:baby_chick: 在admin path的下方接續輸入 meta, beforeEnter (to,from, next)
```javascript=
meta : { requiresAuth: true },
beforeEnter: (to,from, next) => {
  const requiresAuth = to.matched.some(x => x.meta.requiresAuth)
  const currentUser = fb.auth().currentUser

  if(requiresAuth && !currentUser){
    next('/')
  } else if (currentUser && requiresAuth){
    next()
  } else {
    next()
  }
}
```
>  進入 main.js[color=pink]
>  
:baby_chick: onAuthStateChanged
```javascript=
let app = '';

fb.auth().onAuthStateChanged(function(user){
  if(!app){
    new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount('#app')
  }
})
```
