【问题标题】:Angular 6 - Route Guard based on firestore node valuesAngular 6 - 基于firestore节点值的Route Guard
【发布时间】:2019-04-02 08:51:11
【问题描述】:

我目前正在使用 Firestore 构建一个 Angular 项目。我有一个 users 集合,其中包含用户 uid 以及他们的姓名、电子邮件和公司名称。登录后,我可以成功获取用户 uid,在 firestore 中查找文档,然后将他们重定向到 domain.com/theircompanyname - theircompanyname 是存储在用户集合 > 文档下的 firestore 中的内容。

但是,目前这并不能阻止任何人在 URL 中输入公司名称并成功导航到该 URL。我将如何实施一个路由保护,它只授予与 url 中可见的匹配公司的用户访问权限?

login.ts

login(email: string, password:string) {
  this.afAuth.auth.signInWithEmailAndPassword(email, password).then(value => {
      const user_id = value.user.uid;
      this.userService.checkUserForCorrectRedirect(user_id)
  });
}

user.service.ts 这将根据他们在 firestore 中的公司名称将用户重定向到适当的 URL(我通过将 user_id 从登录名传递到此函数来检查)

checkUserForCorrectRedirect(user_id: string) {
   var docRef = this.db.collection("users").doc(`${user_id}`);

   docRef.get().then((doc) => {
    if (doc.exists) {
        const data = doc.data();
        this.company = data.company;
        this.router.navigate(['e', data.company]);
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
 }).catch((error) => {
    console.log("Error getting document:", error);
 });
}

以上所有工作。如果可能的话,路线守卫是我需要帮助的地方。

router.guard 这显然不起作用,我真的不知道如何使它起作用。

 import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, RouterStateSnapshot, CanActivate, Router } from '@angular/router';
import { UserService } from '../services/user.service';

@Injectable()

export class AuthGuardService implements CanActivate {

    authGuardStateURL: string;

    constructor(
        private router: Router,
        private userService: UserService,
    ) { }



    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot){
        if (this.userService.company == "testcompany") {
            return true;
        } else {
            return false;
        }
    }

    }

【问题讨论】:

  • 你能显示你的路由器保护代码吗?
  • 已添加。但是,它非常没用,因为它太糟糕了...... :)
  • this.userService.company的返回值是多少
  • 无论他们的公司名称是什么。登录后,我获取用户 ID,在 firestore 中查找他们的文档,并在 user.service.ts 中更新公司变量——这就是我希望检查的内容。不确定这是否是正确的方法。
  • 你能把你的方法的代码贴出来this.userService.company

标签: angular google-cloud-firestore angular-route-guards


【解决方案1】:

我认为正确的方法是在您的 Firestore 数据库中创建规则,以确保其安全。我使用规则做了我的,检查用户是否拥有公司,并授予读取权限

【讨论】:

    猜你喜欢
    • 2019-01-22
    • 2017-07-24
    • 2017-07-16
    • 1970-01-01
    • 2019-12-14
    • 2019-01-19
    • 2018-03-18
    • 2017-05-11
    • 1970-01-01
    相关资源
    最近更新 更多