Trust you are doing well. I am new to firebase and trying to do user authentication. I have installed pyrebase4 and created a project on the firebase console. I also enabled sign in with "Email and Password" and trying to connect with my app. Below is my code that I am trying:
import pyrebase
#connect to firebase via key-value pair
firebaseConfig = {
"apiKey": "xxxxxxxxxxxxxxxxxx",
"authDomain": "xxxxxxxxxxx",
"projectId": "xxxxxxxxxxx",
"storageBucket": "xxxxxxxxxxxxxx",
"messagingSenderId": "xxxxxxxxxxxxx",
"appId": "xxxxxxxxxxxxxxxxxxxx",
"measurementId": "G-5GCDEC526E"
}
#initialize the app
firebase = pyrebase.initialize_app(firebaseConfig)
#connect to firebase database
#db = firebase.database()
auth = firebase.auth()
#storage = firebase.storage()
#user login authentication
email = input("Enter your email: \n")
password = input("Enter your password: \n")
user = auth.create_user_with_email_and_password(email, password)
auth.get_account_info(user['idToken'])
I am using VS Code as an IDE, Python 3.8, and Ubuntu OS. Below is the error I am getting:
python3 main.py
Traceback (most recent call last):
File "main.py", line 15, in <module>
firebase = pyrebase.initialize_app(firebaseConfig)
File "/home/sonu/.local/lib/python3.8/site-packages/pyrebase/pyrebase.py", line 28, in initialize_app
return Firebase(config)
File "/home/sonu/.local/lib/python3.8/site-packages/pyrebase/pyrebase.py", line 36, in __init__
self.database_url = config["databaseURL"]
KeyError: 'databaseURL'
Can you help me solve the issue? Thanks in advance.
As the error said. The databaseURL property is missing from your configuration.
Since now the Realtime Database is not automatically be created at the time you create the new firebase project so the databaseURL is not included by default. See also
You can add an empty string to the key databaseURL, but be careful when you want to work with Realtime database, you need to update the configurations dictionary in your Python code.
As a result, you can start with these configurations if you don't have or you don't need to work with Realtime database:
firebaseConfig = {
"apiKey": "xxxxxxxxxxxxxxxxxx",
"authDomain": "xxxxxxxxxxx",
"projectId": "xxxxxxxxxxx",
"storageBucket": "xxxxxxxxxxxxxx",
"messagingSenderId": "xxxxxxxxxxxxx",
"appId": "xxxxxxxxxxxxxxxxxxxx",
"measurementId": "G-5GCDEC526E",
"databaseURL": ""
}
Or you can start with these configurations if you've already created a Realtime database:
firebaseConfig = {
"apiKey": "xxxxxxxxxxxxxxxxxx",
"authDomain": "xxxxxxxxxxx",
"projectId": "xxxxxxxxxxx",
"storageBucket": "xxxxxxxxxxxxxx",
"messagingSenderId": "xxxxxxxxxxxxx",
"appId": "xxxxxxxxxxxxxxxxxxxx",
"measurementId": "G-5GCDEC526E",
"databaseURL": "https://fir-#######-rtdb.europe-##########.app/"
}
You can find your database URL at the top of your database viewer in firebase console. [See the image below]
Add databaseURL in your config object ref
firebaseConfig = {
"apiKey": "xxxxxxxxxxxxxxxxxx",
"authDomain": "xxxxxxxxxxx",
"projectId": "xxxxxxxxxxx",
"storageBucket": "xxxxxxxxxxxxxx",
"messagingSenderId": "xxxxxxxxxxxxx",
"appId": "xxxxxxxxxxxxxxxxxxxx",
"measurementId": "G-5GCDEC526E",
"databaseURL":"your database url"
}
It is found in the realtime database tab above your saved data.
Related
i'm using firebase Auth in my expo app (Google Auth) and in order to do that, I need to set my firebase variables in a .env file (my API_KEYS, AuthDomain ...). I'm using expo constants to get those env variables and use them in my firebase.ts file, when implemented it worked on both mobile and web. Today I noticed that it's not working on web anymore because the constants.manifest object is empty and I don't understand why.
firebase.ts :
import { initializeApp } from "firebase/app";
import "firebase/auth";
import Constants from "expo-constants";
// Initialize Firebase
console.log("=======>", Constants);
const firebaseConfig = {
apiKey: Constants.manifest?.extra?.apiKey,
authDomain: Constants.manifest?.extra?.authDomain,
projectId: Constants.manifest?.extra?.projectId,
storageBucket: Constants.manifest?.extra?.storageBucket,
messagingSenderId: Constants.manifest?.extra?.messagingSenderId,
appId: Constants.manifest?.extra?.appId,
};
const Firebase = initializeApp(firebaseConfig);
export default Firebase;
app.config.js :
import "dotenv/config";
export default {
expo: {
entryPoint: "./src/App.tsx",
name: "Flooz",
slug: "flooz",
version: "1.0.0",
orientation: "portrait",
icon: "./src/assets/images/icon.png",
scheme: "flooz",
userInterfaceStyle: "automatic",
splash: {
image: "./src/assets/images/splash.png",
resizeMode: "contain",
backgroundColor: "#ffffff",
},
updates: {
fallbackToCacheTimeout: 0,
},
assetBundlePatterns: ["**/*"],
ios: {
supportsTablet: true,
},
android: {
adaptiveIcon: {
foregroundImage: "./src/assets/images/adaptive-icon.png",
backgroundColor: "#ffffff",
},
},
web: {
favicon: "./src/assets/images/favicon.png",
},
extra: {
apiKey: process.env.API_KEY,
authDomain: process.env.AUTH_DOMAIN,
projectId: process.env.PROJECT_ID,
storageBucket: process.env.STORAGE_BUCKET,
messagingSenderId: process.env.MESSAGING_SENDER_ID,
appId: process.env.APP_ID,
},
},
};
Expo changed their manifest structure.
You can access your environment variables in Constants.expoConfig.extra (source)
error that i'm getting:
Uncaught TypeError: Failed to resolve module specifier
"firebase/database". Relative references must start with either "/",
"./", or "../".
i am trying to setup firebase configuration for the latest version of firebase 9.1
<script type="module">
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-app.js";
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "....",
appId: "..."
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
//below import statement is causing the error
import { getDatabase, ref, set } from "firebase/database";
const db = getDatabase();
</script>
<script type="text/javascript" >
function InsertData() {
set(ref(db, 'TheStudent/'+rollV), {
NameOfStudent: "abc",
RollNo: 13,
Section: "B",
Gender: "Male"
});
}
document.getElementById('insertBtn').onclick = InsertData;
</script>
PS. i have hidden the config on purpose, so thats not the problem.
It seems you are using Firebase SDK over CDN so try importing database in same way:
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.1.0/firebase-database.js";
// CDN URL instead of "firebase/database"
The same source code work into a alone html page:
<script src="https://www.gstatic.com/firebasejs/7.19.0/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.0/firebase-firestore.js"></script>
<script>
var firebaseConfig = {
apiKey: "XYZ",
authDomain: "XYZ.firebaseapp.com",
databaseURL: "https://XYZ.firebaseio.com",
projectId: "XYZ",
storageBucket: "XYZ.appspot.com",
messagingSenderId: "XYZ",
appId: "XYZ"
};
// Initialize Firebase
let db =null;
if(!firebase.apps.length){
firebase.initializeApp(firebaseConfig);
db = firebase.firestore();
}
const id = new Date().getTime();
const userid = new Date().getTime();
let docRef = db.collection("alarms").doc("teste"+id);
docRef.set({ userid: userid }, { merge: true }).then((id)=>{
console.log("ID:",id);
}).catch(
(err)=>{
console.error(err);
}
);
Above, the example I taked from the google tutorial and work fine. But, into side server side, using dependences:
package.json
{
"name": "appengine-typescript",
"description": "An example TypeScript app running on Google App Engine.",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": ">=8.0.0"
},
"scripts": {
"start": "node -r source-map-support/register index.js"
},
"dependencies": {
"async_hooks": "^1.0.0",
"axios": "^0.19.2",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"ejs": "^2.6.2",
"express": "^4.16.3",
"firebase-admin": "8.6.0",
"firebase-functions": "3.3.0",
"jest-cli": "^26.4.2",
"js-sha1": "^0.6.0",
"node-cache": "^4.2.1",
"node-rest-client": "^3.1.0",
"nodemailer": "^6.3.0",
"source-map-support": "^0.5.16",
"uuid": "^3.3.2"
},
"devDependencies": {
},
}
Source:
import * as functions from "firebase-functions";
import * as firebase from "firebase-admin";
if (!firebase.apps.length) {
var firebaseConfig = {
apiKey: "XYZ",
authDomain: "XYZ.firebaseapp.com",
databaseURL: "https://XYZ.firebaseio.com",
projectId: "XYZ",
storageBucket: "XYZ.appspot.com",
messagingSenderId: "XYZ",
appId: "XYZ"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
}
const db = firebase.firestore();
const cmpID = "cmpid:" + new Date().getTime();
const userid = "userid" + new Date().getTime();
let docRef = db.collection("alarms").doc(cmpID);
docRef.set({ userid }, { merge: true }).then((id)=>{
console.log("ID:",id);
}).catch(
(err)=>{
console.error(err);
}
);
This case, happens the error below:
{ Error: 7 PERMISSION_DENIED: Missing or insufficient permissions.
at Object.callErrorFromStatus (/mnt/c/Users/gandb/Documents/workspace/vriend/v-alarm/services/node_modules/#grpc/grpc-js/build/src/call.js:30:26)
at Http2CallStream.call.on (/mnt/c/Users/gandb/Documents/workspace/vriend/v-alarm/services/node_modules/#grpc/grpc-js/build/src/client.js:96:33)
at Http2CallStream.emit (events.js:203:15)
at process.nextTick (/mnt/c/Users/gandb/Documents/workspace/vriend/v-alarm/services/node_modules/#grpc/grpc-js/build/src/call-stream.js:100:22)
at process._tickCallback (internal/process/next_tick.js:61:11)
code: 7,
details: 'Missing or insufficient permissions.',
metadata: Metadata { internalRepr: Map {}, options: {} } }
My Firestore configuration is:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow create,read, write, update, delete: if true;
}
}
}
Also, I tried :
Change folder and subfolders project permission to 777
Using a anonymous tab and the html page example continues working.
I found the error, ocorrs this message for many reasons, in this case I dont found documentation in any place, even here in stackoverflow.
The reason that ocorrous when you authentic using wrong credencials, valid but for another project. In my case, I use docker container, so I setup the credencial using enviroment variable like this:
ENV GOOGLE_APPLICATION_CREDENTIALS wrong-project.json
I generate the correct json credential and works well.
Into html works before, because html no need credential to work. But into nodeJS , google firestore sdk require credential.
I have been trying to deploy my firebase&vue app.
However I couldn't add firebase credentials to the env variable.
Basically this is the structure on vue.js
config
---- key.js
---- keys_dev.js
---- keys_prod.js
key.js
if(process.env.NODE_ENV == 'production'){
module.exports = require('./keys_prod');
} else {
module.exports = require('./keys_dev');
}
keys_dev.js
module.exports = {
firebase: {
apiKey: "*********************************",
authDomain: "*****************************",
databaseURL: "****************************",
projectId: "******************************",
storageBucket: "**************************",
messagingSenderId: "**********************",
}
}
keys_prod.js
module.exports = {
firebase: {
apiKey: process.env['FIREBASE_apiKey'],
authDomain: process.env['FIREBASE_authDomain'],
databaseURL: process.env['FIREBASE_databaseURL'],
projectId: process.env['FIREBASE_projectId'],
storageBucket: process.env['FIREBASE_storageBucket'],
messagingSenderId: process.env['FIREBASE_messagingSenderId'],
}
}
Also I tried like this in keys_prod.js but I guess we can not use object in the env_var, so I changed it to the code above.
module.exports = {
firebase: process.env.FIREBASE_CONFIG
}
After npm run build, I created express app, define process.env's however when I run server, I am getting error because of env_vars are missing.
I tried to see logs on both front and backend console. I can see envs on node console but not in browser.
I also tried to deploy this app to heroku and firebase hosting. In both cases I added envs externally, but nothing change. (I guess there is no difference to use env_vars in localhost or remote server right ?)
Finally I tried to change keys.js (keys_prod > keys_dev)
if(process.env.NODE_ENV == 'production'){
module.exports = require('./keys_dev');
} else {
module.exports = require('./keys_dev');
}
then it works, but I can find the credentials in the source code this time.
There's a better way that the other answer. You don't need to import - that would bring the settings into the deployed JS, which isn't a good idea.
Create a file like .env.local in the root of the Vue app, like this:
$ cat .env.local
# REMEMBER:
# ----------------------------------------------------------
# In development, *restart* "yarn serve" to pick up changes.
# ----------------------------------------------------------
VUE_APP_FIREBASE_API_KEY='1234-F1xH53UCnk'
VUE_APP_FIREBASE_AUTH_DOMAIN='your-web-1234.firebaseapp.com'
VUE_APP_FIREBASE_DATABASE_URL='https://your-web-1234.firebaseio.com'
VUE_APP_FIREBASE_PROJECT_ID='your-web-1234'
VUE_APP_FIREBASE_STORAGE_BUCKET='your-web-1234.appspot.com'
VUE_APP_FIREBASE_MESSAGING_SENDER_ID='12345678'
VUE_APP_FIREBASE_APP_ID='1:1234:web:0398509235'
Wherever you want firebase, do something like:
function getFirebaseConfig() {
const firebaseConfig = {
// see .env file for instructions
apiKey: process.env.VUE_APP_FIREBASE_API_KEY || 'api-key-not-set',
authDomain: process.env.VUE_APP_FIREBASE_AUTH_DOMAIN || 'env-not-set',
databaseURL: process.env.VUE_APP_FIREBASE_DATABASE_URL || 'env-not-set',
projectId: process.env.VUE_APP_FIREBASE_PROJECT_ID || 'env-not-set',
storageBucket: process.env.VUE_APP_FIREBASE_STORAGE_BUCKET || 'env-not-set',
messagingSenderId: process.env.VUE_APP_FIREBASE_MESSAGING_SENDER_ID || 'env-not-set',
appId: process.env.VUE_APP_FIREBASE_APP_ID || 'env-not-set',
}
return firebaseConfig
}
// Initialize Firebase
firebase.initializeApp(getFirebaseConfig())
I'm using TypeScript, so I put that in a file called cloud-functions.ts` and after the above, I have:
export const postContactFunc = firebase.functions().httpsCallable('postContact')
Then, where I want to consume that function, I have:
// somewhere-else.ts
import {postContactFunc} from '#/services/cloud-functions'
Note that .env*.local is never checked in.
To remind myself what the file should be, I have this content in .env which is checked in:
$ cat .env
# REMEMBER:
# ----------------------------------------------------------
# DO NOT EDIT THIS FILE
#
# Edit .env.local or similar.
# ----------------------------------------------------------
# Get these from console - look on the _app_ area not the _project_ area.
VUE_APP_FIREBASE_API_KEY='not-set-yet'
VUE_APP_FIREBASE_AUTH_DOMAIN='not-set-yet'
VUE_APP_FIREBASE_DATABASE_URL='not-set-yet'
VUE_APP_FIREBASE_PROJECT_ID='not-set-yet'
VUE_APP_FIREBASE_STORAGE_BUCKET='not-set-yet'
VUE_APP_FIREBASE_MESSAGING_SENDER_ID='not-set-yet'
VUE_APP_FIREBASE_APP_ID='not-set-yet'
Here how you can do it.
Firstly, add dev.env to your project and add firebase variables.
FIREBASE_CONFIG: {
apiKey: "*********************************",
authDomain: "*****************************",
databaseURL: "****************************",
projectId: "******************************",
storageBucket: "**************************",
messagingSenderId: "**********************",
}
Import the file in dev.env.js
import merge from 'webpack-merge';
import env from './dev.env';
module.exports = merge(env, {
NODE_ENV: 'development'
}
Now, Initialize your firebase app with
import * as firebase from 'firebase';
firebase.initializeApp({VUE_APP_FIREBASE_CONFIG})
There you go! Firebase is set up for you
Hope this helps!
I am trying to create db with sequelize cli but getting this error.
ERROR: Access denied for user 'postgres'#'localhost' (using password: NO)
Here is my config.json file
{
"development": {
"username": "postgres",
"password": "postgres",
"database": "database_development",
"host": "127.0.0.1",
"dialect": "mysql"
},
"test": {
"username": "root",
"password": null,
"database": "database_test",
"host": "127.0.0.1",
"dialect": "mysql"
},
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
}
I can login with same user on phppgAdmin which i am currently using in config.json but its throwing the error. This is default user with all permissions and i had already created a db with ui.
Any help will be appreciated.
Okay so after messing around with config.json i figured out the solution. If you run the commands from sequalize cli documentation
sequalize cli doc then it will create the same config.json as in question. I have only modified the username and password.
The default dialect is mysql so you need to change it with postgres and it will work.