Reputation: 19592
I'm using Algolia to run my search requests on my Firebase Database. I have Algolia hosted on a Heroku server with a Node.js file. Algolia connects to Firebase via that Node.js app.js file.
For Firebase to authenticate Algolia I need a token which I generate after the user signs in and is authenticated on the client.
The Firebase docs says to send the token to my backend via Https-
Firebase: Get Tokens and Send to Https
I found a similar question asked on Stackoverflow but it doesn't give any code on how to do it. I'm not a Node.js dev and only lightly delved into it so I need more context
How to send Firebase token to backend?
In the function I created below func sendTokenToHerokuAppJsFile()
I can send the token after it’s created. I can then use a url (it’s the second line inside the function) to send the token to but I don’t know where to get the url from.
How do I get the URL to send the token to my Heroku app.js file?
Update: @Freya in the comments very helpfully suggested I create an api on the Node side but I’m not a Node dev
How do I create a API in Node.js to receive the token?
iOS Client Swift File:
@IBAction fileprivate func signinButtonTapped(_ sender: UIButton) {
Auth.auth().signIn(withEmail: emailTextField.text!, password: passwordTextField.text!, completion: {
(user, error) in
if error != nil {
return
}
guard let currentUser = user else {
return
}
currentUser?.getIDTokenForcingRefresh(true, completion: {
(idToken, error) in
if error != nil{
return
}
// Send token to your backend via HTTPS
self.sendTokenToHerokuAppJsFile(idToken)
})
}
}
fileprivate func sendTokenToHerokuAppJsFile(_ idToken: String){
let json: [String:Any] = ["token" : idToken]
// HOW DO I GET THIS URL??
let url = URL(string: "https://www.linkToMyHerokuAppJsFile")
var request = URLRequest(url: url!)
request.httpMethod = "POST"
do {
request.httpBody = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
}catch let error as NSError{
print(error.localizedDescription)
return
}
let task = URLSession.shared.dataTask(with: request) {
(data, response, error) in
guard let data = data, error == nil else{
//do something
return
}
do{
let result = try JSONSerialization.jsonObject(with: data, options: []) as? [String:Any]
print(result as Any)
}catch let error{
print(error.localizedDescription)
}
}
task.resume()
}
Heroku App.Js Server file:
var idToken;
//Firebase-Admin Initialization
var admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.cert({
projectId: "********",
clientEmail: "********",
privateKey: "-----BEGIN PRIVATE KEY-----\n********\n-----END PRIVATE KEY-----\n"
}),
databaseURL: "https://********.firebaseio.com/"
});
//Firebase Initialization
var firebase = require('firebase');
var config = {
apiKey: "********",
authDomain: "********.firebaseapp.com",
databaseURL: "https://********.firebaseio.com/",
storageBucket: "********.appspot.com",
messagingSenderId: "********"
};
firebase.initializeApp(config);
admin.auth().verifyIdToken(idToken)
.then(function(decodedToken) {
var uid = decodedToken.uid;
firebase.auth().authenticateWithCustomToken(uid)
}).catch(function(error) {
// Handle error
});
//Algolia Initialization
var algoliasearch = require('algoliasearch');
var algolia = algoliasearch('********', '********');
Upvotes: 0
Views: 932
Reputation: 2685
I cannot test the whole node js code, but here is a start:
First install express and save it in the list of modules in package.json:
npm install express --save
var express = require('express'); //include express
var app = express(); //create your app
var idToken;
//Firebase-Admin Initialization
var admin = require("firebase-admin");
admin.initializeApp({
credential: admin.credential.cert({
projectId: "********",
clientEmail: "********",
privateKey: "-----BEGIN PRIVATE KEY-----\n********\n-----END PRIVATE KEY-----\n"
}),
databaseURL: "https://********.firebaseio.com/"
});
//Firebase Initialization
var firebase = require('firebase');
var config = {
apiKey: "********",
authDomain: "********.firebaseapp.com",
databaseURL: "https://********.firebaseio.com/",
storageBucket: "********.appspot.com",
messagingSenderId: "********"
};
firebase.initializeApp(config);
//here you expose the logic of token verification. From my experience, do not include the initialization (former line), or it will initialize firebase app every time you make the request
app.post('/verify_token', function (req, res) {
var idtoken = req.body.firebase_token;
admin.auth().verifyIdToken(idToken)
.then(function(decodedToken) {
var uid = decodedToken.uid;
firebase.auth().authenticateWithCustomToken(uid)
}).catch(function(error) {
// Handle error
});
})
//Algolia Initialization
var algoliasearch = require('algoliasearch');
var algolia = algoliasearch('********', '********');
Let's assume that the node server's url is http://mynodeserver.com. You can access this API as http://mynodeserver.com/verify_token, using post as a http method, sending firebase_token as a body param. I don't understand enough swift as to make a working code, and there are certainly variations to do this, but the essence is pretty much the same.
Based on this link: https://www.tutorialspoint.com/nodejs/nodejs_express_framework.htm
Upvotes: 1