Ролевая аутентификация vue js firebase - PullRequest
0 голосов
/ 02 апреля 2020

Я использую VueJS с Firebase и у меня есть врачи, администраторы, пациенты. Пациенты не могут получить доступ к роутеру врача. Я следовал за исходным кодом здесь https://github.com/softauthor/vuejs-firebase-role-based-auth?files=1

Я не могу получить сообщение об ошибке, но пациент может обратиться к врачу-маршрутизатору. есть ли кто-нибудь, кто может дать мне решение для этого

Я исправил его, чтобы он тоже не работал

    //router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import firebase from 'firebase'
import Login from '@/views/Login'
import Register from '@/views/Register'
import Admin from '@/views/Admin'
import Driver from '@/views/Doctor'
import Customer from '@/views/Patient'
import Home from '@/views/Home'

Vue.use(Router)

let router = new Router({
  routes: [
  {

      path: '/',
      name: 'home',
      component: Home,
      meta: {
        guest: true
      }
     },


  {
      path: '/register',
      name: 'register',
      component: Register,
      meta: {
        guest: true
      }
    },
    {
      path: '/login',
      name: 'login',
      component: Login,
      meta: {
        guest: true
      }
    },

    {
      path: '/admin',
      name: 'admin',
      component: Admin,
      meta: {
        auth: true
      }
    },
    {
      path: '/doctor',
      name: 'doctor',
      component: Doctor,
      meta: {
        auth: true
      }
    },
    {
      path: '/patient',
      name: 'patient',
      component: Patient,
      meta: {
        auth: true
      }
    },
  ],
})

router.beforeEach((to, from, next) => {

  firebase.auth().onAuthStateChanged(userAuth => {

    if (userAuth) {
      firebase.auth().currentUser.getIdTokenResult()
        .then(then((idTokenResult) =>

         {

          if (!!idTokenResult.claims.patient) {
            if (to.path !== '/patient')
              return next({
                path: '/patient',
              })
          } else if (!!idTokenResult.claims.admin) {
            if (to.path !== '/admin')
              return next({
                path: '/admin',
              })
          } else if (!!idTokenResult.claims.driver) {
            if (to.path !== '/doctor')
              return next({
                path: '/doctor',
              })
          }

        })
    } else {
      if (to.matched.some(record => record.meta.auth)) {
        next({
          path: '/login',
          query: {
            redirect: to.fullPath
          }
        })
      } else {
        next()
      }
    }

  })

  next()

})


export default router









//functions/index.js
    const functions = require('firebase-functions');
    const admin = require('firebase-admin');

admin.initializeApp()



exports.AddUserRole = functions.auth.user().onCreate(async (authUser) => {

  if (authUser.email) {
    const customClaims = {
      customer: true,
    };
    try {
      var _ = await admin.auth().setCustomUserClaims(authUser.uid, customClaims)

      return admin.firestore().collection("roles").doc(authUser.uid).set({
        email: authUser.email,
        role: customClaims
      })

    } catch (error) {
      console.log(error)
    }


  }



});

exports.setUserRole = functions.https.onCall(async (data, context) => {

  if (!context.auth.token.admin) return


  try {
    var _ = await admin.auth().setCustomUserClaims(data.uid, data.role)

    return admin.firestore().collection("roles").doc(data.uid).update({
      role: data.role
    })

  } catch (error) {
    console.log(error)
  }

});

1 Ответ

0 голосов
/ 04 апреля 2020

firebase.auth (). OnAuthStateChanged является асинхронным, поэтому next () в конце защиты маршрутизатора вызывается без ожидания разрешения firebase.auth (). OnAuthStateChanged, что означает, что защита маршрутизатора пропускает всех.

...