Advertisement
roboalex2

AuthService

Jun 14th, 2021
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.27 KB | None | 0 0
  1. import { Router } from '@angular/router';
  2. import { Observable } from 'rxjs';
  3. import { Injectable } from '@angular/core';
  4. import { AngularFireAuth } from '@angular/fire/auth';
  5. import { AngularFirestore } from '@angular/fire/firestore';
  6. import firebase from 'firebase/app';
  7.  
  8. @Injectable({
  9. providedIn: 'root'
  10. })
  11. export class AuthService {
  12. user$: Observable<any>;
  13.  
  14. constructor(private afAuth: AngularFireAuth, public db: AngularFirestore, private router: Router) {
  15. this.user$ = afAuth.authState;
  16. this.db = db;
  17.  
  18. afAuth.onAuthStateChanged((user) => {
  19. if (user && user.emailVerified) {
  20. console.log("Logged in");
  21.  
  22. db.collection('user').doc(user.uid).valueChanges().subscribe((data) => {
  23. console.log("User Data loaded: " + JSON.stringify(data));
  24. });
  25. } else {
  26. this.router.navigate(['/login']);
  27.  
  28. }
  29. });
  30. }
  31.  
  32. async login() {
  33. await this.afAuth.setPersistence(firebase.auth.Auth.Persistence.SESSION)
  34. .then(() => {
  35. const credential = this.afAuth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  36. });
  37. return this.router.navigate(['/dashboard']);
  38. }
  39.  
  40. async logout() {
  41. await this.afAuth.signOut();
  42. return this.router.navigate(['/login']);
  43. }
  44. }
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement