Firebase - Why is it not pulling my information? [duplicate] - javascript

I'm relatively new to coding and am having trouble.
I have this code to send data to firebase
app.userid = app.user.uid
var userRef = app.dataInfo.child(app.users);
var useridRef = userRef.child(app.userid);
useridRef.set({
locations: "",
theme: "",
colorScheme: "",
food: ""
});
However, I keep getting the error:
FIREBASE WARNING: set at /users/(GoogleID) failed: permission_denied
2016-05-23 22:52:42.707 firebase.js:227 Uncaught (in promise) Error: PERMISSION_DENIED: Permission denied(…)
When I try to look this up it talks about rules for Firebase, which seems to be in a language that I haven't learned yet (or it is just going over my head). Can someone explain what is causing the issue? I thought it was that I was asking for it to store email and user display name and you just weren't allowed to do this, but when I took those out I still had the same problem. Is there a way to avoid this error without setting the rules, or are rules something I can teach myself how to write in a day, or am I just way out of my league?
Thanks for any help!

By default the database in a project in the Firebase Console is only readable/writeable by administrative users (e.g. in Cloud Functions, or processes that use an Admin SDK). Users of the regular client-side SDKs can't access the database, unless you change the server-side security rules.
You can change the rules so that the database is only readable/writeable by authenticated users:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
See the quickstart for the Firebase Database security rules.
But since you're not signing the user in from your code, the database denies you access to the data. To solve that you will either need to allow unauthenticated access to your database, or sign in the user before accessing the database.
Allow unauthenticated access to your database
The simplest workaround for the moment (until the tutorial gets updated) is to go into the Database panel in the console for you project, select the Rules tab and replace the contents with these rules:
{
"rules": {
".read": true,
".write": true
}
}
This makes your new database readable and writeable by anyone who knows the database's URL. Be sure to secure your database again before you go into production, otherwise somebody is likely to start abusing it.
Sign in the user before accessing the database
For a (slightly) more time-consuming, but more secure, solution, call one of the signIn... methods of Firebase Authentication to ensure the user is signed in before accessing the database. The simplest way to do this is using anonymous authentication:
firebase.auth().signInAnonymously().catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
And then attach your listeners when the sign-in is detected
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var isAnonymous = user.isAnonymous;
var uid = user.uid;
var userRef = app.dataInfo.child(app.users);
var useridRef = userRef.child(app.userid);
useridRef.set({
locations: "",
theme: "",
colorScheme: "",
food: ""
});
} else {
// User is signed out.
// ...
}
// ...
});

I was facing similar issue and found out that this error was due to incorrect rules set for read/write operations for real time database. By default google firebase nowadays loads cloud store not real time database. We need to switch to real time and apply the correct rules.
As we can see it says cloud Firestore not real time database, once switched to correct database apply below rules:
{
"rules": {
".read": true,
".write": true
}
}
Note:
Be careful with the rules. By setting read and write to true makes database vulnerable to praying eyes.
Read more:
https://firebase.google.com/docs/database/security

Go to the "Database" option you mentioned.
There on the Blue Header you'll find a dropdown which says Cloud Firestore Beta
Change it to "Realtime database"
Go to Rules and set .write .read both to true
Copied from here.

Go to database, next to title there are 2 options:
Cloud Firestore, Realtime database
Select Realtime database and go to rules
Change rules to true.

OK, but you don`t want to open the whole realtime database!
You need something like this.
{
/* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
"rules": {
".read": "auth.uid !=null",
".write": "auth.uid !=null"
}
}
or
{
"rules": {
"users": {
"$uid": {
".write": "$uid === auth.uid"
}
}
}
}

Open firebase, select database on the left hand side.
Now on the right hand side, select [Realtime database] from the drown and change the rules to:
{
"rules": {
".read": true,
".write": true
}
}

Another solution is to actually create or login the user automatically if you already have the credentials handy. Here is how I do it using Plain JS.
function loginToFirebase(callback)
{
let email = 'xx#xx.com';
let password = 'xxxxxxxxxxxxxx';
let config =
{
apiKey: "xxx",
authDomain: "xxxxx.firebaseapp.com",
projectId: "xxx-xxx",
databaseURL: "https://xxx-xxx.firebaseio.com",
storageBucket: "gs://xx-xx.appspot.com",
};
if (!firebase.apps.length)
{
firebase.initializeApp(config);
}
let database = firebase.database();
let storage = firebase.storage();
loginFirebaseUser(email, password, callback);
}
function loginFirebaseUser(email, password, callback)
{
console.log('Logging in Firebase User');
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function ()
{
if (callback)
{
callback();
}
})
.catch(function(login_error)
{
let loginErrorCode = login_error.code;
let loginErrorMessage = login_error.message;
console.log(loginErrorCode);
console.log(loginErrorMessage);
if (loginErrorCode === 'auth/user-not-found')
{
createFirebaseUser(email, password, callback)
}
});
}
function createFirebaseUser(email, password, callback)
{
console.log('Creating Firebase User');
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(function ()
{
if (callback)
{
callback();
}
})
.catch(function(create_error)
{
let createErrorCode = create_error.code;
let createErrorMessage = create_error.message;
console.log(createErrorCode);
console.log(createErrorMessage);
});
}

PermissionDenied can also appear if provided Firebase project ID is incorrect.
See this guide to check your project ID:
Firebase console: Click settings Project settings. The project ID is displayed in the top pane.

If you are attempting to reuse an old project in firebase, due to free account restrictions, then your database rules are probably outdated.
In my case, I was getting error 401 Unauthorized and it solved when I set both read and write rules equal to true.
Thanks for this great community!
Much respect from Brazil!

i was also having the same problem. make sure that you are using the real-time database instead of the cloud. then change rules to allow access to all users as follows
{
"rules": {
".read": true,
".write": true
}
}
by default the firestore database only allows admins to read and write from the database thus the read/write rules will be set to false.

Related

How can I grant authenticated users access to other properties in Firebase and React Native? [AxiosError: Request failed with status code 401]

I'm really new to Firebase and React Native and I'm building a user-based app. In Firebase, users are authenticated with a token and they seem to be restricted when it comes to personal properties. As far as I understood, how it works is, users are automatically assigned with both token and userId. And if you want to add additional info you create an object in the Realtime Database to store users and you assign said users with the ID they belong.
So what I have is a couple of users and I have two user objects with some properties.
enter image description here
I'm using Axios to do a GET request only for authenticated users:
` const authCtx = useContext(AuthContext);
const token = authCtx.token;
// console.log(token);
useEffect(() => {
axios
.get(
"https://fbapp-(heart)-default-rtdb.firebaseio.com/users.json?auth=" +
token
)
.then((response) => {
console.log(response.data);
});
}, [token]);`
My firebase rule is:
` {
"rules":{
".write": "auth.uid != null ",
".read" : "auth.uid != null"
}
}`
The issue here is that with those rules each authenticated user gets access to the Realtime DB. So after some research, I've found out that I can set my rules like so:
` {
"rules": {
"users":{
"$user_id":{
".write": "auth.uid === $user_id",
".read": "auth.uid === $user_id"
}
}
}
}`
As far as I understood that rule's for all the users, that have the user_id property and only those users with the current UID can access them. But that's when I get the following error:
WARN:Possible Unhandled Promise Rejection (id: 0):
[AxiosError: Request failed with status code 401]
The documentation says that auth variable contains uid (A unique user ID assigned to the requesting user). The user is authenticated successfully but still doesn't work. Please help!
Thank you in advance^^
UPDATE:I've found a way to make it work, but I think there's a security issue with the solution. Instead of naming the users "user1, user2,..." I tried naming them with the UID and change my url to:
"https://fbapp-(not here)-default-rtdb.firebaseio.com/users/"+{user_id}+ ".json?auth="+{token}
Not sure if that is correct.
Use access_token to authenticate REST requests.
`https://<DATABASE_NAME>.firebaseio.com/users.json?access_token=${token}`
See Authenticate with an access token for details.

How to pass Auth token in FireStore in Web app

I have developed a single crud project(Login screen and crud operation screen HTML) and hosted on firebase hosting. where User signing with email and password, I am using firebase signing with email and password and its working as expected.
But now issue is I want to secure backend with auth but its not passing auth in setDoc() deleteDoc() etc, My requirement is without auth. no one should do any operation on database.
import { doc, setDoc } from "firebase/firestore";
await setDoc(doc(db, "cities", "LA"), {
name: "Los Angeles",
state: "CA",
country: "USA"
});
below rules are working but its not secured for production env. :
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true
}
}
}
If set rules like below it give me insufficient permission error. I don't know how to pass UID in setDoc() or any operation.
allow read, write: if request.auth != null
Update : If i put below code before setDoc() below code is not executing because currentUser has user data.
function addCity(){
if (!firebase.auth().currentUser) {
// this code not executing because user is signed
alert("Login required");
window.href = "login.html";
return;
}
// i can print UID and it is showing means user is logged.
await setDoc(doc(db, "cities", "LA"), {
name: "Los Angeles",
state: "CA",
country: "USA"
});
}
This is in detail covered in the Firebase documentation on Security & Rules, which I would recommend you to check out.You can secure your data with Security Rules,Firebase Security Rules are evaluated and based on that the rules language it is validated whether the current user can access your data.
Security Rules give you access to a set of server variables to check your rules against. The most commonly used one is the auth variable which lets you check against the currently authenticated user. You can also create wildcard variables with the $, which acts as a route parameter creating.
{ "rules": { "users": { // users can read and write their own data, but no one else. "$uid": { ".read": "auth.uid == $uid", ".write": "auth.uid == $uid" } } } }
You can also check the feature called Firebase App Check, it will let you limit access to your Realtime Database to only those coming from iOS, Android and Web apps that are registered in your Firebase project.
You can combine this with the user authentication based security described above, so that you have another shield.
Also check these similar examples below:
How to prevent unauthorized access to Firebase database
How to prevent users from changing the Database data
Allow only authenticated users to modify database data
Finally,
I found solution. I was using different version library of firebase. like I was using web v8 library for login and modular lib for database access. I just moved all firebase SDK to same version and modular.

Firebase security rules data.exists() not working

Following the post here I created a simple security rule and cloud function that gets called to see if a username already exists. The problem is that the security rule write check always passes and just sets the new value in that location (/username_lookup/user1).
When I try to write at this location using the realtime database rules simulator it works as expected, i.e. the write is blocked.
Can someone spot the problem?
The firebase security rule
"rules": {
"username_lookup": {
"$username": {
// not readable, cannot get a list of usernames!
// can only write if this username is not already in the db
".write": "!data.exists()",
// can only write my own uid into this index
".validate": "newData.val() === auth.uid"
}
}
}
And the cloud function
var fb = admin.database().ref();
createUser(uid, username);
function createUser(userId, usrname) {
fb.child('username_lookup').child(usrname).set(userId, function(unerr) {
if(unerr) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({error: "the_error_code" }));
}
});
}
Screenshot of the username_lookup object/index
You Cloud Functions access the Firebase database through:
var fb = admin.database().ref();
As you can see, the module is admin which indicates that you're using the Firebase Admin SDK. One of the key traits of the Firebase Admin SDK is:
Read and write Realtime Database data with full admin privileges.
source: https://firebase.google.com/docs/admin/setup
So the Admin SDK actually bypasses your security rules.
It's also a pretty bad practice to use an error handler for basic flow control.
Instead, use a Firebase transaction to read/write the location with the name in an atomic way:
fb.child('username_lookup').child(usrname).transaction(function(value) {
if (value) {
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({error: "the_error_code" }));
return; // abort the transaction
}
else {
return userId;
}
});

Fetch database data from firebase to my blog without auth

I've followed the guide from a documentation of firebase on how to fetch the data.
I try to play around with the:
sample of firebase here
However, to get database data need to auth. Is there anyway just only fetch like feed from firebase without auth? I need to read on my own blog to be read for public.
Please..help me to solve this issue.
Thanks.
You could set your rules to this:
{
"rules": {
".read": "true",
".write": "auth != null"
}
}
But this means anyone who has access the database can read all the data.
In your code you would do something like this:
firebase.database().ref("blogItems").on('value', function(snapshot) {
console.log(snapshot.val());
});
If your setup is like this:
firebase-database-123
|
|_blogItems
|
|_entry1
|
|_entry2
I would recommend you get familiar with Firebase Database Security Rules.
These are the ones which dictate who can read/write into the Firebase Database.
All new projects starts with the rules
{
rules: {
.read: auth != null,
.write: auth != null
}
}
This means anyone who isn't authenticated won't be able to read or write in our database.
To achieve what you might need without compromising other data you may do something like the following:
{
rules: {
.read: auth != null,
.write: auth != null
blogEntries: {
.read: true,
.write: auth != null
}
}
}
By doing this you are allowing everyone to read the data inside blogEntries, and this means ALL the data inside, while if someone wants to write data to blogEntries they should be authenticated.
I recommend watching The key to Firebase Security to further understand what can be achieved and how Security Rules work.
Yes, you can get the data without authenticating, but it's not recommended. I did the following setup in the Firebase.
Step 1
Click on Realtime Database's GET STARTED
Step 2
Click on second option start in test mode you can access data without auth
or
Add following lines in rules
{
"rules": {
".read": true,
".write": true
}
}

Firebase rules doesn't work on server request but work on Simulator

{
"rules": {
"verifications": {
// Can only request verification code if it's been one minute than previous request.
"$phoneNumber": {
".validate": "!data.exists() || (newData.child('timestamp').val() > data.child('timestamp').val() + 60000)"
}
},
".read": true,
".write": true
}
}
This rules work on the Firebase Simulator and the writing process got rejected if the timestamp is not later by 1 minute. But when I tried to write from the server, it passed the rules and the writing process was allowed.
The code:
var data = {
timestamp: 1468664575179
};
var phoneNumber = '+14253452';
firebase.database().ref(`verifications/${phoneNumber}`).set(data, function(err) {
console.log(err);
});
I wonder why the writing process was rejected on the Firebase Simulator but allowed when the request came from the server.
This doesn't give the reason:
Firebase Security Rules work in simulator, but not in code
This depends on how you initialize the connection.
If your server is running under an unrestricted service account, it will be running with administrative permissions and bypassing the security rules.
// Initialize the app with a service account, granting admin privileges
firebase.initializeApp({
databaseURL: "https://databaseName.firebaseio.com",
serviceAccount: "path/to/serviceAccountCredentials.json"
});
See the authentication section of the Firebase server docs.
The same section of the docs explains how you can override this behavior, by giving a uid to the server process when you initialize:
// Initialize the app with a custom auth variable, limiting the server's access
firebase.initializeApp({
databaseURL: "https://databaseName.firebaseio.com",
serviceAccount: "path/to/serviceAccountCredentials.json",
databaseAuthVariableOverride: {
uid: "my-service-worker"
}
});

Categories

Resources