0

I am actually learning Angular and firebase, I want to add a route guard to users dashboard so that only logged in users can view the page. The Authentication works fine but I am having issues restricting none logged in users to access users dashboard This is my code below.

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']);
        }
      });
      }

This is the Authguard service, I try to reference the login method from my authservice.service.ts, but it still redirects to users' dashboard despite I am not Logged In.

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},

     ]
    },



];
Gabriel Geelario
  • 227
  • 1
  • 2
  • 16

1 Answers1

0

I realized that you are calling a method called login which handles a promise into AuthGuard class.

You have to handle your login method properly in order to get the correct response and save it into isAuthenicated variable.

You maybe can do something similar to the code below.

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;
      }
    }
bjdose
  • 1,269
  • 8
  • 10