1
votes

I am using Firebase SDK, Angular Cli 1.5.5.

I built an application on Angular using firebase authentication. Successfully creating users and login with email and password. but every time i refresh the page, i need to login again. How could i use firebase local storage object to re-authenticate and pass login status to CanActivate auth-guard?

auth-guard.servie file

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthServiceService } from './auth.service';

@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(private auth: AuthServiceService, private router: Router) { }
  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (this.auth.isAuthenticated()) {
      console.log(true);
      return true;
    } else {
      this.router.navigate(['/login']);
      console.log(false);
      return false;
    }
  }
}

AuthService

import { Injectable, OnInit } from '@angular/core';
import * as firebase from 'firebase';
import { Router } from '@angular/router';

@Injectable()
export class AuthServiceService implements OnInit{

  constructor(private router: Router) {}

  ngOnInit() {
  }

  signUpUser(email: string, password: string) {
    return firebase.auth().createUserWithEmailAndPassword(email, password);
  }

  signInUser(email: string, password: string) {
    return firebase.auth().signInWithEmailAndPassword(email, password);
  }

  isAuthenticated() {
    return firebase.auth().currentUser;
  }

  logout() {
   return firebase.auth().signOut();
  }
}
2

2 Answers

0
votes

The guard can return an Observable :

import { AngularFireAuth } from 'angularfire2/auth';

constructor(private firebaseAuth: AngularFireAuth) {}

canActivate(): Observable<boolean> {
    return this.firebaseAuth.authState.pipe(map(user => user !== null));
}
0
votes

This worked for me in the auth guard.

Firebase Javascript SDK no angularfire.

import { Injectable } from '@angular/core';
import { CanLoad, Route, UrlSegment, Router } from '@angular/router';
import { Observable, of } from 'rxjs';
import { take, tap, switchMap } from 'rxjs/operators';
import { AuthService } from './auth.service';
import * as firebase from 'firebase';
import 'firebase/auth';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanLoad {

  constructor(private authService: AuthService,
              private router: Router) {}

  canLoad(
    route: Route,
    segments: UrlSegment[]
  ): boolean | Observable<boolean> | Promise<boolean> {
    return new Promise((resolve, reject) => {
      firebase.auth().onAuthStateChanged((user: firebase.User) => {
        if (user) {
          console.log('User is logged in');
          resolve(true);
        } else {
          console.log('User is not logged in');
          this.router.navigateByUrl('/auth');
          resolve(false);
        }
      });
    });
  }

Source: https://javebratt.com/ionic-firebase-tutorial-auth/