Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist logged in user with angularfire2 using cookies

Tags:

I'm using a simple custom authentication with angularfire2 and the authentication service from Firebase.

import { Injectable } from '@angular/core';
import { AngularFire } from 'angularfire2';
import { Cookie } from 'ng2-cookies';

@Injectable()
export class GlobalMenuService {

    loggedIn: boolean = false;

    constructor(private af: AngularFire) { }

    login(email: string, password: string) {
        this.af.auth.login({
            email: email,
            password: password
        })
            .then((success) => {
                this.loggedIn = true;
            });
    }

    logout() {
        this.af.auth.logout();
        this.loggedIn = false;
    }
}

Is there a way to save some data in a cookie (token, uid, email or something) to restore the session, i.e. each time the user returns to the app re-login him without him having to write the credentials ?

like image 403
Миле Каранфилов Avatar asked Jul 04 '16 16:07

Миле Каранфилов


1 Answers

You should use auth.subscribe(). This function will be called any time there's a change in the authentication state.

this.af.auth.subscribe(user => {
  if (user) {
    // User is signed in.
    ... do other stuff
  } else {
    // No user is signed in.
    ... do other stuff
  }
});

If you are already logged in when you open your app, or you call signInWithEmailAndPassword, this function will be called and auth will contain your logged user data.

like image 86
Devid Farinelli Avatar answered Nov 03 '22 02:11

Devid Farinelli