An Angular 5 authentication application using angularfire2 and Firebase has been developed. The app functions correctly when navigating through in-app links. However, an issue arises when refreshing the browser, as it redirects back to the Login page even after a successful login with Firebase. The 'allowed' status always returns false despite being true.
AuthInfo Class
export class AuthInfo {
constructor(public $uid: string) {}
isLoggedIn() {
return !!this.$uid;
}
}
AuthService Class
import { Injectable } from '@angular/core';
import { Observable, Subject, BehaviorSubject } from 'rxjs/Rx';
import { AngularFireAuth } from 'angularfire2/auth';
import { AuthInfo } from '../security/auth-info';
import { Router } from '@angular/router';
import * as firebase from 'firebase/app';
@Injectable()
export class AuthService {
static UNKNOWN_USER = new AuthInfo(null);
authInfo$: BehaviorSubject<AuthInfo> = new BehaviorSubject<AuthInfo>(AuthService.UNKNOWN_USER);
constructor(private afAuth: AngularFireAuth, private router: Router) {}
login(email, password): Observable<AuthInfo> {
return this.fromFirebaseAuthPromise(this.afAuth.auth.signInWithEmailAndPassword(email, password));
}
// signUp(email, password) {
// return this.fromFirebaseAuthPromise(this.afAuth.auth.createUserWithEmailAndPassword(email, password));
// }
fromFirebaseAuthPromise(promise): Observable<any> {
const subject = new Subject<any>();
promise
.then(res => {
const authInfo = new AuthInfo(this.afAuth.auth.currentUser.uid);
this.authInfo$.next(authInfo);
subject.next(res);
subject.complete();
},
err => {
this.authInfo$.error(err);
subject.error(err);
subject.complete();
});
return subject.asObservable();
}
logout() {
this.afAuth.auth.signOut();
this.authInfo$.next(AuthService.UNKNOWN_USER);
this.router.navigate(['/login']);
}
refresh() {
const url = window.location.href;
}
}
AuthGuard Class
import { tap, take, map } from 'rxjs/operators';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { Observable } from 'rxjs/Rx';
import { Injectable } from '@angular/core';
import { AuthService } from '../security/auth-service';
import { Location } from '@angular/common';
@Injectable()
export class AuthGuard implements CanActivate {
redirectUrl: string;
currentURL = '';
constructor(private authService: AuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean> {
console.log(this.authService.authInfo$);
return this.authService.authInfo$.pipe(
map(authInfo => authInfo.isLoggedIn()),
take(1),
tap(allowed => {
if (!allowed) {
console.log(allowed);
this.router.navigate(['/login']);
}
}),
);
}
}