Delete Firebase anonymous users after a while

后端 未结 5 891
长情又很酷
长情又很酷 2020-12-16 15:26

I am using anonymous auth to allow my users to use the app without logging in. However, Firebase seems to persist these anonymous user IDs indefinitely. Is there a way to au

5条回答
  •  情歌与酒
    2020-12-16 15:47

    Somehow, there is a way of delete old anonymous users. I do it with a AppEngine cronjob that runs hourly.

    But before you do that you have to define, what a anonymous user is. My users have to validate their email address and therefore I declare all users who are not validated to be anonymously after 90 days.

    With the PubSub tick I then collect all users and delete them, here you've got a sample:

    export const removeOldUsers = functions.pubsub.topic( "hourly-tick" ).onPublish( event => {
        function getInactiveUsers( users: Array = [], nextPageToken?: string ) {
            let userList = users;
    
            return admin.auth().listUsers( 1000, nextPageToken ).then( ( result: any ) => {
                console.log( `Found ${result.users.length} users` );
    
                const inactiveUsers = result.users.filter( ( user ) => {
                    return moment( user.metadata.lastSignInTime ).isBefore( moment().subtract( 90, "days" ) ) && !user.emailVerified;
                } );
    
                console.log( `Found ${inactiveUsers.length} inactive users` );
    
                // Concat with list of previously found inactive users if there was more than 1000 users.
                userList = userList.concat( inactiveUsers );
    
                // If there are more users to fetch we fetch them.
                if ( result.pageToken) {
                    return getInactiveUsers( userList, result.pageToken );
                }
    
                return userList;
            } );
        }
    
        return new Promise( ( resolve ) => {
            console.info( `Start deleting user accounts` );
    
            getInactiveUsers().then( ( users ) => {
                resolve( users );
            } );
        } ).then( ( users: Array ) => {
            console.info( `Start deleting ${users.length} user accounts` );
    
            return Promise.map( users, ( user ) => {
                return admin.auth().deleteUser( user.uid ).then( () => {
                    console.log( "Deleted user account", user.uid, "because of inactivity" );
                } ).catch( ( error ) => {
                    console.error( "Deletion of inactive user account", user.uid, "failed:", error );
                } );
            }, { concurrency: 3 } );
        } ).then( () => {
            console.info( `Done deleting user accounts` );
        } );
    } );
    

    Here I just pushed my class to npmjs @beyond-agentur-ug/firebase-delete-inactive-users

提交回复
热议问题