Firebase Cloud Function to copy user email to database collection - firebase

I would like to copy the email associated to each user to a Firestore collection ('users') using Cloud Functions. Each document in the collection has the UID of the user as its name.. I have the following function:
const getAllUsers = (req, res) => {
auth.listUsers().then((userRecords) => {
userRecords.users.forEach(
(user) => db.collection('users').doc(user.uid).update({ "email": user.email })
)
res.end('Retrieved users list successfully.');
}).catch((error) => console.log(error));
};
module.exports = {
api: functions.https.onRequest(getAllUsers),
};
I am getting the following error for invalid data:
FirebaseError: Function DocumentReference.update() called with invalid data. Unsupported field value: undefined (found in field email)
Any ideas?

Got this to work by converting the data to JSON beforehand, here is the working function:
const getAllUsers = (req, res) => {
auth.listUsers().then((userRecords) => {
userRecords.users.forEach(
(user) =>
function() {
let thisUser = user.toJSON();
db.collection('users').doc(thisUser.uid).update({ "email": thisUser.email })
}
)
res.end('Retrieved users list successfully.');
}).catch((error) => console.log(error));
};
module.exports = {
api: functions.https.onRequest(getAllUsers),
};

Related

Firestore - How to store current user data and keep previews one?

I'm trying to store user data on Firestore which is I have multiple things to add such as (taskIndex,levelName,step,steps) and I did it successfully also I'm getting that user info after refresh or killing the app, but the problem here is that on my App I have multiple indexes and Levels and each of them has their special steper, once I add current user data previews one gets deleted, so how can I fix this?
This is what i did for storing the data
//Set userInfo
useEffect(() => {
const setUser = async () => {
await setDoc(doc(db, 'user', uid), {
uid: uid,
step: step,
steps: steps,
taskIndex: taskIndex,
levelName: levelName,
});
};
And getting data
// Get userInfo
const userRef = collection(db, 'user');
useEffect(() => {
const getUserInfo = async () => {
const data = await getDocs(userRef);
setUserData(data.docs.map((doc) => ({ ...doc.data(), id: doc.id })));
};
getUserInfo();
}, []);
useEffect(() => {
const userInfo =
userData &&
userData.map((items) => {
setStep(items.step);
setSteps(items.steps);
setTaskIndex(items.taskIndex);
setLevelName(items.levelName);
});
}, [userData]);

Send auth context to firebase callable function in unittest

I have been working on a firebase project in which I created a cloud function that creates documents in firestore. This is the function -
export const createExpenseCategory = functions
.region("europe-west1")
.https.onCall(async (data, context) => { // data is a string
if (!context.auth?.uid) { // check that requesting user is authenticated
throw new functions.https.HttpsError(
"unauthenticated",
"Not Authenticated"
);
}
const res = await admin
.firestore()
.collection("/categories/")
.where("uid", "==", context.auth.uid)
.get();
const categoryExists = res.docs.find((doc) => doc.data().name === data); // check that there are not duplicates.
// doc looks like this -
// {
// "name": "Food",
// "uid": "some_long_uid"
// }
if (categoryExists) {
throw new functions.https.HttpsError(
"already-exists",
`Category ${data} already exists`
);
}
return admin
.firestore()
.collection("/categories/")
.add({ name: data, uid: context.auth.uid });
});
As you can see, at the beginning of the function I check whether the user that sent the request is authenticated with the context parameter. Everything works fine when I play around with it in my web app, but I have been trying to figure out a way to create a unittest for this function. My problem is that I can't really figure out how to create an authenticated request to make sure that my function doesn't fail every time. I tried to look online for any documentation but couldn't seem to find any.
Thanks in advance!
You can unit test your functions using the firebase-functions-test SDK. The guide mentions you can mock the data within the eventContext or context parameter passed to your function. This works for mocking the uid field of the auth object:
// Left out authType as it's only for RTDB
wrapped(data, {
auth: {
uid: 'jckS2Q0'
}
});
The guide uses mocha for testing, but you can use other testing frameworks. I made a simple test to see if it would work and I could send the mock uid to the function, which worked as expected:
index.js
exports.authTest = functions.https.onCall( async (data, context) => {
if(!context.auth.uid){
throw new functions.https.HttpsError('unauthenticated', 'Missing Authentication');
}
const q = await admin.firestore().collection('users').where('uid', '==', context.auth.uid).get();
const userDoc = q.docs.find(doc => doc.data().uid == context.auth.uid);
return admin.firestore().collection('users').doc(userDoc.id).update({name: data.name});
});
index.test.js
const test = require('firebase-functions-test')({
projectId: PROJECT_ID
}, SERVICE_ACCTKEY); //Path to service account file
const admin = require('firebase-admin');
describe('Cloud Functions Test', () => {
let myFunction;
before(() => {
myFunction = require('../index.js');
});
describe('AuthTest', () => {
it('Should update user name in UID document', () => {
const wrapped = test.wrap(myFunction.authTest);
const data = {
name: 'FooBar'
}
const context = {
auth: {
uid: "jckS2Q0" //Mocked uid value
}
}
return wrapped(data, context).then(async () => {
//Asserts that the document is updated with expected value, fetches it after update
const q = await admin.firestore().collection('users').where('uid', '==', context.auth.uid).get();
const userDoc = q.docs.find(doc => doc.data().uid == context.auth.uid);
assert.equal(userDoc.data().name, 'FooBar');
});
});
});
});
Let me know if this was useful.

Why is firebase cloud function invoked in react-native not logging output?

I have a firebase cloud function:
exports.copyImage = functions.region('us-central1').https.onCall(async (data, context) => {
const { auth } = context || {}
const { uid } = auth || {}
if (!uid) throw 'Unauthenticated'
const srcBucketName = <bucket-name>'
const destinationBucketName = '<bucket-name'
const { imageFile, archiveId, sessionId } = data
const srcFileName = `message-attachments/${imageFile}`
const destinationFileName = `archived-attachments/${uid}/${imageFile}`
console.log(`source path: ${srcFileName}\ndestination path: ${destinationFileName}`)
const storage = new Storage()
storage
.bucket(srcBucketName)
.file(srcFileName)
.copy(storage.bucket(destinationBucketName).file(destinationFileName))
.then(() => {
console.log(`COPY SUCCESS: gs://${destinationBucketName}/${destinationFileName}`)
})
.catch(err => console.error('COPY ERROR: ' + err))
})
and I have a react-native project (v61.5) using react-native-firebase (v5) which calls this function:
firebase.functions().httpsCallable('copyFile')({
imageFile: fileName,
archiveId: uid,
sessionId
})
.then(() => {
// copied file
const ref = firebase.storage()
.ref('archived-attachments')
.child(uid)
.child(fileName)
ref.getDownloadURL()
.then(url => {
// do more
})
.catch(err => alert(err.message))
})
.catch(err => {
// copy error
})
the problem is im not getting any log output in the functions console when executing this function. the functions been successfully deployed as well. Any advice?
Updating my comment in this answer as it solves the issue.
The issue occurred because Jim has been triggering a different function copyFile
instead of copyImage.
mismatch between the function name exports.copyImage vs httpsCallable('copyFile').
Updating the function name solved the issue!

Can't access data base from a Firebase function

I tried everything , I have this cloud function (that otherwise works) :
exports.contentServer = functions.https.onRequest((request, response) => {
admin.database().ref('/list/' + "abc").once('value').then(function(snapshot) {
console.log(snapshot.val() );
return null;
}).catch(function(error) {
console.log("Error getting document:", error);
return response.send(error);
});
});
or also this :
admin.database().ref('/list').once('value').then(function(snapshot) {
var event = snapshot.val();
app.tell('Result: '+event);
});
and this :
exports.contentServer = functions.https.onRequest((request, response) => {
var db = admin.database();
db.ref("list/abc").once("value").then(snap => {
var store = snap.val().description;
return store;
}).then(() => {
var store = snap.val().description;
return store;
}).then(snap => {
var store = snap.val().description;
return store;
}).catch(err => {
console.log(err);
response.send("error occurred");
});
});
and always get back the error :
"Could not handle the request"
Or I get error on deploy that :
Each then() should return a value or throw
I have a collection called list, inside I have a document named "abc".
Is there something I have to include ? something I have to setup in Firebase to make it work ? anything basic nobody write on the docs ?
Modified following the comments above explaining the OP uses Firestore and not the Realtime Database
You should do as follows. You have to wait that the promise returned by the get() method resolves before sending back the response. For this you need to use the then() method, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
exports.contentServer = functions.https.onRequest((request, response) => {
admin.firestore().collection('list').doc('abc').get()
.then(docSnapshot => {
console.log(docSnapshot.data());
return response.send(docSnapshot.data()); // or any other value, like return response.send( {result: "success"} );
})
.catch(error => {
console.log("Error getting document:", error);
return response.status(500).send(error);
});
});
As written in the comments above, I would suggest that you watch the 3 videos about "JavaScript Promises" from the Firebase video series: https://firebase.google.com/docs/functions/video-series/
Try this
Updated. Return the response inside then() as what #Renaud Tarnec pointed out.
Using realtime database
exports.contentServer = functions.https.onRequest((request, response) => {
var database = admin.database();
database.ref('list').child('abc').once("value", snapshot => {
const data = snapshot.val();
return response.send(data);
}).catch(error => {
return response.status(500).send(error);
});
});
If you are using firestore.
exports.contentServer = functions.https.onRequest((request, response) => {
const firestore = admin.firestore();
firestore.collection("list").doc('abc').get().then(doc => {
console.log(doc.data());
return response.send(doc.data());
}).catch(error => {
return response.status(500).send(error);
});
});
Important: Don't forget to terminate the request by calling response.redirect(), response.send(), or responses.end() so you can avoid excessive charges from functions that run for too long

What is the suitable query for the following case?

This is my database structure:
I am trying to list all users with "locale" equal to "Cairo, Egypt" so I made the following query:
exports.calculateMatches = functions.https.onRequest((request, response) => {
// Access users' profiles that are located in the locale of the requesting user
databaseRef.child("users").orderByChild("locale").equalTo(request.query.locale).once("value")
.then(snap => {
snap.forEach(profile => {
console.log(profile);
});
});
});
Note this function is deployed to firebase cloud functions and this is what I get in the logs:
HTTPS type functions require that you send a response to the client in order to terminate the function. Without that, they will always time out, and the client will be waiting the whole time.
For example:
const databaseRef = admin.database().ref('')
exports.calculateMatches = functions.https.onRequest((request, response) => {
databaseRef.child("users").orderByChild("locale").equalTo(request.query.locale).once("value")
.then(snap => {
const profiles = []
snap.forEach(profile => {
profiles.push(profile.val())
});
response.send(profiles)
})
.catch(error => {
response.status(500).send(error)
});
});

Resources