I am building an app that calls Twitter API from Cloud Functions. The user's access token is stored in Firebase RTDB.
The problem is that when I don't call Firebase's Auth sign in method, the database returns a null snapshot.
When I do call Firebase's Auth sign in (code below), it works as normal
const functions = require("firebase-functions");
const Twitter = require('twitter');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true });
admin.initializeApp();
exports.tweet = functions.https.onRequest(async (req, res) => {
console.log('devs do something', req.body)
cors(req, res, () => {
if (req.body.uid) {
var uid = req.body.uid
var promise = admin.database().ref(`auth/`).child(uid).once('value');
return promise.then(snapshot => {
var event = snapshot.val()
const client = new Twitter({
access_token_key: event.accessToken,
access_token_secret: event.secret,
consumer_key: "HUYEtFs1NJVGlFqBDq7GJ6HF2",//functions.config().twitter.key,
consumer_secret: "ChcSAVwBbd4wLXBSZlIu6nUi6mjsk4b6HqoivuhziP3zAkgGni"//functions.config().twitter.secret
//consumer_token_secret: "ChcSAVwBbd4wLXBSZlIu6nUi6mjsk4b6HqoivuhziP3zAkgGni"//functions.config().twitter.secret
});
var params = {
"tweet_mode": "extended"
}
client.get('statuses/home_timeline', params, function(error, tweets, response) {
if (error) throw error;
res.send(tweets)
});
})
} else {
console.log("No UID provided")
}
})
})
This code only works when the below function is called first. If it is not called, then admin.database().ref('auth/${uid}') returns a null snapshot.
The below code redirects user to sign in with Twitter Popup, which is inconvenient every single time.
async login(context) {
console.log("auth.login()");
return await auth
.signInWithPopup(provider)
.then(async (result) => {
// This gives you a the Twitter OAuth 1.0 Access Token and Secret.
// You can use these server side with your app's credentials to access the Twitter API.
var credential = result.credential;
var accessToken = credential.accessToken;
var secret = credential.secret;
// The signed-in user info.
var user = result.user;
db.ref(`auth/${user.uid}/`).update({ accessToken, secret })
return user
// ...
})
Is there a connection between Firebase Auth and Firebase Admin that I am unaware of?