0
votes

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
// import { User } from './user.model.ts'; // optional

import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';

import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user';
import { HttpClient } from '@angular/common/http';
import { UserService } from './user.service';

@Injectable({ providedIn: 'root' })
export class AuthService {

  user$: Observable<User>;

  constructor(
    private userServe: UserService,
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router
  ) {

    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        // Logged in
        if (user) {
          this.router.navigate(["user_home"]);
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null);
        }
      })
    )
  }
  async googleSignin() {
    const provider = new auth.GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);
   
   const token =(await this.afAuth.currentUser).getIdToken();
   
   console.log(token);
    // localStorage.setItem('token',JSON.stringify(token));
    // var token = credential.accessToken;
    // alert(JSON.stringify(token));
    return this.updateUserData(credential.user);
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      username: user.displayName,
      password: '',
      phone: 0,
      state: '',
      district: '',
      city: '',
      pincode: 0,
    }
    this.userServe.postUserData(data)
      .subscribe(data => {
        console.log("Account added");
      }, error => {
        console.log(error);
      }
      );
    return userRef.set(data, { merge: true })

  }

  async signOut() {
    await this.afAuth.signOut();
    // this.router.navigate(['login']);
  }


}

I was doing a firebase authentication through google , while calling an api from service getting values like below format, const token =(await this.afAuth.currentUser).getIdToken();

console.log(token); ==> "D {a: 0, i: undefined, c: D, b: null, f: null, …} " getting an extra D , So not able to extract the token alone from this structure, Attaching the service calls above. Thanks in advance,

Please let me know anything more needed :)

2

2 Answers

1
votes

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
// import { User } from './user.model.ts'; // optional

import { auth } from 'firebase/app';
import { AngularFireAuth } from '@angular/fire/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/firestore';

import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
import { User } from './user';
import { HttpClient } from '@angular/common/http';
import { UserService } from './user.service';

@Injectable({ providedIn: 'root' })
export class AuthService {

  user$: Observable<User>;

  constructor(
    private userServe: UserService,
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router
  ) {

    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
        // Logged in
        if (user) {
          this.router.navigate(["user_home"]);
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null);
        }
      })
    )
  }
  async googleSignin() {
    const provider = new auth.GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);
   
   const token =(await this.afAuth.currentUser).getIdToken();
   
   console.log(token);
    // localStorage.setItem('token',JSON.stringify(token));
    // var token = credential.accessToken;
    // alert(JSON.stringify(token));
    return this.updateUserData(credential.user);
  }

  private updateUserData(user) {
    // Sets user data to firestore on login
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = {
      uid: user.uid,
      email: user.email,
      displayName: user.displayName,
      photoURL: user.photoURL,
      username: user.displayName,
      password: '',
      phone: 0,
      state: '',
      district: '',
      city: '',
      pincode: 0,
    }
    this.userServe.postUserData(data)
      .subscribe(data => {
        console.log("Account added");
      }, error => {
        console.log(error);
      }
      );
    return userRef.set(data, { merge: true })

  }

  async signOut() {
    await this.afAuth.signOut();
    // this.router.navigate(['login']);
  }


}

< router >

0
votes

This worked for me

const token =(await this.afAuth.currentUser).getIdToken().then(function(idToken){ localStorage.setItem('token',idToken); console.log(idToken) });