Search code examples
angularauth-guard

Redirect after AuthGuard callback in Angular


I have two routes that require Angular canActivate: [AuthGuard]

const routes: Routes =  [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'home', component: HomeComponent },
  {
    path: 'projects', 
    children: [
      { path: '', component: ProjectsComponent , canActivate: [AuthGuard] },
      { path: 'sjcl', component: HashgenComponent, canActivate: [AuthGuard]  },
    ]
  },
  { path: 'login', component: LoginComponent },
  { path: '**', redirectTo: '/home', pathMatch: 'full' }
];

As you can see if a user is not logged in he is redirected to /login route which by my AuthGuard

if (this.auth.isLoggedIn) { return true; }

return this.auth.currentUserObservable.pipe(
  take(1),
  map(user => {
    console.log('user: ', user);
    return !!user
  }),
  tap(loggedIn => {
    console.log("loggedIn: ", loggedIn);
    if (!loggedIn) {
      console.log("access denied");
      //this.router.navigate(['/login']);
      this.router.navigate(['login'], { queryParams: { returnUrl: state.url } });
    }
  })
);

And my login component is as follows,

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';
import { AngularFireAuth } from '@angular/fire/auth';
import { FirebaseUISignInSuccessWithAuthResult, FirebaseUISignInFailure } from 'firebaseui-angular';
import { Router, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss']
})
export class LoginComponent implements OnInit {

  returnUrl: string;

  constructor(
    public auth: AuthService, 
    private router: Router,
    private route: ActivatedRoute,
    public afAuth: AngularFireAuth) {
      this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
      console.log("yes i am here");
      console.log(this.returnUrl);
     }

  ngOnInit() {}
  ngAfterViewInit(){

  }
  successCallback(signInSuccessData: FirebaseUISignInSuccessWithAuthResult) {
    console.log("Logged in!"+this.returnUrl);
    this.router.navigateByUrl(this.returnUrl);
  }

  errorCallback(errorData: FirebaseUISignInFailure) {
    console.log("Login failure!");
  }
}

PROBLEM

Now, everything is working fine and well except for one thing. Assume

  • I start from /home and click on /projects and login, i am being redirected to /projects after login. (No problem here)
  • I start from /home and click on /projects/sjcl and login, i am being redirected to /projects/sjcl after login. (No problem here)
  • I start from /home and click on /projects and then click on /projects/sjcl and login, i am being redirected to /projects after login, whereas i should've been redirected to /projects/sjcl (Problem here)

The thing is,

  this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
  console.log("yes i am here");
  console.log(this.returnUrl);

is not being called if LoginComponent is already loaded and being called again from another Authguard. I tried using different lifecycles and even placed it on constructor still no help.

How should above snippet be called everytime LoginComponent is loaded?


Solution

  • Dont use route snapshot but rather listen to route change. Router have event for that that you can subscribe to. Update your "return" URL accordingly.