Angular Firebase Routeguard Аутентификация - PullRequest
0 голосов
/ 17 февраля 2020

Я на самом деле изучаю Angular и firebase, я хочу добавить защиту маршрута на панель инструментов пользователей, чтобы только зарегистрированные пользователи могли просматривать страницу. Аутентификация работает нормально, но у меня возникают проблемы, не позволяющие никому не заходить в систему для доступа к панели пользователя. Это мой код ниже.

Authservice.service.ts

@Injectable({
      providedIn: 'root'
    })
    export class AuthServiceService {

      newUser: any;
      // passing Error message
      private eventAuthError = new BehaviorSubject<string>('');
      eventError$ = this.eventAuthError.asObservable();
      showSuccessCreated: boolean;

      constructor( private authz: AngularFireAuth, private db: AngularFirestore, private route:Router) 
      { } 
      // geting user details
      getUserState() {
       return this.authz.authState;
      }

      // LoggIn Users
      login(email: string , password: string ) {
        this.authz.auth.signInWithEmailAndPassword(email, password)
        .catch( error => {
          this.eventAuthError.next(error);
      }).then(userCredential => {
        if (userCredential) {
          this.route.navigate(['/dashboard']);
        }
      });
      }

Это служба Authguard, я пытаюсь сослаться на метод входа из моего authservice.service.ts, но он все еще перенаправляет на панель пользователя, несмотря на то, что я не вошел в систему.

authguard.service.ts

export class AuthguardService implements CanActivate {
  constructor(private authservice: AuthServiceService, private route: Router) { }

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {

    let isAuthenicated = !!this.authservice.login;
    if(isAuthenicated ){
     return true;
    }
    console.log('Access denied');
    this.route.navigate(['/login']);
    return false;
  }
}

route.module.ts

const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent, canActivate:[AuthguardService],
     children: [
      {path: '', redirectTo: 'employees', pathMatch: 'full'},
      {path: 'employees', component: EmployeelistComponent, resolve: {employeeList: ResolverGuardService}},
      {path: 'detail/:id', component: EmployeeDetailComponent,  canActivate: [CanActivateGuardService],

      { path: 'notfound', component: PageNotFoundComponent},

     ]
    },



];

1 Ответ

0 голосов
/ 17 февраля 2020

Я понял, что вы вызываете метод с именем login, который обрабатывает обещание в классе AuthGuard.

Вы должны правильно обработать свой метод входа в систему, чтобы получить правильный ответ и сохранить его в переменной isAuthenicated.

Возможно, вы можете сделать что-то похожее на код ниже.

AuthService.ts

login(): Promise<boolean> {
  // create new promise and handle our login flow 
  return new Promise((resolve, reject) => {
    // get email and password somehow
    const = email = this.getEmail();
    const = password = this.getPassword();
    // call sign in with email and password
    return this.authz.auth.signInWithEmailAndPassword(email, password)
     .catch( error => {
       this.eventAuthError.next(error);
       // reject our promise on error
       reject(false);
      })
      .then(userCredential => {
       if (userCredential) {
         // resolve our login promise
         resolve(true);
       } else {
         // reject our promise on userCredential falsy value
         reject(false);
       }
     });
  });
}

AuthGuard.ts

 export class AuthguardService implements CanActivate {
      constructor(private authservice: AuthServiceService, private route: Router) { }

      async canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        // handling our promise properly with asnyc/await
        const isAuthenicated = await this.authservice.login();
        if(isAuthenicated ){
          // here we allow enter the page dashboard or any other
          return true;
        }
        console.log('Access denied');
        this.route.navigate(['/login']);
        return false;
      }
    }
...