|
| 1 | +/** |
| 2 | + * Copyright 2016 Google Inc. All Rights Reserved. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for t`he specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +'use strict'; |
| 17 | + |
| 18 | +const functions = require('firebase-functions'); |
| 19 | +const firebaseAdmin = require('firebase-admin'); |
| 20 | +const serviceAccount = require('./service-account.json'); |
| 21 | +firebaseAdmin.initializeApp({ |
| 22 | + credential: firebaseAdmin.credential.cert(serviceAccount), |
| 23 | + databaseURL: `https://${serviceAccount.project_id}.firebaseio.com` |
| 24 | +}); |
| 25 | +const google = require('googleapis'); |
| 26 | +const rp = require('request-promise'); |
| 27 | +const promisePool = require('es6-promise-pool'); |
| 28 | +const PromisePool = promisePool.PromisePool; |
| 29 | +const MAX_CONCURRENT = 3; |
| 30 | + |
| 31 | +/** |
| 32 | + * When requested this Function will delete every user accounts that has been inactive for 30 days. |
| 33 | + * The request needs to be authorized by passing a 'key' query parameter in the URL. This key must |
| 34 | + * match a key set as an environment variable using `firebase env:set cron.key="YOUR_KEY"`. |
| 35 | + */ |
| 36 | +exports.accountcleanup = functions.https().onRequest((req, res) => { |
| 37 | + const key = req.query.key; |
| 38 | + |
| 39 | + // Exit if the keys don't match |
| 40 | + if (key !== functions.env.cron.key) { |
| 41 | + console.log('The key provided in the request does not match the key set in the environment. Check that', key, |
| 42 | + 'matches the cron.key attribute in `firebase env:get`'); |
| 43 | + return res.status(403).send('Security key does not match. Make sure your "key" URL query parameter matches the ' + |
| 44 | + 'cron.key environment variable.'); |
| 45 | + } |
| 46 | + |
| 47 | + // We'll fetch all user details. |
| 48 | + getUsers().then(users => { |
| 49 | + // We'll use a pool so that we delete maximum `MAX_CONCURRENT` users in parallel. |
| 50 | + const promisePool = new PromisePool(() => { |
| 51 | + let user; |
| 52 | + // We search for users that have not signed in in the last 30 days. |
| 53 | + while (!user || user.metadata.lastSignedInAt.getTime() > Date.now() - 30 * 24 * 60 * 60 * 1000) { |
| 54 | + if (users.length === 0) { |
| 55 | + return null; |
| 56 | + } |
| 57 | + user = users.pop(); |
| 58 | + } |
| 59 | + |
| 60 | + // If an inactive user is found we delete it. |
| 61 | + return firebaseAdmin.auth().deleteUser(user.uid).then(() => { |
| 62 | + console.log('Deleted user account', user.uid, 'because of inactivity'); |
| 63 | + }).catch(error => { |
| 64 | + console.error('Deletion of inactive user account', user.uid, 'failed:', error); |
| 65 | + }); |
| 66 | + }, MAX_CONCURRENT); |
| 67 | + |
| 68 | + return promisePool.start().then(() => { |
| 69 | + console.log('User cleanup finished'); |
| 70 | + res.send('User cleanup finished'); |
| 71 | + }); |
| 72 | + }); |
| 73 | +}); |
| 74 | + |
| 75 | +/** |
| 76 | + * Returns the list of all users. Including additional metadata such as last sign-in Date. |
| 77 | + */ |
| 78 | +function getUsers() { |
| 79 | + // Create a pool so that there is only `MAX_CONCURRENT` max parallel requests to fetch user details. |
| 80 | + return getUserIds().then(userIds => { |
| 81 | + const users = []; |
| 82 | + |
| 83 | + const promisePool = new PromisePool(() => { |
| 84 | + if (userIds.length === 0) { |
| 85 | + return null; |
| 86 | + } |
| 87 | + const nextUserId = userIds.pop(); |
| 88 | + return firebaseAdmin.auth().getUser(nextUserId).then(user => { |
| 89 | + users.push(user); |
| 90 | + }); |
| 91 | + }, MAX_CONCURRENT); |
| 92 | + |
| 93 | + return promisePool.start().then(() => users); |
| 94 | + }); |
| 95 | +} |
| 96 | + |
| 97 | +/** |
| 98 | + * Returns the list of all user Ids. |
| 99 | + */ |
| 100 | +function getUserIds(userIds = [], nextPageToken, accessToken) { |
| 101 | + return getAccessToken(accessToken).then(accessToken => { |
| 102 | + const options = { |
| 103 | + method: 'POST', |
| 104 | + uri: 'https://www.googleapis.com/identitytoolkit/v3/relyingparty/downloadAccount?fields=users/localId,nextPageToken&access_token=' + accessToken, |
| 105 | + body: { |
| 106 | + nextPageToken: nextPageToken, |
| 107 | + maxResults: 1000 |
| 108 | + }, |
| 109 | + json: true // Automatically stringifies the body to JSON |
| 110 | + }; |
| 111 | + |
| 112 | + return rp(options).then(resp => { |
| 113 | + if (!resp.users) { |
| 114 | + return userIds; |
| 115 | + } |
| 116 | + resp.users.forEach(user => { |
| 117 | + userIds.push(user.localId); |
| 118 | + }); |
| 119 | + if (resp.nextPageToken) { |
| 120 | + return getUserIds(userIds, resp.nextPageToken, accessToken); |
| 121 | + } |
| 122 | + return userIds; |
| 123 | + }); |
| 124 | + }); |
| 125 | +} |
| 126 | + |
| 127 | +/** |
| 128 | + * Returns an access token using the Service accounts credentials. |
| 129 | + */ |
| 130 | +function getAccessToken(accessToken) { |
| 131 | + if (accessToken) { |
| 132 | + return Promise.resolve(accessToken); |
| 133 | + } |
| 134 | + |
| 135 | + const jwtClient = new google.auth.JWT(serviceAccount.client_email, null, |
| 136 | + serviceAccount.private_key, ['https://www.googleapis.com/auth/firebase'], null); |
| 137 | + |
| 138 | + return new Promise((resolve, reject) => { |
| 139 | + jwtClient.authorize((error, token) => { |
| 140 | + if (error) { |
| 141 | + console.error('Error while fetching access token for Service accounts', error); |
| 142 | + return reject(); |
| 143 | + } |
| 144 | + resolve(token.access_token); |
| 145 | + }); |
| 146 | + }); |
| 147 | +} |
0 commit comments