I'm trying to create a collection called "users" but there seems to be a problem with the firebase reference , I'm using an already existing repo where I added my addUserToDb() function, in the function above called saveMessagingDeviceToken() there seems to be no problem with the firebase.
<code>
// Saves the messaging device token to the datastore.
function saveMessagingDeviceToken() {
firebase.messaging().getToken().then(function(currentToken) {
if (currentToken) {
console.log('Got FCM device token:', currentToken);
// Saving the Device Token to the datastore.
firebase.firestore().collection('fcmTokens').doc(currentToken)
.set({uid: firebase.auth().currentUser.uid});
} else {
// Need to request permissions to show notifications.
requestNotificationsPermissions();
}
}).catch(function(error){
console.error('Unable to get messaging token.', error);
});
}
// Add the user to DB
function addUserToDb(profilePicUrl, userName, userID){
var db = this.firebase.firestore();
db.collection("users").doc(userID).set({
name: userName,
profilePic: profilePicUrl,
uid: userID
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
}
</code>
The way to add is taken from https://firebase.google.com/docs/firestore/manage-data/add-data which is the documentation.
the full error :
TypeError: Cannot read property 'firebase' of undefined
at addUserToDb (main.js:115)
at Object.authStateObserver [as next] (main.js:199)
at subscribe.ts:104
at subscribe.ts:233
Related
I am using signInWithCustomToken() after initiating it on the server.
async function signinWithToken(data, sendResponse) {
const { token } = data;
console.log(token);
signInWithCustomToken(auth, token)
.then((user) => {
console.log(user);
sendResponse({ success: true, user });
})
.catch((err) => {
sendResponse({ success: false, message: err.message
});
});
}
The problem is that the user object returned doesn't include the user details like displayName, email, etc...
Is there something I could do about it?
A custom token only contains the properties/claims that you put into it. Firebase doesn't add any information to the custom token, so if you find certain values missing, it's because your code didn't add them while minting the token.
Also see the Firebase documentation on minting a custom token using the Admin SDK.
The signInWithCustomToken() method returns a Promise which resolves with a UserCredential and not a User.
So you need to do as follows:
async function signinWithToken(data, sendResponse) {
const { token } = data;
console.log(token);
signInWithCustomToken(auth, token)
.then((userCredential) => {
console.log(userCredential.user);
//..
})
Suppose the user wanted to sign up or sign in to the account. However, the Firebase error appears like this. How can I display the toast notification to the user using try-catch statement with typescript?
[FirebaseError: Firebase: Error (auth/email-already-in-use).]
Here is the code I tried:
try {
const credential = await signUpWithEmail(data.email, data.password);
if (credential.uid) {
toast.show({
title: 'Account created! 🎊',
status: 'success',
description: 'Welcome!.',
});
} else {
const auth = getAuth();
auth.signOut();
}
} catch (err) {
toast.show({
title: 'Cannot sign-up an account.',
status: 'error',
description: [CONDITIONAL ERROR MESSAGE FOR DISPLAYING TO THE USER],
});
}
Edit: add code
The err object has a code property that you check check in your code, and a message property that you can display to the user.
So:
...
} catch (err) {
toast.show({
title: 'Cannot sign-up an account.',
status: 'error',
description: err.message,
});
}
See the Firebase documentation on sending a password reset email that has an example of accessing these two properties.
Also see:
Firebase error messages in different languages?
list of all auth/ errors for firebase web API
Does Firebase Auth return an Error Code if authentification is not successful?
I want to create a node js app which downloads some data from the firestore. Although I've done everything like it's shown in tutorials I've been stuck with reading document from the firestore for hours. I have a very simple database structure with simple security rules:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /partners/{document=**} {
allow read: if true;
}
}
}
In my code I just want to login into firebase using email and password and then download one document under existing path:
const firebase = require("firebase/app");
require("firebase/auth");
require("firebase/firestore");
const email = <correct email>
const password = <correct password>
var firestoreConfig = {
...
};
// Initialize Firebase
firebase.initializeApp(firestoreConfig);
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(user){
const userId = user.user.uid
const firestore = firebase.firestore();
console.log(`logged to firestore as ${userId}`)
firestore.doc("/partner/test/communication/544a3deec/messages/2e5b89b8-c48f-4d4f").get()
.then(function(data){
console.log(`${Object.keys(data).length}`);
})
.catch(function(error){
console.log(error);
})
})
and the error is
{ FirebaseError: Missing or insufficient permissions.
at new FirestoreError (/Users/cb/Documents/IdeaProjects/node-hello/node_modules/#firebase/firestore/dist/index.node.cjs.js:1205:28)
at fromRpcStatus (/Users/cb/Documents/IdeaProjects/node-hello/node_modules/#firebase/firestore/dist/index.node.cjs.js:5246:12)
at fromWatchChange (/Users/cb/Documents/IdeaProjects/node-hello/node_modules/#firebase/firestore/dist/index.node.cjs.js:5482:35)
at PersistentListenStream.onMessage (/Users/cb/Documents/IdeaProjects/node-hello/node_modules/#firebase/firestore/dist/index.node.cjs.js:15817:27)
at /Users/cb/Documents/IdeaProjects/node-hello/node_modules/#firebase/firestore/dist/index.node.cjs.js:15750:30
at /Users/cb/Documents/IdeaProjects/node-hello/node_modules/#firebase/firestore/dist/index.node.cjs.js:15786:28
at /Users/cb/Documents/IdeaProjects/node-hello/node_modules/#firebase/firestore/dist/index.node.cjs.js:14218:20
at process._tickCallback (internal/process/next_tick.js:68:7)
code: 'permission-denied',
name: 'FirebaseError',
toString: [Function] }
I see that the login was successful because it printed out the uid of the user. What can be the issue ? Security rules or I just completely don't understand the firestore ?
EDIT:
Changed my code according to Doug answer:
firebase.initializeApp(firestoreConfig);
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
const userId = user.uid
const firestore = firebase.firestore();
console.log(`logged firestore as ${userId}`)
firestore.doc("/partner/test/communication/544a3deec/messages/2e5b89b8-c48f-4d4f").get()
.then(function(data){
console.log(`${Object.keys(data).length}`);
})
.catch(function(error){
console.log(error);
})
} else {
}
});
firebase.auth().signInWithEmailAndPassword(email, password)
.catch(function(error){
console.log(error);
})
same error as before
There is a typo in the code, an additional s for partner.
I'm trying a basic proof of concept with firebase cloud messaging and I'm having pain receiving messages, nothing happens when I send messages even if the app is in foreground, the onMessage event doesn't return anything despite I don't have any error on sending all seem to be ok from postman or fcm console.
I noticed also that chrome://gcm-internals/ displays state "CONNECTING"
here is my app.js but for me it seems more to be related to the gcm state who should display "CONNECTED"
var firebase = require("firebase/app");
require('firebase/messaging');
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "AIzaSyCbrs6uvQQ5s6kAp6YfvDzsds_CfMt3-hA",
authDomain: "test-flarum-fcm.firebaseapp.com",
databaseURL: "https://test-flarum-fcm.firebaseio.com",
projectId: "test-flarum-fcm",
storageBucket: "",
messagingSenderId: "977636469573",
appId: "1:977636469573:web:76e2e191f02f8923df6c2c"
};
// Initialize Firebase
var app = firebase.initializeApp(firebaseConfig);
// Retrieve Firebase Messaging object.
var messaging = firebase.messaging();
//console.log(messaging);
console.log('myToken : '+getToken());
Notification.requestPermission().then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.');
//getMyToken();
if(isTokenSentToServer()){
console.log("token already saved")
}else{
// TODO(developer): Retrieve an Instance ID token for use with FCM.
getMyToken();
}
} else {
console.log('Unable to get permission to notify.');
setTokenSentToServer(false);
}
});
// Get Instance ID token. Initially this makes a network call, once retrieved
// subsequent calls to getToken will return from cache.
function getMyToken() {
messaging.getToken().then((currentToken) => {
if (currentToken) {
console.log(currentToken);
//sendTokenToServer(currentToken);//#todo
//updateUIForPushEnabled(currentToken);
saveToken(currentToken);
setTokenSentToServer(true);
} else {
// Show permission request.
console.log('No Instance ID token available. Request permission to generate one.');
// Show permission UI.
//updateUIForPushPermissionRequired();//#todo
//setTokenSentToServer(false); //#todo
setTokenSentToServer(false);
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
//showToken('Error retrieving Instance ID token. ', err);
setTokenSentToServer(false);
});
}
// Callback fired if Instance ID token is updated.
messaging.onTokenRefresh(() => {
messaging.getToken().then((refreshedToken) => {
console.log('Token refreshed.');
// Indicate that the new Instance ID token has not yet been sent to the
// app server.
setTokenSentToServer(false);
// Send Instance ID token to app server.
//sendTokenToServer(refreshedToken);
// ...
}).catch((err) => {
console.log('Unable to retrieve refreshed token ', err);
//showToken('Unable to retrieve refreshed token ', err);
});
});
function setTokenSentToServer(sent) {
window.localStorage.setItem('sentTokenToServer', sent ? 1 : 0);
}
function isTokenSentToServer(){
return window.localStorage.getItem('sentTokenToServer') == 1;
}
function saveToken(token){
myToken = token;
window.localStorage.setItem('myToken', token);
}
function getToken(){
return window.localStorage.getItem('myToken');
}
messaging.onMessage((payload) => {
console.log('Message received. ', payload);
// ...
});
Thanks for your help
[update] I solved the problem of gcm state but that's not wworking better despite the send result seems to be ok in postman
{
"multicast_id": 7270949329343339591,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1569712574121124%e609af1cf9fd7ecd"
}
]
}
I am trying to create a mongodb on the fly based on user input using javascript. Here is a snipit of the code I am writing.
mp.MongoClient.connect("mongodb://admin:admin_password#mongo_server.com:27017/admin")
.then(function (db) {
getListOfDatabases(db)
.then(function (databases) {
if (doesDatabaseExist(databases)) {
mp.MongoClient.connect("mongodb://admin:admin_password#mongo_server.com:27017/"+userDefinedDb)
.then(function (userDb) {
insertInFakeCollection(userDb, dbObject);
createRead(userDb, dbObject);
})
.fail(function(err){
console.log(err);
})
}
})
})
.fail(function (err) {
console.log(err);
})
I am able to to connect and get a list of databases, I try to connect to the user defined database, mongo throws me an error { [MongoError: auth failed] name: 'MongoError', ok: 0,errmsg: 'auth failed', code: 18 }
The admin password and user name are the same and it has role userAdminAnyDatabase.
I am not sure what I am doing wrong or why this issue is occurring. any help is appreciated.