Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 使用自定义声明的角度和firebase路线防护_Angular_Firebase_Oauth_Google Cloud Firestore_Angularfire - Fatal编程技术网

Angular 使用自定义声明的角度和firebase路线防护

Angular 使用自定义声明的角度和firebase路线防护,angular,firebase,oauth,google-cloud-firestore,angularfire,Angular,Firebase,Oauth,Google Cloud Firestore,Angularfire,我在firestore auth中动态创建用户,并添加了多种类型的声明,即管理员、讲师、助理。到目前为止,我能够使用新创建的用户登录,并根据我提供的登录凭据将claims属性设置为true,即管理员:true,讲师:true。但是我无法在路由中正确设置[AuthGuard],甚至在没有登录的情况下,我能够使用URL重定向到组件,这不应该发生。对于如何正确添加AuthGuard,我有点困惑。这是我的密码 auth-service.ts import * as firebase from 'fire

我在firestore auth中动态创建用户,并添加了多种类型的声明,即管理员、讲师、助理。到目前为止,我能够使用新创建的用户登录,并根据我提供的登录凭据将claims属性设置为true,即
管理员:true
讲师:true
。但是我无法在路由中正确设置
[AuthGuard]
,甚至在没有登录的情况下,我能够使用URL重定向到组件,这不应该发生。对于如何正确添加
AuthGuard
,我有点困惑。这是我的密码

auth-service.ts

import * as firebase from 'firebase/app';

import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore } from '@angular/fire/firestore';
import { Injectable } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
import { Observable } from 'rxjs/Observable';
import { Router } from "@angular/router";

@Injectable() 
export class AuthService {
public user: Observable<firebase.User>;
public userDetails: firebase.User = null;

constructor(private _firebaseAuth: AngularFireAuth, private router: Router, 
    private _firestore: AngularFirestore,
    public jwtHelper: JwtHelperService ) {
    this.user = _firebaseAuth.authState;
    this.user.subscribe(
        (user) => {
            if(user) {
                this.userDetails = user;   
                this._firebaseAuth.auth.currentUser.getIdTokenResult(true).then(res => {
                    user= res.claims;
                })
            }
            else {
                this.userDetails = null;
            }
        }
    );
}
}
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/take';

import { CanActivate, Router } from '@angular/router';

import { AuthService } from './auth-service.service';
import { Injectable } from "@angular/core";
import { Observable } from "rxjs/Rx";
import { tap } from 'rxjs/operators';

@Injectable()

export class AuthGuard implements CanActivate {

    constructor(private auth: AuthService, private router: Router) { }

    canActivate() {
      return this.auth.user
              .take(1)
              .map(authState => !!authState)
              .do(authenticated => {
                if (!authenticated) {
                    this.router.navigate(['auth/login']);
                }
              });

    }

  }
app-routing.module.ts

import { ExtraOptions, RouterModule, Routes } from '@angular/router';

import { AuthGuard } from './auth/auth-guard.service';
import { LoginComponent } from './auth/login/login.component'
import {
  NbAuthComponent,
} from '@nebular/auth';
import { NgModule } from '@angular/core';
import { RegisterComponent } from './auth/register/register.component';
import { RequestPasswordComponent } from './auth/request-password/request-password.component';
import { ResetPasswordComponent } from './auth/reset-password/reset-password.component';

const routes: Routes = [
  {
    path: 'pages',
    canActivate: [AuthGuard],
    loadChildren: () => import('../app/pages/pages.module')
      .then(m => m.PagesModule),
  },
  {
    path: 'studentcourseregistration',
    loadChildren: () => import('../app/studentcourseregistration/studentcourseregistration.module')
      .then(m => m.StudentcourseregistrationModule),
  },
  {
    path: 'auth',
    component: NbAuthComponent,
    children: [
      {
        path: '',
        component: LoginComponent,
      },
      {
        path: 'login',
        component: LoginComponent,
      },
      {
        path: 'register',
        component: RegisterComponent,
      },
      // {
      //   path: 'logout',
      //   component: ,
      // },
      {
        path: 'request-password',
        component: RequestPasswordComponent,
      },
      {
        path: 'reset-password',
        component: ResetPasswordComponent,
      },
    ],
  },
  // {
  //   path: 'student',
  //   loadChildren: () => import('../student/student.module')
  //     .then(m => m.StudentModule),
  // },
  { path: '', redirectTo: 'auth/login', pathMatch: 'full' },
  { path: '**', redirectTo: 'pages' },
];

const config: ExtraOptions = {
  useHash: false,
};

@NgModule({
  imports: [RouterModule.forRoot(routes, config)],
  exports: [RouterModule],
})
export class AppRoutingModule {
}
像这样在auth中添加新用户

  this._firebaseAuth.auth.createUserWithEmailAndPassword(this.user.email, this.user.password)
  .then(cred => {
    const adminRole = firebase.functions().httpsCallable('addAdminRole');
    adminRole({email: this.user.email}).then(res => {
      console.log(res);
    })
  })

它将是这样的:

import { CanActivate, Router } from '@angular/router';
import { Injectable } from "@angular/core";
import { AngularFireAuth } from '@angular/fire/auth';
import { take, switchMap } from 'rxjs/operators';

@Injectable()
export class AdminGuard implements CanActivate {

    constructor(private auth: AngularFireAuth, private router: Router) { }

    canActivate() {
        return this.auth.authState.pipe(
            take(1),
            switchMap(async (authState) => {
                if (authState) { // check are user is logged in
                    const token = await authState.getIdTokenResult()
                    if (!token.claims.admin) { // check claims
                        this.router.navigate(['/auth/login'])
                        return false
                    } else {
                        return true
                    }
                } else {
                    this.router.navigate(['/auth/login'])
                    return false
                }
            }),
        )
    }
}

那么有没有用户登录成为管理员?XD@Mises没有注册的选项。将只有一个管理员,该管理员将被允许添加其他管理员。将向新添加的用户发送讲师或助理以及邮件,以更改其默认密码。到目前为止,代码尚未处于最佳状态。请指出我的问题的解决方案检查是answear fit。它说authState在auth上不存在,也找不到takeauthState确实存在。我注入AngularFireAuth不是您的服务。最好下载实际的authState,而不是读取用户内存中的内容,因为它可能已过期。为什么
take(1)
而不是
last()