firebase / firebase-admin-node Goto Github PK
View Code? Open in Web Editor NEWFirebase Admin Node.js SDK
Home Page: https://firebase.google.com/docs/admin/setup
License: Apache License 2.0
Firebase Admin Node.js SDK
Home Page: https://firebase.google.com/docs/admin/setup
License: Apache License 2.0
Is there deobfuscated code for database.js ?
Why is @types/jsonwebtoken a dependency and not a dev dep?
See https://github.com/firebase/firebase-admin-node/blob/master/package.json#L28
I success send push to device using firebase-admin node.js.
I called admin.messageing().sendToDevice(token, payload).then(function(response) {
console.log("Successfully sent message:", response);
});
I didn't using http call to calling admin.messageing().sendToDevice. I just call that function.
Next, I input CLI 'node app.js' for execute that function. Then, I success send message to device. but node process was not terminating.
Why the process not terminate?
kjwook@kjwook-15N540-RFLGL:~/node aa.js
Successfully sent message: { results: [ { messageId: '0:1506502554508960%254b46d6f9fd7ecd' } ],
failureCount: 0,
successCount: 1,
multicastId: 6370642410814556000 }
^[[C^[[A^[[D^[[B
These methods currently accept arbitrary collections of properties. It is better to support a more strongly typed signature. For example:
UserRecord createUser(req?)
where req
is a type defined as follows:
export type CreateRequest {
public uid: string
public displayName: string
public emailVerified: bool
...
}
jasmine
Changing back firebase-admin to 5.3.0 made my unit tests run fine again. Neither 5.4.0 or 5.4.1 resolved the issue.
Message:
Error: Module did not self-register.
Stack:
Error: Module did not self-register.
at Error (native)
at Object.Module._extensions..node (module.js:597:18)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/builds/project/web/functions/node_modules/firebase-admin/node_modules/grpc/src/node/src/grpc_extension.js:30:15)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/builds/project/web/functions/node_modules/firebase-admin/node_modules/grpc/src/node/src/client.js:38:12)
Message:
TypeError: Cannot read property 'database' of undefined
Stack:
TypeError: Cannot read property 'database' of undefined
at UserContext.<anonymous> (/builds/project/web/functions/triggers/database/onUserFirstNameWrite.spec.ts:37:26)
at runCallback (timers.js:672:20)
at tryOnImmediate (timers.js:645:5)
Message:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
Stack:
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
at ontimeout (timers.js:386:14)
at tryOnTimeout (timers.js:250:5)
at Timer.listOnTimeout (timers.js:214:5)
Line 37 of onUserFirstNameWrite.spec.ts
is new functions.database.DeltaSnapshot(null, admin, null, user.first_name)
npm install --save firebase-admin
and run eb-deploy
The deploy fails with:
============= i-05310204bd3adbe90 ==============
-------------------------------------
/var/log/nodejs/nodejs.log
-------------------------------------
module.js:487
throw err;
^
Error: Cannot find module 'grpc'
at Function.Module._resolveFilename (module.js:485:15)
at Function.Module._load (module.js:437:25)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/var/app/current/node_modules/firebase-admin/node_modules/@google-cloud/common-grpc/src/service.js:26:12)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: `node index.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
┌──────────────────────────────────────────────────┐
│ npm update check failed │
│ Try running with sudo or get access │
│ to the local update config store via │
│ sudo chown -R $USER:$(id -gn $USER) /tmp/.config │
└──────────────────────────────────────────────────┘
> [email protected] start /var/app/current
Here is my package.json
{
"name": "App",
"version": "1.0.0",
"description": "App backend code",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/ParsePlatform/parse-server-example"
},
"license": "MIT",
"dependencies": {
"body-parser": "^1.17.2",
"express": "^4.15.4",
"firebase-admin": "5.2.1",
"kerberos": "~0.0.x",
"parse": "^1.10.0",
"parse-server": "^2.6.0",
"pug": "^2.0.0-rc.4",
"shortid": "^2.2.8"
},
"scripts": {
"start": "node index.js"
},
"engines": {
"node": ">=4.3"
}
}
In v5.2.0 we added Cloud Storage support to the Admin SDK. As a part of this we made a few changes to the index.d.ts
file:
import {Bucket} from '@google-cloud/storage';
declare namespace admin.storage {
interface Storage {
app: admin.app.App;
bucket(name?: string): Bucket;
}
}
Turns out this is not supported properly in TypeScript. It triggers the following error in downstream apps:
node_modules/firebase-admin/lib/index.d.ts(396,3): error TS2666: Exports and export assignments are not permitted in module augmentations.
npm ERR! Test failed. See above for more details.
Simply having the import statement at the top-level of the file is sufficient to trigger the error.
Possible Solutions
Bucket
type in our API, and use any
instead.// index.d.ts
declare module 'firebase-admin' {
}
export = admin;
This fixes the error, but I don't know if it has other consequences.
I'm using firebase-admin to fire FCM notifications to iOS and Androids clients. The module work fine but some time throw exception "Failed to parse response data"
I've tried to search but seem no one report it before and I don't know why it's happen.
Fire FCM notification
fcmSender.messaging().sendToDevice(registrationTokens, fcmPayload, fcmOptions)
Here is trace log:
Error: Failed to parse response data: "SyntaxError: Unexpected end of JSON input". Raw serverresponse: "."
File "/backend/node_modules/firebase-admin/lib/utils/error.js", line 39, col 28, in FirebaseAppError.FirebaseError [as constructor]
var _this = _super.call(this, errorInfo.message) || this;
File "/backend/node_modules/firebase-admin/lib/utils/error.js", line 84, col 23, in new FirebaseAppError
return _super.call(this, {
File "/backend/node_modules/firebase-admin/lib/utils/api-request.js", line 104, col 48, in IncomingMessage.<anonymous>
var parsingError = new error_1.FirebaseAppError(error_1.AppErrorCodes.UNABLE_TO_PARSE_RESPONSE, "Failed to parse {snip}
File "events.js", line 110, col 20, in emitNone
File "events.js", line 207, col 7, in IncomingMessage.emit
File "_stream_readable.js", line 1047, col 12, in endReadableNT
File "internal/process/next_tick.js", line 102, col 11, in _combinedTickCallback
File "internal/process/next_tick.js", line 198, col 9, in process._tickDomainCallback
I tried making a custom email action handler in a firebase cloud function and found that these methods weren't available with the firebase-admin-node implementation.
Testing the current version of this module [email protected]
with snyk/snyk results in a low severity warning and makes it exit with an error.
This can be resolved by updating [email protected]
to [email protected]
.
snyk test firebase-admin
Debian buster
Node.js v 8.5.0
firebase-admin v ^5.0.0
When internet connection is disabled, application should print "Firebase disconnected".
It seems, it never does!
"use strict";
var path = require('path');
var admin = require("firebase-admin");
var serviceAccount = require(path.join(__dirname, "some-firebase-adminsdk-lu0x5-82c66d50f5.json"));
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://some.firebaseio.com/"
});
const database = admin.database();
var connectedRef = database.ref(".info/connected");
connectedRef.on("value", function(snap) {
if (snap.val() === true) {
console.log("Firebase connected!");
} else {
console.log("Firebase disconnected!");
}
});
In firebase functions, when using storage hook, Google cloud storage has to be used to generate signed URL for any resource. The signed URL generated by the Google cloud storage cannot be used for photoURL in auth object. When setting that URL, firebase admin throws not a valid URL. On checking the source code of validateURL @ https://github.com/firebase/firebase-admin-node/blob/master/src/utils/validator.ts#L165, the path regex doesn't accept %
as a valid character in URL.
const functions = require('firebase-functions');
const mkdirp = require('mkdirp-promise');
const gcs = require('@google-cloud/storage')({keyFilename: 'service-account.json'});
const spawn = require('child-process-promise').spawn;
const LOCAL_TMP_FOLDER = '/tmp/';
const admin = require('firebase-admin');
// initialize admin SDK with env variables
admin.initializeApp(functions.config().firebase);
// Max height and width of the thumbnail in pixels.
const THUMB_MAX_HEIGHT = 200;
const THUMB_MAX_WIDTH = 200;
// Thumbnail prefix added to file names.
const THUMB_PREFIX = 'thumb_';
/**
* When an image is uploaded in the Storage bucket We generate a thumbnail automatically using
* ImageMagick.
*/
exports.generateThumbnail = functions.storage.object().onChange(event => {
const filePath = event.data.name;
const filePathSplit = filePath.split('/');
const fileName = filePathSplit.pop();
const fileDir = filePathSplit.join('/') + (filePathSplit.length > 0 ? '/' : '');
const thumbFilePath = `${fileDir}${THUMB_PREFIX}${fileName}`;
const tempLocalDir = `${LOCAL_TMP_FOLDER}${fileDir}`;
const tempLocalFile = `${tempLocalDir}${fileName}`;
const tempLocalThumbFile = `${LOCAL_TMP_FOLDER}${thumbFilePath}`;
// Exit if this is triggered on a file that is not an image.
if (!event.data.contentType.startsWith('image/')) {
console.log('This is not an image.');
return;
}
// Exit if the image is already a thumbnail.
if (fileName.startsWith(THUMB_PREFIX)) {
console.log('Already a Thumbnail.');
return;
}
// Exit if this is a move or deletion event.
if (event.data.resourceState === 'not_exists') {
console.log('This is a deletion event.');
return;
}
// Create the temp directory where the storage file will be downloaded.
return mkdirp(tempLocalDir).then(() => {
// Download file from bucket.
const bucket = gcs.bucket(event.data.bucket);
return bucket.file(filePath).download({
destination: tempLocalFile
}).then(() => {
console.log('The file has been downloaded to', tempLocalFile);
// Generate a thumbnail using ImageMagick.
return spawn('convert', [tempLocalFile, '-thumbnail', `${THUMB_MAX_WIDTH}x${THUMB_MAX_HEIGHT}>`, tempLocalThumbFile]).then(() => {
console.log('Thumbnail created at', tempLocalThumbFile);
// Uploading the Thumbnail.
return bucket.upload(tempLocalThumbFile, {
destination: thumbFilePath
}).then((files) => {
console.log('Thumbnail uploaded to Storage at', thumbFilePath);
return files[0].getSignedUrl({
action: 'read',
expires: '03-09-2491'
}).then(signedUrls => {
const photoURL = signedUrls[0];
const uid = 'XXXXXXXXXXXXX';
return admin.auth().updateUser(uid, {
photoURL: outputURL,
})
.then(response => {
console.log('success');
});
});
});
});
});
});
});
I'm using firebase-admin to authenticate requests made to my express server. I'm looking to write unit tests for my routes, but I'm blocked on testing routes that require authentication.
I have a middleware that checks if requests are authenticated.
public resolve(): (req, res, next) => void {
return async (req, res, next) => {
const header = req.header('Authorization');
if (!header || !header.split(' ')) {
throw new HttpException('Unauthorized', UNAUTHORIZED);
}
const token = header.split(' ')[1];
await admin.auth().verifyIdToken(token).then((decodedToken: any) => {
req.user = decodedToken;
next();
}).catch((error: any) => {
throw new HttpException(error, UNAUTHORIZED);
});
};
}
So far, I can only unit test my routes to make sure that they respond UNAUTHORIZED
instead of NOT_FOUND
.
it('GET /api/menu should return 401 ', done => {
const NOT_FOUND = 404;
const UNAUTHORIZED = 401;
supertest(instance)
.get('/api/menu')
.end((error, response: superagent.Response) => {
expect(response.status).not.toEqual(NOT_FOUND);
expect(response.status).toEqual(UNAUTHORIZED);
done();
});
});
But, I want to write more unit tests than this! I'd like a way to mock an authenticated user. Perhaps I'm overcomplicating this and don't need a feature from firebase-admin, but I thought I might as well ask.
Could there be a feature to mock the ID token of test users in my firebase db so that I can unit test my routes with users of different types?
I've asked about how this might be possible currently on stack overflow here. Sorry if I'm over complicating this, but this might be a pretty nifty feature if not possible already.
Hello,
So I'm try to call the key in the snapshot but I get this error:
UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot set property 'id' of null
I'm using firebase-admin: 4.2.1 and nodejs 6.9.1, the firebase product is storage, I'm using MacOx and my code is:
var db = admin.database().ref('events/-KlGpV1rBu9iACpwdluZ').orderByKey(),
deferred = Q.defer(),
childData = null,
info = [];
db.once("value").then(function(snapshot) {
snapshot.forEach(function(childSnapshot) {
console.log('key', childSnapshot.key);
console.log('val', childSnapshot.val());
info.push(childSnapshot.key);
});
deferred.resolve(info);
});
return deferred.promise;
I have been reading all documentation about the key and I didn't found any issue in the code. Is possible that the problem is that the documentation is not updated or has issues?
Thanks
What happened? How can we make the problem occur?
This could be a description, log/console output, etc.
// TODO(you): code here to reproduce the problem
In the FirebaseAppError
constructor, it prepends the string app/
to the error code before calling super
. This makes it very difficult to look at an instance of FirebaseAppError
at runtime and determine which error code it has.
For example:
let err = new FirebaseAppError(AppErrorCodes.NETWORK_ERROR, "ECONNRESET");
if (err.code === AppErrorCodes.NETWORK_ERROR) {
// ...
} else {
// Unexpectedly we end up here because err.code === ('app/' + AppErrorCodes.NETWORK_ERROR)
}
Is there a suggestion for how to deal with this? I couldn't find an example elsewhere in the codebase.
Retrieve the latest Realtime Database client code from from https://github.com/firebase/firebase-js-sdk
Related to #52
I'm getting a "Unable to import module" error when deploying v5.3.0 or above to AWS Lambda. The error log is cryptic but it does contain reference to "firebase-admin/node_modules/grpc/src/node/src/grpc_extension.js:30:15"
All works as expected when downgrading to v5.2.1.
[Refiling for user @Sun3 from https://github.com/firebase/functions-samples/issues/181]
Feature Request:
The user.sendEmailVerification()
needs to be supported by Firebase Cloud Functions. This is available in client side but not server side. When using Cloud Functions to create new users we also need to automatically send Email Verification before new user can use our apps. This is currently as stopping block for our apps.
At this point the user.sendEmailVerification()
gives error that function is not found.
admin.auth().createUser({
email: emailAddress,
emailVerified: false,
password: password,
displayName: '', //name,
disabled: false
})
.then(function (user) {
// A error representation of the newly created user is returned
console.log("Created Firebase User successfully with id: ", user.uid);
console.log("user.emailVerified:", user.emailVerified);
// Send Email Verification
user.sendEmailVerification()
.then(function (emailSent) {
console.log('emailSent ', emailSent);
})
.catch(function (error) {
console.log('emailSent error ', error);
});
// ... Additional code below
Thank you and I am open to any suggestions.
I am trying to make it work with nestjs server. I had a problem doing a normal require('cert.json') so i changes my cert file to a ts file and modified the typescript file as
export default {
...SETTINGS
}
and then did
import * as firebase from 'firebase-admin';
import { default as config } from './firebase-config';
firebase.initializeApp({
credential: firebase.credential.cert(config),
databaseURL: 'https://xxx.firebaseio.com'
});
the firebase-admin is running fine, but along the way, it throws an error first.
ERROR in [at-loader] ./src/electron/nest/firebase-config.ts:2:3
TS2345: Argument of type '{ "type": string; "project_id": string; "private_key_id": string; "private_key": string; "client_...' is not assignable to parameter of type 'string | ServiceAccount'.
Object literal may only specify known properties, and '"type"' does not exist in type 'string | ServiceAccount'.
as explained in above.
as explained above.
[REQUIRED] Step 2: Describe your environment
[REQUIRED] Step 3: Describe the problem
import * as admin from 'firebase-admin';
var serviceAccount = require('./keys/keyfile.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://test.firebaseio.com"
});
var registrationToken = "--some-key--";
var payload = {
notification: {
title: "$GOOG up 1.43% on the day",
body: "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day."
},
data: {
stock: "GOOG",
open: "829.62",
close: "635.67"
}
};
function panelMessage(){
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
})
.catch(function(error) {
// console.log(serviceAccount);
var date = new Date();
console.log(date.toString());
console.log("Error sending message:", error);
});
}
I run this code through node and it work but when i add it in angular-universal
server.ts
file.. it give the following error..
Error sending message: { Error: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "socket hang up". at FirebaseAppError.Error (native) at FirebaseAppError.FirebaseError [as constructor] (D:\angular2MH\firebase - panel\panel\node_modules\firebase-admin\lib\utils\error.js:39:28) at new FirebaseAppError (D:\angular2MH\firebase - panel\panel\node_modules\firebase-admin\lib\utils\error.js:84:23) at D:\angular2MH\firebase - panel\panel\node_modules\firebase-admin\lib\firebase-app.js:119:23 at ZoneDelegate.invoke (D:\angular2MH\firebase - panel\panel\node_modules\zone.js\dist\zone-node.js:232:26) at Zone.run (D:\angular2MH\firebase - panel\panel\node_modules\zone.js\dist\zone-node.js:114:43) at D:\angular2MH\firebase - panel\panel\node_modules\zone.js\dist\zone-node.js:502:57 at ZoneDelegate.invokeTask (D:\angular2MH\firebase - panel\panel\node_modules\zone.js\dist\zone-node.js:265:35) at Zone.runTask (D:\angular2MH\firebase - panel\panel\node_modules\zone.js\dist\zone-node.js:154:47) at drainMicroTaskQueue (D:\angular2MH\firebase - panel\panel\node_modules\zone.js\dist\zone-node.js:401:35)
errorInfo: { code: 'app/invalid-credential', message: 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "socket hang up".' } }
I checked the time (read at many place that could be the issue) and they are all synced.. Can anyone help me out with the issue? I'm using this repository https://github.com/Skillnter/angular-universal
Steps to reproduce:
1). Get the angular-universal from git https://github.com/Skillnter/angular-universal
2). open file \src\server.ts
3). write the following code with respective values of keyfile and
import * as admin from 'firebase-admin';
var serviceAccount = require('./keys/keyfile.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: "https://test.firebaseio.com"
});
var registrationToken = "--some-key--";
var payload = {
notification: {
title: "$GOOG up 1.43% on the day",
body: "$GOOG gained 11.80 points to close at 835.67, up 1.43% on the day."
},
data: {
stock: "GOOG",
open: "829.62",
close: "635.67"
}
};
function panelMessage(){
admin.messaging().sendToDevice(registrationToken, payload)
.then(function(response) {
// See the MessagingDevicesResponse reference documentation for
// the contents of response.
console.log("Successfully sent message:", response);
})
.catch(function(error) {
// console.log(serviceAccount);
var date = new Date();
console.log(date.toString());
console.log("Error sending message:", error);
});
}
and use the panelMessage function after server started..
let server = app.listen(app.get('port'), () => {
console.log(`Listening on: http://localhost:${server.address().port}`, __dirname);
panelMessage();
});
4). open CMD(windows)/terminal(Linux) and run "npm start" in the working directory of angular-universal
I am currently using passportjs with Node.js in firebase functions to create authentication.
The problem is I used Facebook authentication. However when I create account using the following command. It still creates account by email only. There is no provider if I check in console.
admin
.auth()
.createUser({
email: profile.emails[0].value,
emailVerified: false,
displayName: profile.displayName,
photoURL: profile.photos[0].value,
disabled: false,
providerData: [
{
displayName: profile.displayName,
email: profile.emails[0].value,
photoURL: profile.photos[0].value,
providerId: 'facebook.com',
uid: profile.id
}
]
})
And when I try to sign-in from client side by Facebook with the same email. I cannot sign in since there is email existing in Firebase Authentication. On the other hands, if I create account from Client Side App by Facebook. I cannot create admin.auth().createUser({ .... }) with the same Facebook email.
I think it happen because. The account is no linking together if we create account by Firebase Admin.
Related issue is here - googleapis/nodejs-firestore#21
Stream utility - bun
that pins node engine to 0.10.x, yarn doesnt like it and its right to do it so. Latest release depends on the firestore, hence cant update the module
My system specs:
Step 3: Describe the problem
Whenever I try to use firebase-admin in my webpack-react project, it throws a bunch of errors,
"Module parse failed: /path/to/file.json Unexpected token (2:6)
You may need an appropriate loader to handle this file type."
As a result, a bunch other errors: "Module not found : Error: Cannot resolve 'file' or 'directory' occurs
I used npm to install firebase-admin, and defined it in my project js file. The error occurs when I run the project with "npm start"
import * as admin from 'firebase-admin"
I'd like to suggest a way to validade the phone number in the server.
Something like validatePhoneNumber(verificationId, verificationCode)
(which returns the phone number, for example) would be very useful.
Maybe also a validatePhoneNumber(verificationId, verificationCode, phoneNumber)
that returns a Boolean.
I don't see how to verify if the phone is valid without creating an account. The client has sent the sms, the user has submited the verification code, but the only methods available are to link
or signin
(which would create an account with sJks92mda0
uid).
PS: A way to set/change the uid of a firebase user would also be a workaround to me, because then I would be able to create the account in the client and change the uid in the server.
Here the code at index.js (briefly)
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
const dB = admin.database();
exports.contactAdded = functions.database.ref('/cards/{userPhoneEmail}/cont')
.onWrite(event =>{
var telMail = (event.data._path).split('/')[2];
if (!telMail.includes('@')) {
admin.auth().getUserByPhoneNumber(telMail)
.then(function(userRecord) {
console.log("Successfully fetched user data:", userRecord.toJSON());
findOutMyContacts(userRecord);
})
.catch(function(error) {
console.log("Error fetching user data:", error);
});
}
return console.log(event.data._path, event.data._delta, event.data._newData);
});`
```
Function is triggered but this : admin.auth().getUserByPhoneNumber(telMail) gives an error :
> TypeError: admin.auth(...).getUserByPhoneNumber is not a function
> at exports.contactAdded.functions.database.ref.onWrite.event (/user_code/index.js:234:22)
> at /user_code/node_modules/firebase-functions/lib/cloud-functions.js:35:20
> at process._tickDomainCallback (internal/process/next_tick.js:135:7)
[issues100](https://github.com/firebase/firebase-functions/issues/100#issuecomment-327264141)
The Cloud Functions for Firebase SDK uses the Firebase Admin SDK as its source for a TypeScript definition of an auth.UserRecord
. The auth.UserRecord
currently contains the following fields:
public readonly uid: string;
public readonly email: string;
public readonly emailVerified: boolean;
public readonly displayName: string;
public readonly photoURL: string;
public readonly disabled: boolean;
public readonly metadata: UserMetadata;
public readonly providerData: UserInfo[];
However, when a Cloud Function is invoked for an Auth user creation that uses phone authentication, the UserRecord sent as a JSON object also contains a phoneNumber
field:
{
"metadata": {
"createdAt": "2017-06-01T23:01:23.000Z",
"lastSignedInAt": "2017-06-01T23:01:23.000Z"
},
"phoneNumber": "+1555123456",
"providerData": [
{
"providerId": "phone",
"uid": "+1555123456"
}
],
"uid": "C6simWCCNlO3Mdyq9PYyY1O8qPJ3"
}
This new phoneNumber
is currently hard to access for TypeScript users, since it's not yet present in the auth.UserRecord
.
We should add the phoneNumber
field to the Node.js Admin SDK.
Operating System version:
macOS Sierra 10.12.6
node/6.11.1
Firebase SDK version:
"firebase": "4.4.0",
"firebase-admin": "5.2.1",
Library version:
Firebase Product: database
When an exception is thrown from a user callback (inside .once or .then)
the exception is raised as a uncaught exception event instead of
calling the .catch function.
const db = getDatabase();
const id = `/path/key`;
process.on('uncaughtException', function (err) {
// this event is called instead of the .catch(err)
console.error( "UNCAUGHT EXCEPTION " );
console.error( "[Inside 'uncaughtException' event] " + err.stack || err.message );
process.exit();
});
db.ref(id)
.once('value', snap => {
throw new Error('test');
})
.catch(err=>{
// This catch function is not ever called.
console.log('caught the error', err);
});
This behavior is not consistent with the standard promise model.
const promise = new Promise(function (resolve, reject) { resolve('ok'); });
promise
.then(value=>{
console.log(value);
throw new Error('test');
})
.catch (err=>{
// This catch function is called.
console.log('catch 1');
});
When I do an 'npm run dev' I get missing dependencies, probably based on the fact that dns, dgram and native-dns are deprecated and thus not maintained.
'''
This dependency was not found:
To install it, you can run: npm install --save dns
'''
Thanks for any information to solve this issue.
Integration test suite may sometimes fail with the following error:
FIREBASE WARNING: set at /blocked failed: permission_denied
[FAILURE] nonNullApp.database().ref("blocked").set(): Error: PERMISSION_DENIED: Permission denied
This happens when there are custom rules in the realtime database. Changing the rules back to defaults usually fixes the issue:
{
"rules": {
".read": "auth != null",
".write": "auth != null",
}
}
The integration test suite should not depend on a specific rules configuration. If such a dependency is needed, the test suite should update the rules config during the setup phase (Java and Python SDKs do this already).
var FieldValue = require("firebase-admin").FieldValue;
in cloud functions index.js (as per https://firebase.google.com/docs/firestore/manage-data/delete-data) is showing as undefined. Which leads to an error when trying to delete from Firestore:
TypeError: Cannot read property 'delete' of undefined at /user_code/index.js:239:34 at process._tickDomainCallback (internal/process/next_tick.js:135:7)
With the release of phone number authentication many apps will not have email address as a unique key. It would be very useful to have a 'findUserByPhoneNumber()` call in the admin SDK to match the email one.
According to https://firebase.google.com/docs/cloud-messaging/admin/errors, clients should honor Retry-After header for messaging/server-unavailable
and messaging/internal-error
.
However, the MessagingDevicesResponse does not include a Retry-After header.
I get the following error when server starts:
Cannot find module 'XXX\node_modules\firebase-admin\node_modules\grpc\src\node\extension_binary\node-v46-win32-ia32\grpc_node.node
main.ts:
import { Meteor } from 'meteor/meteor';
import * as admin from "firebase-admin";
Meteor.startup(() => {
admin.initializeApp({
credential: admin.credential.cert("./key.json"),
databaseURL: "XXX"
});
});
picture of the lost file's path:
Could you help me please ?
database
When attempting to use firebase-admin
s initializeApp
function, the URL is strictly enforced. I'm sure this is intended, however it is keeping me from proxying the firebase URL to a local server for testing. Example:
firebase.initializeApp({
credential: firebase.credential.cert(FIREBASE_CREDENTIALS),
databaseURL: 'http://localhost:4001/https://my.firebaseio.com'
});
Resulting in the following error:
Error: FIREBASE FATAL ERROR: Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com
I use mockyeah for integration testing, which is a nice solution for being able to record snapshots for outgoing requests and their responses. The only caveat is that in order to record the response you have to proxy the URL so that the server can make the call itself.
The issue isn't necessarily with implementation on either side. My overall question is, would supporting a proxied URL be feasible?
Listed above.
index.d.ts
sometimes has any
where not required
e.g
admin.database().ref('someref').once('value')
is Promise<any>
when it should return the same type as the successCallback
e.g. Promise<admin.database.DataSnapshot>
.
I'm seeing some dependency issues.
firebase-admin: 5.2.1
➜ customer-manager (master) ✗ yarn add firebase-admin .../customer-manager
yarn add v0.27.5
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...
success Saved lockfile.
success Saved 2 new dependencies.
├─ @google-cloud/[email protected]
└─ [email protected]
Done in 4.74s.
➜ customer-manager (master) ✗ yarn start .../customer-manager
yarn start v0.27.5
$ node build/dev-server.js
> Starting dev server...
ERROR Failed to compile with 22 errors 10:37:27 PM
These dependencies were not found:
* fs in ./~/firebase-admin/lib/auth/credential.js, ./~/@google-cloud/storage/src/bucket.js and 10 others
* net in ./~/faye-websocket/lib/faye/websocket/client.js, ./~/forever-agent/index.js and 3 others
* tls in ./~/faye-websocket/lib/faye/websocket/client.js, ./~/forever-agent/index.js and 1 other
* child_process in ./~/google-auth-library/lib/auth/googleauth.js
* dns in ./~/isemail/lib/isemail.js
I want to use the the Firebase Admin Node.js SDK (v5.0.0) to manage users of my app (add/delete users), but I'm not able to find sample code that would allow me to learn how to implement this API for my needs.
Operating System version: CentOS
Firebase SDK version: 5.4.1
Firebase Product: Cloud Messaging
Is there any particular reason why we're restricting the values of the key:value
pairs in data
to just string
s?
If calling https://fcm.googleapis.com/fcm/send
directly, you can include objects
within data
.
firebase-admin
needs to declare a dependency on @types/google-cloud__storage
for TypeScript projects.
firebase-functions
.firebase-admin
node package (peer dependency)tsc
fails with this error. Try `npm install @types/@google-cloud/storage` if it exists or add a new declaration (.d.ts) file containing `declare module '@google-cloud/storage';`
I use AWS Elastic Beanstalk for my application deployment.
Using of firebase-admin library causes deployment failures:
ERROR: Failed to run npm install. Snapshot logs for more details. ERROR: [Instance: i-068bd9d30a1d8df4b] Command failed on instance. Return code: 1 Output: (TRUNCATED)...pt/elasticbeanstalk/containerfiles/ebnode.py", line 180, in npm_install raise e subprocess.CalledProcessError: Command '['/opt/elasticbeanstalk/node-install/node-v6.10.0-linux-x64/bin/npm', '--production', 'rebuild']' returned non-zero exit status 254. Hook /opt/elasticbeanstalk/hooks/appdeploy/pre/50npm.sh failed. For more detail, check /var/log/eb-activity.log using console or EB CLI. INFO: Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. ERROR: Unsuccessful command execution on instance id(s) 'i-068bd9d30a1d8df4b'. Aborting the operation. ERROR: Failed to deploy application.
The same problem is reproduced on t2.micro and t2.small.
Similar issue is described here, but I don't want to use EC2 with bigger CPU:
parse-community/parse-server#1276
Looks like you have some problems with memory leaks during dependency installation.
P.S. - no problem with deployment during using library from https://www.npmjs.com/package/fcm-node
I experience this error when running mocha with --use_strict argument
Version 4.2.1
node v6.11.2
mocha v3.5.0
TypeError: Cannot read property 'navigator' of undefined
at node_modules\firebase-admin\lib\database\database.js:39:492
at Object.<anonymous> (node_modules\firebase-admin\lib\database\database.js:254:3)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (node_modules\firebase-admin\lib\index.js:11:1)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (node_modules\firebase-functions\lib\apps.js:25:16)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (node_modules\firebase-functions\lib\providers\database.js:25:14)
at Module._compile (module.js:570:32)
at Object.Module._extensions..js (module.js:579:10)
at Module.load (module.js:487:32)
at tryModuleLoad (module.js:446:12)
at Function.Module._load (module.js:438:3)
at Module.require (module.js:497:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (node_modules\firebase-functions\lib\index.js:32:16)
Not Applicable
view http://registry.npmjs.org/firebase-admin and notice that legacy casetext
URLs are still present
You should fix/update the repository and the license fields in package.json
.
As a regular snyk user, running snyk test
to check for vulnerabilities of all NPM dependencies and the latest Firebase Admin could not pass the test and discovered that jsonwebtoken
is the culprit. See the image below for more details:
The npm install
command should warn the user if the admin SDK is installed in a client environment.
"windows": "10"
"node.js": "8.2.1"
"firebase-admin": "~4.2.1"
I already posted this on StackOverflow, but I think that this is not really a question, rather an issue because it works in the documentation, but not in my project. https://stackoverflow.com/questions/45543072/firebase-admin-database-snapshot-data-after-query
I am trying to use a query to select a child and then retrieve the data from there, but I am unable to access the properties, i.e. snapshot.val().property
.
JSON (data)
values: {
a: {
randomValue: "set",
sorter: 1
},
b: {
randomValue: "hat",
sorter: 2
}
}
admin.database().ref('values/a').once('value').then(snapshot => {
console.log(snapshot.val().randomValue + ' .. ' + snapshot.val().sorter);
});
output:
set .. 1
admin.database().ref('values').orderByChild('sorter').equalTo(1).once('value').then(snapshot => {
console.log(snapshot.val());
console.log(snapshot.val().randomValue + ' .. ' + snapshot.val().sorter);
console.log(snapshot.child('randomValue').val() + ' .. ' + snapshot.child('sorter').val());
}
output:
a: {
randomValue: "set",
sorter: 1
}
undefined .. undefined
null .. null
should be:
a: {
randomValue: "set",
sorter: 1
}
set .. 1
set .. 1
Add a source map to the doc generation process so that reference docs can link directly into source files for each function/constant/etc.
The database trigger event contains auth info about the user generating the event. The same auth info would be very useful to have in the storage onChange events as well.
Currently the integration test suite can only be run against the admin-sdks-integration
project, which means only the core Firebase developers can actually run them. It should be made possible to run the integration tests against any project, so that external developers can also test and contribute to the integration test suite.
URL:
https://us-central1-ossbot-f0cad.cloudfunctions.net/githubWebhook
Content type:
application/json
Secret:
N/A
Select individual events:
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.