Gleb S
Gleb S

Reputation: 34

How to do a costum authentication with firebase, angular and node?

So I'm making a transition to firebase with my mean application.

But I'm getting lost in all the information on de website of firebase on how to authenticate an user. I can allready create users on firebase and I have a node project.

So my questions are:

how do I need to do the login part?

Do I need to call firebase.auth().signInWithEmailAndPassword() in my angular application?

Do I need to call my node application and to there the autentication?

How do I check if a user is signed in ?

If you guys know a good read-up, i'm very interested

Upvotes: 0

Views: 59

Answers (1)

Ameer Amjed
Ameer Amjed

Reputation: 149

login

import { AngularFireAuth } from '@angular/fire/auth'
import { AngularFireDatabase, AngularFireList ,AngularFireObject } from '@angular/fire/database';
import { Router } from '@angular/router';
import * as firebase from 'firebase';

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


  constructor(private fbAuth: AngularFireAuth ,public router:Router , public db :AngularFireDatabase) {}

  login(email,password){
    this.fbAuth.signInWithEmailAndPassword(email,password)
    .then(async user =>{

        await localStorage.setItem('userData', user.user.refreshToken) 
        this.router.navigate(['home'])

    }).catch(error=>{
           console.error(error)
  }
  }
  
}

Method one check Login Status

isAuth(){
  const luserData = localStorage.getItem('userData');

    // console.log(userData);
    if (luserData && luserData.length > 0) {
      return true;
    } else {
      return false;
    }
}

Method two check Login Status

async loginStatus(): Promise<boolean> {
  return new Promise((resolve,reject) => {
    const auth = firebase.auth()
    auth.onAuthStateChanged(firebaseUser => {
      if(firebaseUser) {
        resolve(true)
      } else {
        resolve(false)
      }
    })
 })
}
  
async checkLoginStatus() {
  const isLoginSuccessed: boolean = await this.loginStatus()
  return isLoginSuccessed;
  }

Hope this helps.

Upvotes: 1

Related Questions