Firebase - How to disable user using Cloud Function?

梦想与她 提交于 2020-01-16 09:43:21

问题


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;
});

回答1:


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.




回答2:


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'});
}


来源:https://stackoverflow.com/questions/53105505/firebase-how-to-disable-user-using-cloud-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!