I am building an ionic app with ionic4. Therefore I use firestore as database. Also I want to use the firebase-authentication to login and register to my app. The problem is as following: I have multiple pages on my websites. Some of the pages are for public access, and some of them are for private access. With a router guard I achieved, that the private ones are only visible, if I'm logged in. My problem is now, that there are public sites (like login or register) which should only be accessable if I'm not logged in.
In the moment my routing works like this, that I have a "/" directory and all the private stuff is in the "/private/" directory. This directory has an own router guard, which is only accessible if logged in. I would prefere, that everything sits in the "/" directory. To this issue I want to achieve, that my router redirects a user to an error page if he tries to access a private page without beeing logged in or if he tries to access a public page, which should not be accessable if he's logged in.
Router:
const routes: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full' },
{ path: 'home', loadChildren: './pages/home/home.module#HomePageModule' },
{ path: 'login', loadChildren:
'./pages/public/login/login.module#LoginPageModule' },
{ path: 'register', loadChildren:
'./pages/public/register/register.module#RegisterPageModule' },
{
path: 'private',
canActivate: [AuthGuardService],
loadChildren: './pages/private/private-routing.module#PrivateRoutingModule'
},
// TODO: Create an awesome 404 Page :D
{ path: '**', redirectTo: 'home' },
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {}
RouterGuard:
@Injectable({
providedIn: 'root'
})
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthenticationService, private router: Router) {
}
canActivate(): boolean {
const isAuthenticated = this.auth.isAuthenticated();
if (!isAuthenticated) {
this.router.navigate(['/login']);
}
return isAuthenticated;
}
}
You can find my code on GitHub: Code
I hope my problem is clear and I'm happy for every answer :)
Edit: I got no results and am really stuck! Any help is welcome!!