Search code examples
angularfirebase-authenticationangular11

Angulare Fire, extending AuthGuard and redirect url


Anguar Fire comes with an own set of guards (AngularFireAuthGuard):

https://github.com/angular/angularfire/blob/master/docs/auth/router-guards.md

However, when using them I can no longer store the redirect url. Storing the redirect url within the Auth Guard is incredibly handy, as you can simply use this value for any auth state observer, auto routing you to the previous page.

Storing the redirect url with the guard is the intended Angular way too, see https://angular.io/guide/router-tutorial-toh#milestone-5-route-guards chapter "Authenticate with AuthGuard".

So how can I customize/enrich the logic of the Fire Auth guards to also simply store the redirect url?


Solution

  • Hmm, will be good if we can see some attempt codes. Especially to where you would like to redirect? and after what condition if any?

    In any case, this is how I redirect unauthorized users.

    *EDITED: As mentioned in the comment. I use the AngularAuthGuard to direct the unauthorized user to the auth page, in the auth component I grab the previous URL by subscribing to the router events and use RXJS filter operation to just get previous.

    Well depends on how your logic is. This works fine for me. I bet there is something better. Might be more of a workaround. Cheer~

    Redirect Unauthorized Users

    import {
      AngularFireAuthGuard,
      redirectUnauthorizedTo,
    } from '@angular/fire/auth-guard';
    
    const redirectUnauthorizedToLogin = () => redirectUnauthorizedTo(['loginPage']);
    
    const routes: Routes = [
      {
        path: 'members',
        component: InstructorComponent,
        canActivate: [AngularFireAuthGuard],
        data: { authGuardPipe: redirectUnauthorizedToLogin },
      },
    ]
    

    Auth component page

    import { NavigationEnd, Router } from '@angular/router';
    import { filter } from 'rxjs/operators';
    
    previousUrl: string;
    currentUrl: string;
    
    constructor(private router: Router) {}
    
    ngOnInit(): void {
        this.router.events
          .pipe(filter((event) => event instanceof NavigationEnd))
          .subscribe((event: NavigationEnd) => {
            this.previousUrl = this.currentUrl;
            this.currentUrl = event.url;
            console.log(this.previousUrl);
          });
      }
    
    reDirectToPreviousURL() {
        this.router.navigate([this.previousUrl]);
      }