Skip to content

Commit

Permalink
Add auth guard
Browse files Browse the repository at this point in the history
Closes #7
  • Loading branch information
salah3x committed Jul 17, 2019
1 parent ba313a8 commit eba5475
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 2 deletions.
2 changes: 2 additions & 0 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { BrowserModule } from '@angular/platform-browser';
import { RouteReuseStrategy } from '@angular/router';
import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
import { AngularFireModule } from '@angular/fire';
import { AngularFireAuthModule } from '@angular/fire/auth';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
Expand All @@ -15,6 +16,7 @@ import { environment } from '../environments/environment';
BrowserModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
IonicModule.forRoot(),
AngularFireAuthModule,
AppRoutingModule
],
providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
Expand Down
6 changes: 5 additions & 1 deletion src/app/auth/auth.page.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,8 @@
</ion-toolbar>
</ion-header>

<ion-content> </ion-content>
<ion-content>
<ion-button routerLink="/tabs/map" expand="block">
Close
</ion-button>
</ion-content>
27 changes: 27 additions & 0 deletions src/app/shared/auth.guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Injectable } from '@angular/core';
import { CanLoad, Route, UrlSegment, Router } from '@angular/router';
import { AngularFireAuth } from '@angular/fire/auth';
import { Observable } from 'rxjs';
import { take, map, tap } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanLoad {
constructor(private authService: AngularFireAuth, private router: Router) {}

canLoad(
route: Route,
segments: UrlSegment[]
): boolean | Observable<boolean> | Promise<boolean> {
return this.authService.authState.pipe(
take(1),
map(user => !!user),
tap(isAuhtenticated => {
if (!isAuhtenticated) {
this.router.navigate(['/auth']);
}
})
);
}
}
4 changes: 3 additions & 1 deletion src/app/tabs/tabs-routing.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { TabsPage } from './tabs.page';
import { AuthGuard } from '../shared/auth.guard';

const routes: Routes = [
{
Expand Down Expand Up @@ -31,7 +32,8 @@ const routes: Routes = [
children: [
{
path: '',
loadChildren: '../settings/settings.module#SettingsPageModule'
loadChildren: '../settings/settings.module#SettingsPageModule',
canLoad: [AuthGuard]
}
]
},
Expand Down

0 comments on commit eba5475

Please sign in to comment.