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();
}
}