Firebase module requires an older version of node while deploying the functions - javascript

I want to make a cloud function that uses 'firebase' module (not a 'firebase-functions')
And when I'm using or even only import it, npm throws an error:
Error: Error parsing triggers: Failed to load gRPC binary module because it was not installed for the current system
Expected directory: node-v64-darwin-x64-unknown
Found: [node-v79-darwin-x64-unknown]
This problem can often be fixed by running "npm rebuild" on the current system
Original error: Cannot find module '/Users/rame/functions/node_modules/grpc/src/node/extension_binary/node-v64-darwin-x64-unknown/grpc_node.node'
1) If you want to compile the package/file into executable, please pay attention to compilation warnings and specify a literal in 'require' call. 2) If you don't want to compile the package/file into executable and want to 'require' it from filesystem (likely plugin), specify an absolute path in 'require' call using process.cwd() or process.execPath
here's my code on Type script:
import * as functions from 'firebase-functions';
import admin = require('firebase-admin');
//the cause of an error
import * as firebase from 'firebase';
admin.initializeApp()
export const getProfilePicture = functions.https.onRequest((request, response) => {
//also there
const uid = firebase.auth().currentUser?.getIdToken
const promise = admin.storage().bucket().file('usersPfp/' + uid).getSignedUrl({
action: 'read',
expires: '03-09.2441'
})
const p2 = promise.then(GetSignedUrlResponse => {
const data = GetSignedUrlResponse[0]
return response.send({"data": data})
})
p2.catch(error =>{
console.log(error)
return response.status(500).send({"error": error})
})
})
How to fix that?

What you're doing isn't supported. The Firebase Authentication JavaScript client library isn't supported for use in backend environments like Cloud Functions.
The idea of a current user:
firebase.auth().currentUser
only makes sense in the client app where the user is signed in. It's not something that's known on the backend.
What you can do instead is send the user's ID token from your client to your function, the use the Admin SDK to verify it, then perform some actions on the user's behalf.

Related

git clone fails with error: connect ECONNREFUSED 127.0.0.1:80

I'm using isomorphic-git for a project, and when attempting to use git.clone I get the error Error: connect ECONNREFUSED 127.0.0.1:80.
This is a simple reproduction of what I'm trying to do:
import * as git from 'isomorphic-git';
import * as fs from 'fs';
import * as http from 'http';
const git_options = {
fs,
http,
dir: config.git_dir, //yes this is defined
};
const remote_repo = 'dr-vortex/blankstorm';
await git.clone({ ...git_options, url: `https://github.com/${remote_repo}.git` });
I've seen this question using canonical git and checked the config with isomorphic-git and none of the values are set.
After navigating to the repository destination I found a complete git repository without a working tree. Doing a git pull fixes everything.
I also tried setting the ref option on the config (in case it was trying to pull the non-existant master branch, since I use main)
Is there a way to fix the error so that a git pull is not necessary?
Node.js' http isn't a supported HTTP client. You have to use an HTTP client that implements the documented interface: https://isomorphic-git.org/docs/en/http
isomorphic-git provides two HTTP clients. You can use the provided Node.js HTTP client:
import * as git from 'isomorphic-git';
import * as fs from 'fs';
import * as http from 'isomorphic-git/http/node/index.js';
const git_options = {
fs,
http,
dir: config.git_dir, //yes this is defined
};
const remote_repo = 'dr-vortex/blankstorm';
await git.clone({ ...git_options, url: `https://github.com/${remote_repo}.git` });

Package path ./standalone is not exported from package

I'm trying to use the firebase admin SDK, heres my code:
import * as admin from 'firebase-admin';
var firebaseAdminAccount = require("../serviceAccount.json");
var app : admin.app.App = null;
if(!admin.apps.length)
{
app = admin.initializeApp({
credential: admin.credential.cert(firebaseAdminAccount)
})
}
if(app === null)
{
app = admin.apps[0];
}
export default app;
the idea behind this is that whenever used, it will check if the firebase admin SDK is initialized or not, if it's not, then it will initialize it, then export it.
My problem however is when I try to run this, it gives me the following error:
error -
./node_modules/firebase-admin/lib/app/firebase-namespace.js:106:0
Module not found: Package path ./standalone is not exported from
package D:\NewRepos\1d3a\node_modules#firebase\database-compat (see
exports field in
D:\NewRepos\1d3a\node_modules#firebase\database-compat\package.json)
Import trace for requested module:
./node_modules/firebase-admin/lib/default-namespace.js
./node_modules/firebase-admin/lib/index.js ./lib/firebaseAdminSdk.ts
./middleware.ts
https://nextjs.org/docs/messages/module-not-found\
I just installed everything so it should be on the latest version, anyone have an idea why this is happening?
Seems like I didn't realize that Next.js middleware runs on V8, and therefor, firebase-admin cannot run on it. Back to the drawing board.

Node.js use mssql for accessing database

I'm making the Meteor.js app and I have to get data from mssql database. I use Meteor 1.8 and a npm package - mssql(version 5.1.0). That's my code:
const sql = require('mssql')
const config = {something}
export default function fetch(query) {
const config = {something}
sql.connect(config, err => {
if (err) {
console.error(err)
return
}
// create Request object
var request = new sql.Request()
// query to the database and get the records
request.query(query, (err, recordset) => {
if (err) {
console.error(err)
return
}
return recordset
})
})
}
And I have such error
TypeError: sql.connect is not a function
I don't know what's going on, I tried to do it in many ways and I failed. When I use ConnectionPool I see an error saying that ConnectionPool is not a constructor.
What is the proper way to do this?
In my config file I have: user, password, server, database, port.
It appears to be because you're mixing your module systems, you're using require (which is CommonJS-like) but in something that's apparently an ECMAScript module (ESM) (from the export default ...). Node.js itself won't let you do that, but if you're using some kind of bundler or transpiler, perhaps it might...
Changing your require to:
import sql from "mssql";
...and making sure Node.js is using ESM¹, I don't get any error with sql.connect not being a function.
¹ In my case, since I'm using Node.js v12, I do that by having "type": "module" in my package.json and running it via node --experimental-modules filename.js, more here.

How do I authenticate a Vue.js progressive web app with the Microsoft Graph

I have a Vue.js app. This app is a progressive web app, so it's intended to primarily run on the client-side. However, during the initial start-up, I need to authenticate the user in my Azure Active Directory, get data associated with their account, and store it for offline use.
I have a server-side API in place already for retrieving the data associated with a user account. I also know how to store it for offline use. However, my question is: how do I authenticate with the Microsoft Graph from my Vue.js app? Everything I see relies on using Node.js middleware, but unless I'm misunderstanding something, my progressive web app isn't a Node.js app. It's just straight up JavaScript, HTML, and CSS.
If the user closes the app, then revisits it in a couple of days, I believe I would need to use the refresh token to get a new access token. Still, once again, everything I see relies on Node.js middleware. I believe I need a solution that works purely in Vue.js / JavaScript. Am I mistaken?
Updates
1) Installed the Microsoft Graph Client via NPM (npm install #microsoft/microsoft-graph-client --save). This installed v1.7.0.
2) In my Vue.js app, I have:
import * as MicrosoftGraph from '#microsoft/microsoft-graph-client';
import * as Msal from 'msal';
let clientId = '<some guid>';
let scopes = ['user.read'];
let redirectUrl = 'http://localhost:1234/'; // This is registered in Azure AD.
let cb = (message, token, error, tokenType) => {
if (error) {
console.error(error);
} else {
console.log(token);
console.log(tokenType);
}
}
let reg = new Msal.UserAgentApplication(clientId, undefined, cb, { redirectUrl });
let authProvider = new MicrosoftGraph.MSALAuthenticationProvider(reg, scopes);
The last line generates an error that says: export 'MSALAuthenticationProvider' (imported as 'MicrosoftGraph') was not found in '#microsoft/microsoft-graph-client'
The last line generates an error that says: export 'MSALAuthenticationProvider' (imported as 'MicrosoftGraph') was not found in '#microsoft/microsoft-graph-client'
This error occurs because the main script (lib/src/index.js) of #microsoft/microsoft-graph-client does not export that symbol. You'll notice that logging MicrosoftGraph.MSALAuthenticationProvider yields undefined. Actually, the main script is intended to be run in Node middleware.
However, #microsoft/microsoft-graph-client provides browser scripts that do make MSALAuthenticationProvider available:
lib/graph-js-sdk-web.js
browserified bundle (not tree-shakable)
sets window.MicrosoftGraph, which contains MSALAuthenticationProvider
does not export any symbols itself
import '#microsoft/microsoft-graph-client/lib/graph-js-sdk-web'
let authProvider = new window.MicrosoftGraph.MSALAuthenticationProvider(/* ... */)
demo 1
lib/es/browser/index.js
ES Modules (tree-shakable)
exports MSALAuthenticationProvider
import { MSALAuthenticationProvider } from '#microsoft/microsoft-graph-client/lib/es/browser'
let authProvider = new MSALAuthenticationProvider(/* ... */)
demo 2
lib/src/browser/index.js
CommonJS module (not tree-shakable)
exports MSALAuthenticationProvider
import { MSALAuthenticationProvider } from '#microsoft/microsoft-graph-client/lib/src/browser'
let authProvider = new MSALAuthenticationProvider(/* ... */)
demo 3

Cloud Functions - Cloud Firestore error: can't get serverTimestamp

Cloud Functions - Cloud Firestore error: can't get serverTimestamp
const admin = require('firebase-admin');
exports.userlog = functions.firestore
.document('user/{userId}')
.onUpdate((change, context) =>
{
const db = admin.firestore();
//var timestamp = db.FieldValue.serverTimestamp();
var timestamp = db.ServerValue.TIMESTAMP;
...
return db.collection('userlog').add(
{
userId : previousValue.userId,
...
timestamp: timestamp
}).then(ref =>
{
return console.log('Added document with ID: ', ref.id);
});
});
I got two errors separately:
TypeError: Cannot read property 'serverTimestamp' of undefined
TypeError: Cannot read property 'TIMESTAMP' of undefined
The correct syntax is:
firebase.firestore.FieldValue.serverTimestamp()
Note the lack of parenthesis (()) after firestore: this is a static variable, not an instance variable/member field.
// Imports: Dependencies
const admin = require('firebase-admin');
// Correct Syntax (If You Don't Want To Import Firestore)
created_at: admin.firestore.FieldValue.serverTimestamp(),
since #FrankvanPuffelen's edit queue is full with missing imports, documentation, etc I'll post an update on his solution
include from (web version 8):
const firebase = require('firebase-admin');
or use more recent (web version 9):
import {FieldValue} from "firebase/firestore";
The correct syntax is:
firebase.firestore.FieldValue.serverTimestamp()
Note the lack of parenthesis (()) after firestore: this is a static variable, not an instance variable/member field.
See Firebase example for more info
I was using the correct syntax as per the upvoted answer(s), but still go this error. It turns out it had something to do with my version of the firebase CLI being off-sync with versions of the firebase-admin package (I'm not sure how it happened in the first place, but I noticed form my source tracking tool that the package.json and lock files had been updated).
Solved the problem by deleting all changes I had made on my package.json & lock files and re-installed the CLI:
npm i -g firebase-tools

Categories

Resources