-
Notifications
You must be signed in to change notification settings - Fork 3.8k
[WIP] add manage FCM tokens sample #958
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kroikie
wants to merge
2
commits into
main
Choose a base branch
from
fcm-manage-tokens
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
# Manage FCM registration tokens | ||
|
||
This sample demonstrates how FCM registration tokens should be | ||
managed on the server side. | ||
|
||
1. Clients should regularly send valid tokens to the server and | ||
the server updates their corresponding timestamp. | ||
2. The server should periodically prune stale tokens. Unsubscribing | ||
from topics then deleting them. | ||
|
||
|
||
## Functions Code | ||
|
||
See file [functions/index.js](functions/index.js) for the code. | ||
|
||
Storing and pruning the tokens is done using the [Firebase Admin SDK](https://www.npmjs.com/package/firebase-admin). | ||
|
||
The dependencies are listed in [functions/package.json](functions/package.json). | ||
|
||
|
||
## Trigger rules | ||
|
||
- updateToken is triggered... | ||
- pruneTokens is triggered... | ||
|
||
|
||
|
||
## Setup and test this sample section | ||
|
||
To deploy and test the sample: | ||
|
||
- TODO(kroikie): describe usage of sample | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
{} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
{ | ||
"parserOptions": { | ||
// Required for certain syntax usages | ||
"ecmaVersion": 2017 | ||
}, | ||
"plugins": [ | ||
"promise" | ||
], | ||
"extends": "eslint:recommended", | ||
"rules": { | ||
// Removed rule "disallow the use of console" from recommended eslint rules | ||
"no-console": "off", | ||
|
||
// Removed rule "disallow multiple spaces in regular expressions" from recommended eslint rules | ||
"no-regex-spaces": "off", | ||
|
||
// Removed rule "disallow the use of debugger" from recommended eslint rules | ||
"no-debugger": "off", | ||
|
||
// Removed rule "disallow unused variables" from recommended eslint rules | ||
"no-unused-vars": "off", | ||
|
||
// Removed rule "disallow mixed spaces and tabs for indentation" from recommended eslint rules | ||
"no-mixed-spaces-and-tabs": "off", | ||
|
||
// Removed rule "disallow the use of undeclared variables unless mentioned in /*global */ comments" from recommended eslint rules | ||
"no-undef": "off", | ||
|
||
// Warn against template literal placeholder syntax in regular strings | ||
"no-template-curly-in-string": 1, | ||
|
||
// Warn if return statements do not either always or never specify values | ||
"consistent-return": 1, | ||
|
||
// Warn if no return statements in callbacks of array methods | ||
"array-callback-return": 1, | ||
|
||
// Requre the use of === and !== | ||
"eqeqeq": 2, | ||
|
||
// Disallow the use of alert, confirm, and prompt | ||
"no-alert": 2, | ||
|
||
// Disallow the use of arguments.caller or arguments.callee | ||
"no-caller": 2, | ||
|
||
// Disallow null comparisons without type-checking operators | ||
"no-eq-null": 2, | ||
|
||
// Disallow the use of eval() | ||
"no-eval": 2, | ||
|
||
// Warn against extending native types | ||
"no-extend-native": 1, | ||
|
||
// Warn against unnecessary calls to .bind() | ||
"no-extra-bind": 1, | ||
|
||
// Warn against unnecessary labels | ||
"no-extra-label": 1, | ||
|
||
// Disallow leading or trailing decimal points in numeric literals | ||
"no-floating-decimal": 2, | ||
|
||
// Warn against shorthand type conversions | ||
"no-implicit-coercion": 1, | ||
|
||
// Warn against function declarations and expressions inside loop statements | ||
"no-loop-func": 1, | ||
|
||
// Disallow new operators with the Function object | ||
"no-new-func": 2, | ||
|
||
// Warn against new operators with the String, Number, and Boolean objects | ||
"no-new-wrappers": 1, | ||
|
||
// Disallow throwing literals as exceptions | ||
"no-throw-literal": 2, | ||
|
||
// Require using Error objects as Promise rejection reasons | ||
"prefer-promise-reject-errors": 2, | ||
|
||
// Enforce “for” loop update clause moving the counter in the right direction | ||
"for-direction": 2, | ||
|
||
// Enforce return statements in getters | ||
"getter-return": 2, | ||
|
||
// Disallow await inside of loops | ||
"no-await-in-loop": 2, | ||
|
||
// Disallow comparing against -0 | ||
"no-compare-neg-zero": 2, | ||
|
||
// Warn against catch clause parameters from shadowing variables in the outer scope | ||
"no-catch-shadow": 1, | ||
|
||
// Disallow identifiers from shadowing restricted names | ||
"no-shadow-restricted-names": 2, | ||
|
||
// Enforce return statements in callbacks of array methods | ||
"callback-return": 2, | ||
|
||
// Require error handling in callbacks | ||
"handle-callback-err": 2, | ||
|
||
// Warn against string concatenation with __dirname and __filename | ||
"no-path-concat": 1, | ||
|
||
// Prefer using arrow functions for callbacks | ||
"prefer-arrow-callback": 1, | ||
|
||
// Return inside each then() to create readable and reusable Promise chains. | ||
"promise/always-return": 2, | ||
|
||
//Enforces the use of catch() on un-returned promises | ||
"promise/catch-or-return": 2, | ||
|
||
// Warn against nested then() or catch() statements | ||
"promise/no-nesting": 1 | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,61 @@ | ||
/** | ||
* Copyright 2022 Google Inc. All Rights Reserved. | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
'use strict'; | ||
|
||
const admin = require('firebase-admin'); | ||
const functions = require('firebase-functions'); | ||
const {write} = require("firebase-functions/logger"); | ||
admin.initializeApp(); | ||
|
||
const EXPIRATION_TIME = 1000 * 60 * 60 * 24 * 30; // 30 days | ||
|
||
/** | ||
* Callable function that stores/updates the freshness timestamp associated with the | ||
* submitted FCM registration token. | ||
* | ||
* Note: Most FCM registration tokens would be associated with a user. In that case | ||
* there should be some mapping between the user and the token(s) when stored. | ||
*/ | ||
exports.updateToken = functions.https.onCall(async (data, context) => { | ||
const registrationToken = data['fcm_token']; | ||
await admin.firestore().collection('tokens').doc(registrationToken).set( | ||
{timestamp: Date.now()}, | ||
{merge: true} | ||
); | ||
}); | ||
|
||
/** | ||
* Scheduled function that runs once a day. It retrieves all stale tokens then | ||
* unsubscribes them from 'topic1' then deletes them. | ||
* | ||
* Note: topic1 is an example topic here. It is up to the developer to unsubscribe | ||
* all topics the token is subscribed to. | ||
*/ | ||
exports.pruneTokens = functions.pubsub.schedule('every 24 hours').onRun(async (context) => { | ||
const staleTokensResult = await admin.firestore().collection('tokens') | ||
.where("timestamp", "<", Date.now() - EXPIRATION_TIME) | ||
.get(); | ||
|
||
const staleTokens = staleTokensResult.docs.map(staleTokenDoc => staleTokenDoc.id); | ||
|
||
await admin.messaging().unsubscribeFromTopic(staleTokens, 'topic1'); | ||
|
||
const deletePromises = []; | ||
for (const staleTokenDoc of staleTokensResult.docs) { | ||
deletePromises.push(staleTokenDoc.ref.delete()); | ||
} | ||
await Promise.all(deletePromises); | ||
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
{ | ||
"name": "developer-motivator-functions", | ||
"description": "A simple developer motivator using Cloud Function and firebase analytics", | ||
"dependencies": { | ||
"firebase-admin": "^10.0.0", | ||
"firebase-functions": "^3.16.0" | ||
}, | ||
"devDependencies": { | ||
"eslint": "^6.8.0", | ||
"eslint-plugin-promise": "^4.2.1" | ||
}, | ||
"scripts": { | ||
"lint": "./node_modules/.bin/eslint --max-warnings=0 .", | ||
"serve": "firebase emulators:start --only functions", | ||
"shell": "firebase functions:shell", | ||
"start": "npm run shell", | ||
"deploy": "firebase deploy --only functions", | ||
"logs": "firebase functions:log", | ||
"compile": "cp ../../tsconfig.template.json ./tsconfig-compile.json && tsc --project tsconfig-compile.json" | ||
}, | ||
"engines": { | ||
"node": "14" | ||
}, | ||
"private": true | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@kroikie what do you think about making this a Firestore trigger instead of a callable? Reasoning is that then the writes to Firestore can be protected by Security Rules