Dennis Schiepers
Dennis Schiepers

Reputation: 137

Firebase - How to disable user using Cloud Function?

I am trying to work out an enable/disable user cloud function. When using the admin SDK to disable the user, I get the response: that the disabled property is read only. Can someone help me out? The data that is passed to the function, is the user ID.

 export const disableUser = functions.https.onCall((data, context) => {
    console.log(data);

    admin.auth().updateUser(data, {
        disabled: true
    }).then(() => {
        admin.firestore().collection('users').doc(data).update({ disabled: true})
            .then(() =>  {
                console.log(`Successfully disabled user: ${data}`);

                return 200;
            })
            .catch((error => console.log(error)));        
    }).catch( error => console.log(error));

    return 500;
});

Upvotes: 2

Views: 2478

Answers (2)

Suhail Kawsara
Suhail Kawsara

Reputation: 515

I used typeScript for Cloud Functions.

index.ts

import * as functions from 'firebase-functions';

export const disableUser = functions.https.onCall((data, context) => {
  const userId = data.userId;
  return functions.app.admin.auth().updateUser(userId, {disabled: true});
});

In my app, I called "disableUser" function like this:

import {AngularFireFunctions} from '@angular/fire/functions';

export class AppComponent {

data$: Observable<any>;
callable: (data: any) => Observable<any>;

constructor(private fns: AngularFireFunctions) {
  this.callable = fns.httpsCallable('disableUser');
  this.data$ = this.callable({userId: 'ZDxaTS0SoYNYqUVJuLLiXSLkd8A2'});
}

Upvotes: 3

Doug Stevenson
Doug Stevenson

Reputation: 317562

It looks like you're trying to return an HTTP status code from your function. It doesn't work that way. Please read the documentation for callable functions to understand what to return.

Since you are performing asynchronous work in your function (updateUser(), then update()), you need to return a promise that resolves with the data to send to the client. Right now, you are just returning 500 before the async work completes. At the very least, you need to return the promise from update() so that Cloud Functions knows when your async work is done.

return admin.auth().updateUser(...)
.then(() => {
    return admin.firestore().collection('users').doc(data).update(...)
})

It's crucial to understand how promises work when deal with Cloud Functions for Firebase. You can't just return whatever you want.

Upvotes: 2

Related Questions