Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. import { AngularFireModule } from '@angular/fire';
  2. import { AngularFireAuthModule } from '@angular/fire/auth';
  3. import { AngularFirestoreModule } from '@angular/fire/firestore';
  4.  
  5. @NgModule({
  6. imports: [
  7. BrowserModule.withServerTransition({ appId: 'serverApp' }),
  8.  
  9. // Firebase
  10. AngularFireModule.initializeApp(environment.firebase),
  11. AngularFirestoreModule,
  12. AngularFireAuthModule,
  13.  
  14. // App
  15. AppRoutingModule
  16. ],
  17. declarations: [
  18. AppComponent
  19. ],
  20. bootstrap: [AppComponent]
  21. })
  22.  
  23. export class AppModule {}
  24.  
  25. import { Injectable } from '@angular/core';
  26. import { CanActivate, CanActivateChild, CanLoad } from '@angular/router';
  27. import * as firebase from 'firebase/app';
  28.  
  29. @Injectable({
  30. providedIn: 'root'
  31. })
  32.  
  33. export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
  34.  
  35. /** @ignore */
  36. constructor() {}
  37.  
  38. canLoad(): boolean {
  39. return this.performCheck();
  40. }
  41.  
  42. canActivate(): boolean {
  43. return this.performCheck();
  44. }
  45.  
  46. canActivateChild(): boolean {
  47. return this.performCheck();
  48. }
  49.  
  50. private performCheck() {
  51. return !!firebase.auth().currentUser;
  52. }
  53. }
  54.  
  55. export const Routes = [
  56. {
  57. path: '',
  58. pathMatch: 'full',
  59. redirectTo: 'hello'
  60. },
  61. {
  62. path: 'hello',
  63. component: HelloComponent,
  64. canActivate: [AuthGuard]
  65. }
  66. ];
  67.  
  68. import { Injectable } from '@angular/core';
  69. import { CanActivate, CanActivateChild, CanLoad } from '@angular/router';
  70. import { AngularFireAuth } from '@angular/fire/auth'; // instead of firebase
  71. import { Observable } from 'rxjs';
  72. import { take, map } from 'rxjs/operators'
  73.  
  74. @Injectable({
  75. providedIn: 'root'
  76. })
  77.  
  78. export class AuthGuard implements CanActivate, CanActivateChild, CanLoad {
  79.  
  80. /** @ignore */
  81. constructor(private auth: AngularFireAuth) {}
  82.  
  83. canLoad(): Observable<boolean> {
  84. return this.performCheck();
  85. }
  86.  
  87. canActivate(): Observable<boolean> {
  88. return this.performCheck();
  89. }
  90.  
  91. canActivateChild(): Observable<boolean> {
  92. return this.performCheck();
  93. }
  94.  
  95. private performCheck(): Observable<boolean> {
  96. return this.auth.user.pipe(map((user) => {
  97. if (user) {
  98. // user is logged in
  99. return true;
  100. }
  101. // user is not logged in
  102. return false;
  103. }),
  104. take(1));
  105. }
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement