import { NgModule } from '@angular/core'; import { AuthService } from './auth.service'; import { AngularFireAuthModule } from 'angularfire2/auth'; import { AngularFirestoreModule } from 'angularfire2/firestore'; @NgModule({ imports: [ AngularFireAuthModule, AngularFirestoreModule ], providers: [AuthService] }) export class CoreModule { }
AuthService:
import { Injectable } from '@angular/core'; import { Router } from '@angular/router'; import * as firebase from 'firebase/app'; import { AngularFireAuth } from 'angularfire2/auth'; import { AngularFirestore, AngularFirestoreDocument } from 'angularfire2/firestore'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/switchMap' interface User { uid: string; email: string; photoURL?: string; displayName?: string; favoriteColor?: string; } @Injectable() export class AuthService { user: Observable<User>; constructor(private afAuth: AngularFireAuth, private afs: AngularFirestore, private router: Router) { //// Get auth data, then get firestore user document || null this.user = this.afAuth.authState .switchMap(user => { if (user) { return this.afs.doc<User>(`users/${user.uid}`).valueChanges() } else { return Observable.of(null) } }) } googleLogin() { const provider = new firebase.auth.GoogleAuthProvider() return this.oAuthLogin(provider); } private oAuthLogin(provider) { return this.afAuth.auth.signInWithPopup(provider) .then((credential) => { this.updateUserData(credential.user) }) } private updateUserData(user) { // Sets user data to firestore on login const userRef: AngularFirestoreDocument<any> = this.afs.doc(`users/${user.uid}`); const data: User = { uid: user.uid, email: user.email, displayName: user.displayName, photoURL: user.photoURL } return userRef.set(data) } signOut() { this.afAuth.auth.signOut().then(() => { this.router.navigate(['/']); }); } }
Guard:
import { Injectable } from '@angular/core'; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router'; import { AuthService} from './auth.service' import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/do'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/take'; @Injectable() export class AuthGuard implements CanActivate { constructor(private auth: AuthService, private router: Router) {} canActivate( next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { return this.auth.user .take(1) .map(user => !!user) .do(loggedIn => { if (!loggedIn) { console.log('access denied') this.router.navigate(['/login']); } }) } }