I have a really weird problem with Firebase functions. It seems to only occur on mobile and only happens right after the user first logs in (if I reload the page after the initial sign-in, things work fine.
Code:
const functions = require("firebase-functions");
const cors = require("cors")({
origin: true
});
const admin = require("firebase-admin");
admin.initializeApp();
var db = admin.firestore();
exports.account = functions.https.onRequest((req, res) => {
return cors(req, res, () => {
admin.auth().verifyIdToken(req.query.token).then(function(decoded) {
var uid = decoded.uid;
db.collection("users").where("uid", "==", uid).get().then(function(data) {
if (data.size == 0) {
admin.auth().getUser(uid).then(function(user) {
if (!user.email.endsWith("@domain.com")) {
admin.auth().deleteUser(user.uid);
res.status(401).send("Please use a valid account to continue");
} else {
db.collection("users").doc(user.email).set({name: user.displayName, email: user.email, uid: user.uid, starred: []}).then(function() {
res.status(200).end();
}).catch(function(error) {
admin.auth().deleteUser(user.uid);
res.status(500).send("An error occurred while creating new account: " + error.message);
});
}
}).catch(function(error) {
res.status(500).send("An error occurred while creating new user: " + error.message);
});
} else {
data.forEach(function(doc) {
var user = doc.data();
res.status(200).json(user);
}).catch(function(error) {
res.status(500).send("An error occurred while retrieving user data: " + error.message);
});
}
}).catch(function(error) {
res.status(500).send("An error occurred while fetching user data: " + error.message);
});
});
});
});
The HTTP trigger function is meant to return user data from a Firestore database. However it also checks to see if the user is signed in with an email that doesn't match a specified domain, and if so the user account is deleted.
At first I thought this was a CORS error because I was getting access control errors in the console. However I'm quite certain I've got CORS right which leads me to believe that there may be an error with the actual function. I am getting unhandled rejection errors in the log as well, but I don't know what I'm doing wrong (since it's an HTTP function I just need to res.send or res.end every time, which I'm doing).
UPDATE: The issue had nothing to do with CORS... it was the .catch attached to the .forEach (which isn't a promise). That was causing the request to return an error, which didn't include the CORS headers and therefore triggered the access control error.