I am trying to add a Firebase function that verify the id token given by a http request to verify user before letting him access my distant database.
I tried something using documentation in Node.js
Here is my code :
const { initializeApp } = require('firebase-admin/app');
var admin = require("firebase-admin");
var serviceAccount = require("path/to/serviceAccountCred.json");
const app = initializeApp({
credential: admin.credential.cert(serviceAccount)
});
exports.verifyToken = onRequest((req, res) => {
const { uid, token } = req.query;
if (!uid || !token) {
res.status(400).send('Paramètres manquants : uid et token sont requis.');
return;
}
app.Auth().verifyIdToken(token).then((decodedToken) => {
if (decodedToken.uid === uid) {
res.status(200).send('Token valide.');
} else {
res.status(401).send('Token invalide.');
}
}).catch((error) => {
res.status(500).send(error.message);
});
});
But, using this code, I keep getting this error :
Internal Server Error : 500
Here is my Flutter request code :
Future<void> validateTokenDB() async {
String token="";
try {
token = await getIdToken() ?? "";
} catch (e) {
// Handle error
print('Error getting token: $e');
}
String uid = firebaseAuth.currentUser!.uid;
// Creating the query parameters
Map<String, String> queryParams = {
'uid': uid,
'token': token,
};
// Constructing the URL with query parameters
Uri url = Uri(
scheme: 'https',
host: 'link-to-the-function-url.a.run.app',
queryParameters: queryParams,
);
try {
// Sending the HTTP request
http.Response response = await http.get(url);
// Handling the response
if (response.statusCode == 200) {
// Request was successful
print(response.body);
print('Token updated successfully');
return;
} else {
// Request failed
print('${response.body} : ${response.statusCode}');
Auth().signOut();
}
} catch (e) {
// Error occurred during HTTP request
print('Error during HTTP request: $e');
Auth().signOut();
}
Auth().signOut();
}
Hope you can help me resolve this error.