I am writing an app in Flutter with a Firebase Backend. My App needs to check if a user turnt 18, and if they did it should make their attribute "hasAgreedToTerms" to false because I want them to re-agree to the Terms and Conditions after they turn 18. I have looked around online and asked ChatGPT and it seems like I need to add a Cloud Function to Firebase that checks their age. I have tried implementing a function but I do not have any experience with JS, therefore I have trouble writing the function. Additionally, when I try to deploy my function, an error occurs.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.checkUserAgeAndUpdateTerms = functions.firestore
.document("users/{userId}")
.onUpdate(async (change, context) => {
const userId = context.params.userId;
const newData = change.after.data(); // Get the updated data
// Check if the birthdate exists
if (!newData.birthdate) {
console.log("No birthdate found for user:", userId);
return null;
}
const birthdate = new Date(newData.birthdate);
const age = calculateAge(birthdate);
// Check if the user is 18 or older
if (age >= 18) {
// Update the 'hasAgreedToTerms' field to false
await admin.firestore().collection("users").doc(userId).update({
hasAgreedToTerms: false,
});
console.log("User ${userId} turnt 18. Updated hAtT to false.");
}
return null;
});
/**
* Function
* @param {Date} birthdate
* @return {boolean} Description of the return value
*/
function calculateAge(birthdate) {
const today = new Date();
let age = today.getFullYear() - birthdate.getFullYear();
const monthDiff = today.getMonth() - birthdate.getMonth();
if (monthDiff < 0 || (monthDiff === 0 &&
today.getDate() < birthdate.getDate())) {
age--;
}
return age;
}
I tried updating my firebase-functions version and using 2nd gen cloud functions, but I have no experience and could not write something working.picture of the error
2
Answers
First, take a look at scheduled functions so you can set this up running daily.
https://firebase.google.com/docs/functions/schedule-functions?gen=2nd
Second, it seems like you only have one logical gate. Every day you run the scheduled function – you will be resetting everyone over 18 back to false, meaning they will have to agree to the terms over and over again. Add another boolean
hasAgreedToTerms18
if you want to keep things simple.Third, you did not post your error so we cannot help you with it.
I would recommend to reconsider your approach. Instead of running functions on server side, just store date of birth on firestore. Make
hasAgreedToTerms
false by default. Everytime the user opens the app, check if it has turned 18 and alterhasAgreedToTerms
accordingly.Server side solution is cost intensive and will add unnecessary overhead on your firebase.