首页 > 解决方案 > 具有多个条件的 AngularFireAuthGuard

问题描述

我正在开发一个使用 AngularFire 的 Ionic 项目。应用程序有两个主要特点。

我正在使用带有“redirectUnauthorizedToLogin”管道的 AngularFireAuthGuard 来控制路由。

const redirectUnauthorizedToLogin = () => redirectUnauthorizedTo(['login']);

{ path: '...', loadChildren: '...', canActivate: [AngularFireAuthGuard], data: { authGuardPipe: redirectUnauthorizedToLogin } }, 

这两个功能都与 FireStore 交互。由于安全原因,我想实现 Firebase 匿名登录。因此,对于功能 2,我可以控制谁可以写入 db 而无需所有人的许可。同时,功能 1仍然需要一个帐户。

问题来了,因为我找不到向功能 1保护添加两个条件的方法,例如

if (is anonymous || not logged in) redirectToLogin

据我所知,redirectUnauthorizedToLogin 将匿名登录计为授权。

我查看了官方文档,发现有一个“IsNotAnonymous”内置管道,但它只被引用一次,我找不到它的任何其他用法。

我希望有人可以帮助我解决这个问题。

提前致谢,

Ionic:

   Ionic CLI                     : 5.2.1
   Ionic Framework               : @ionic/angular 4.6.0
   @angular-devkit/build-angular : 0.13.9
   @angular-devkit/schematics    : 7.2.4
   @angular/cli                  : 7.3.9
   @ionic/angular-toolkit        : 1.4.0

   "@angular/fire": "^5.2.1",
   "firebase": "^5.11.1",

Cordova:

   Cordova CLI       : 8.1.2 (cordova-lib@8.1.1)
   Cordova Platforms : android 7.1.4

Utility:

   cordova-res : 0.6.0
   native-run  : 0.2.7

System:

   Android SDK Tools : 26.1.1 (D:\Sdk)
   NodeJS            : v11.4.0 (D:\nodejs\node.exe)
   npm               : 6.4.1
   OS                : Windows 10

标签: angularfireauth-guard

解决方案


如果您查看源代码,您可以在这里看到它们是如何实现isNotAnonymous的:https ://github.com/angular/angularfire/blob/5.2.3/src/auth-guard/auth-guard.ts#L32但问题是即 isNotAnonymous 拒绝但不重定向。我认为您基本上可以模仿这一行:https ://github.com/angular/angularfire/blob/5.2.3/src/auth-guard/auth-guard.ts#L37添加重定向。

这些是管道式的,所以你应该很好地使用:


import { AngularFireAuthGuard, isNotAnonymous } from '@angular/fire/auth-guard';

export const redirectAnonymousTo = (redirect: any[]) => 
  pipe(isNotAnonymous, map(loggedIn => loggedIn || redirect)
);

const redirectUnauthorizedToLogin = () => redirectAnonymousTo(['login']);

export const routes: Routes = [
  { path: '', component: AppComponent },
  { 
    path: 'items',
    component: ItemListComponent,
    canActivate: [AngularFireAuthGuard],
    data: { authGuardPipe: redirectUnauthorizedToLogin }
  }
];

如果未经身份验证或匿名,它将返回 false,因此将发生重定向,否则将解析为 true。

我没有尝试执行此代码,但希望这将是一个好的开始。


推荐阅读