#LoginWithGoogle using signInWithPopup via Firebase, help

5 messages · Page 1 of 1 (latest)

jolly leaf
#

Interface -- >

export interface User {
    uid: string;
    name: string;
    bloq:boolean;
    email: string;
    photoURL: string;
    address?: string;
    admin?:  boolean;
    obs?: string;
    createdAt: number;
    updatedAt: number;
 }

Ok, now we have the function to perform the login system

async loginUser(userEmail, userPsw) {
    this.showSpinner = true;
    await this.authService.login(userEmail, userPsw)
    .then(res => {
      if (res) {
        localStorage.setItem('userUID', res.user.uid);
        localStorage.setItem('userEmail', res.user.email);
        this.authService.getUserProfile(res.user.uid)
        .pipe(take(1))
        .subscribe({
          next: (res) => {
            this.showSpinner = false;
            let userRes = res.payload.data();
            localStorage.setItem('userProfile', JSON.stringify(userRes));
            if(userRes['bloq']===false){
              this.router.navigateByUrl('/inicio');
            }else{
              Swal.fire({
                icon: 'warning',
                title: 'Oops...',
                text: 'Acesso negado! Por favor, fale com os Administradores.'
              });
              return this.authService.logout();
            }
          }, error: (error) => this.showSpinner = false,
          complete: () => this.showSpinner = false
        });         
      } else {
        this.showSpinner = false;
        Swal.fire({
          icon: 'warning',
          title: 'Oops...',
          text: 'Usuário não existe, ou dados incorretos.'
        });
        this.router.navigate(['/login']);
      }
    }).catch((err)=>{
      Swal.fire({
        icon: 'error',
        title: 'Oops...',
        text: 'Informe os seus dados.'
      });
      // console.log('Opss... algo errado.');
      this.router.navigate(['/login']);
    });
#
login(login, psw){
    return this.fireAuth.signInWithEmailAndPassword(login, psw);
  }


 getUserProfile(id: string) {
    let userRef = this.firestore.doc('Users/' + id);
    return userRef.snapshotChanges();
  }



#

Now I'll show you what I'm trying to develop 🧐

#
async loginWithGoogle() {
      const provider = new firebase.auth.GoogleAuthProvider();
      const result = await this.afAuth.signInWithPopup(provider);
    
      const user = result.user;
    
      // Verifica se o usuário já tem um perfil salvo no Firestore
      const userProfileRef = firebase.firestore().collection('usersGoogle').doc(user.uid);
      
      const userProfileSnapshot = await userProfileRef.get();
    
      if (userProfileSnapshot.exists) {
        console.log('Perfil já existe', userProfileSnapshot.data());
      } else {
        localStorage.setItem('userUID', userProfileSnapshot.data().admin);
       
        // Cria um perfil de usuário com as informações adicionais
        
       const userProfileRef = firebase.firestore().collection('UsersGoogle').doc(user.uid).set({
        
          createdAt: Date.now(),
          bloq: false,
          admin: false,
          email: user.email,
          name: user.displayName,
          photoURL: user.photoURL,
          address: 'Adicione seu endereço!',
          obs: 'Ótimo, agora ficou mais fácil participar dos editais!',
          updatedAt: Date.now(),
          
        });

    
        // Salva o perfil no Firestore
        console.log('Perfil criado com sucesso');
      }
      // Navega para a página de início
      this.router.navigateByUrl('/inicio');
    }