AngluarFire 2 authState function displaying null after refreshing the page

Currently, I am working on integrating Firebase with AngularFire 2 and facing an issue.

The problem arises when I try to refresh the page, as the auth instance returns null.

Below is the code snippet for my AuthService:

Everything functions correctly, but every time I reload the page, the auth becomes null which prevents me from accessing the Firebase database due to authentication rules.

export class AuthService {
private userDetails: Users = null;
private dbUsers;
public loginStatus = new BehaviorSubject(false);

public GOOGLE_OATH_SCOPES = 'email, https://www.googleapis.com/auth/drive';

constructor(
    private _firebaseAuth: AngularFireAuth,
    private router: Router,
    private firebase: AngularFireDatabase,
    private _userService: UserService
) {
    var currentUser = JSON.parse(localStorage.getItem('currentUser'));
    this.setUserFromLocalstorage(currentUser);
    _firebaseAuth.authState.subscribe(
        (user) => {
             console.log("Step 1", user);
            if (user) {

            }
            else {
                this.setUserFromLocalstorage(currentUser);
            }
        }
    );

}
setUserFromLocalstorage(currentUser) {
    if (currentUser && !_.isEmpty(currentUser)) {
        this.userDetails = currentUser;
    } else {
        this.userDetails = null;
    };
}
signInWithGoogle() {
    var provider = new firebase.auth.GoogleAuthProvider();
    provider.setCustomParameters({
        prompt: 'select_account'
    });
    provider.addScope(this.GOOGLE_OATH_SCOPES);
    this._firebaseAuth.auth.setPersistence(firebase.auth.Auth.Persistence.NONE).then(() =>
        this._firebaseAuth.auth.signInWithPopup(
            provider
        ).then((result) => {
            localStorage.setItem('accessToken', result.credential.accessToken);
        })
    )
}

isLoggedIn() {
    if (!this.loginStatus.value) {
        return false;
    } else {
        return true;
    }
}


logout() {
    this._firebaseAuth.auth.signOut()
        .then((res) => {
            this.router.navigate(['/'])
            localStorage.clear()
            this.userDetails = null;
            this.loginStatus.next(false);
        }
        );

}


getLoggedInUser() {
    return _.cloneDeep(this.userDetails);
}

setLoggedInUser(user: Users) {
    this.userDetails = user;
    localStorage.setItem("currentUser", JSON.stringify(user));
}

}

Concerning AngularFireAuth:

export declare class AngularFireAuth {
    private zone;
    readonly auth: FirebaseAuth;
    readonly authState: Observable<User | null>;
    readonly idToken: Observable<string | null>;
    constructor(config: FirebaseOptions, name: string, platformId: Object, zone: NgZone);
}

Regarding my SignIn Method:

this._firebaseAuth.auth.setPersistence(firebase.auth.Auth.Persistence.None).then(() =>
                this._firebaseAuth.auth.signInWithPopup(
                    provider
                ).then((result) => {

                })
    )

I am seeking a solution to overcome this issue. Any suggestions are welcomed!

Answer №1

Your login method needs to be adjusted.

this._firebaseAuth.auth.setPersistence(firebase.auth.Auth.Persistence.None).then(() =>
            this._firebaseAuth.auth.signInWithPopup(
                provider
            ).then((result) => {

            })
)

The line

setPersistence(firebase.auth.Auth.Persistence.None)
indicates that the state will only be stored temporarily in memory and will be cleared upon window or activity refresh.

Consider switching to either

firebase.auth.Auth.Persistence.Session
or
firebase.auth.Auth.Persistence.Local

depending on your specific needs.

For more information, please visit : https://firebase.google.com/docs/auth/web/auth-state-persistence

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generic partial application fails type checking when passing a varargs function argument

Here is a combinator I've developed that converts a function with multiple arguments into one that can be partially applied: type Tuple = any[]; const partial = <A extends Tuple, B extends Tuple, C> (f: (...args: (A & B)[]) => C, ...a ...

The VSCode's intellisense for Angular Material fails to function effectively

In the midst of my project on Angular version 13, I have successfully installed Angular Material using the command below: ng add @angular/material The package has been properly included in the node_modules folder. However, when working with TypeScript ...

Implement new interface methods on-the-fly

I am seeking a way to dynamically incorporate methods that are defined in an interface. Initially, I considered using the index signature approach, but unfortunately, not all methods have the same signature. My objective is to preserve all type information ...

How can I dynamically render a component using VueJS?

Incorporating a component named CanvasComp from my components folder, I am rendering it on the template like <CanvasComp :jsoData="data"/> to send jsonData to the component. However, I am seeking a way to dynamically render this component w ...

The repository's dependencies remain unresolved by Nest

I encountered an error in my nestjs application. Unfortunately, I am having trouble identifying the issue within my code snippet. Here is a glimpse of the relevant sections: AppModule import { Module } from '@nestjs/common'; import { TypeOrmMod ...

The image that was uploaded onto Firebase is not displaying properly

When storing images, a hierarchy of folders is created in the storage path. Within these folders, the image file is saved. However, I have encountered an issue where downloaded images do not open correctly. const completeAlbum = () => { let alb ...

Attaching an event listener to elements with a specified Class name

Currently facing a challenge where I am trying to implement a function that captures click events on squares. The objective is to capture the click event on every button with the square class. import { Component, OnInit } from '@angular/core&apos ...

Encountering a "ReferenceError: global is not defined" in Angular 8 while attempting to establish a connection between my client application and Ethereum blockchain

I'm trying to configure my web3 provider using an injection token called web3.ts. The token is imported in the app.component.ts file and utilized within the async ngOnInit() method. I've attempted various solutions such as: Medium Tutorial ...

encounter an auth/argument issue while using next-firebase-auth

Issues: Encountered an error while attempting to log in using Firebase Authentication. No errors occur when using the Firebase Auth emulator, but encountered errors without it. Received a 500 response from login API endpoint: {"error":"Unex ...

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

How can I make TypeScript's http.get Observable wait for the inline parameter to be returned?

I'm currently facing an issue with my http.get call in which I need one of the parameters (getUserToken) to be returned before the function is executed. However, I don't want to chain them together since the calling function getSomeData returns a ...

Creating a union type from an array that is not a literal (using `Object.keys` and `Array.map`)

Can a union be derived from a non-literal array? I attempted the following: const tokens = { "--prefix-apple": "apple", "--prefix-orange": "orange" }; const tokenNames = Object.keys(tokens).map(token => toke ...

Exploring the possibilities of ZMQ_XPUB_MANUAL in action with zeromq.js

I'm currently in the process of setting up a pub/sub broker using ZeroMQ, and I want to ensure that clients are only able to subscribe to authorized prefixes. While researching this topic, I came across a helpful tutorial that discusses achieving a si ...

Is it possible to display the combined string when concatenating two strings?

Consider the following code snippet: const a = "url"; const b = "/route"; const c = a + b; Even though TypeScript knows the exact values of a and b, resulting in immutable constants, when concatenating both strings, the type of c is di ...

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

Received corrupted file during blob download in Angular 7

When using Angular 7, I am making an API call by posting the URL file and attempting to download it using the 'saveAs' function from the fileSaver library. The file is successfully downloading, but it appears to be corrupted and cannot be opened. ...

Unable to automatically redirect to portal upon submission of form

After successfully logging the user into my app, I want to redirect them imperatively to the portal page. However, when I use the router.navigate() function, a few things happen that are causing issues. First, the app redirects to /portal. Then, it immedia ...

NgZone is no longer functioning properly

Seemingly out of the blue, my NgZone functionality has ceased to work. I'm currently in the process of developing an application using Ionic, Angular, and Firebase. An error is being thrown: Unhandled Promise rejection: Missing Command Error ; Zon ...

What steps can I take to make sure that the asynchronous initialization in the Angular service constructor has finished before proceeding?

Hello experts, can you advise on ensuring that asynchronous initialization in the service constructor is completed before calling other functions within the class? constructor() { var sock = new SockJS(this._chatUrl); this.stompClient = Stomp.ov ...

Having difficulty utilizing defineProps in TypeScript

For some time now, I've been utilizing withDefaults and defineProps. Unfortunately, this setup has recently started failing, leaving me puzzled as to why! Here's a simple SFC example: <script setup lang = "ts"> const props ...