Firebase Writing with Security Rules - javascript

I have a Node app with a Firebase db with security like this :
{
"rules": {
".read": true,
"albums": {
".write": "auth != null",
}
}
}
I login like this:
var firebaseTokenGenerator = require('firebase-token-generator'),
firebase = require('firebase');
var tokenGenerator = new firebaseTokenGenerator('my key');
var token = tokenGenerator.createToken();
var albumRef = new firebase('https://glowing-fire-8113.firebaseio.com/albums');
albumRef.auth(token, function(err) {
if(err) {
console.log("Authentication failed!");
} else {
console.log("Login succeeded!");
}
});
I get "Login succeeded!" printed to the console.
Then, later on I call this function:
var addAlbum = function(album, callback) {
if(album["album"] && album["artist"] && album["image"]) {
albumRef.push().set(album);
callback(null);
}
callback(new Error("Album JSON was missing some items"));
};
But, I get this printed out:
FIREBASE WARNING: set at /albums/-JMU95j8W4Vz3kchhNzL failed: permission_denied
What is going on here? Am I doing authentication incorrectly?
For reference, I'm using
"firebase" : "1.0.14",
"firebase-token-generator" : "0.1.4",

Related

Vonage Sms Api Implementation at Node js

I try to use sms provider at node js to send sms to users but I have a problem at this point
I try so :
const { Vonage } = require('#vonage/server-sdk');
const vonage = new Vonage({
apiKey: 'VONAGE_API_KEY',
apiSecret: 'VONAGE_API_SECRET'
});
var recipient = 'TO_NUMBER';
vonage.message.sendSms(sender, recipient, message, (err, responseData) => {
if (err) {
console.log(err);
} else {
if (responseData.messages[0]["status"] === "0") {
console.dir(responseData);
} else {
console.log(
`Message failed with error: ${responseData.messages[0]["error-text"]}`
);
}
}
}
)
But I get this error:
TypeError: Cannot read properties of undefined (reading 'sendSms')

Can not access firebase Realtime database in my web app

I am developing firebase webapp and faced one problem.
I cannot access(read/write) firebase realtime database.
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
<script>
var config = {
apiKey: "AIzaSyCPYu_iqHjNoXjMfdMVLoYs5Graf2gdz7I",
authDomain: "sharing-is-caring-967c8.firebaseapp.com",
databaseURL: "https://sharing-is-caring-967c8.firebaseio.com",
projectId: "sharing-is-caring-967c8",
storageBucket: "sharing-is-caring-967c8.appspot.com",
messagingSenderId: "884406512169"
};
firebase.initializeApp(config);
firebase.auth().signInWithEmailAndPassword("myemail#gmail.com", "Qqqq123").then(function(info) {
var uid = info.uid;
firebase.database().ref('users/' + uid + '/userDetails').once('value').then(function(data) {
alert(data)
}).catch(function(error) {
alert(error.message);
});
}).catch(function(error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
alert(errorMessage);
// ...
});
</script>
SignInWithEmailAndPassword work fine.
And At database part,
once('value') function does not response anymore.
There is no success and no fail.
There isn't any error message and always silence
Rules of Realtime Database
{
"rules": {
".read": "auth != null",
".write": "auth != null",
"threads": {
"$tid": {
"messages": {
".indexOn": ["read", "date"]
}
}
}
}
}
Fire base Web Setup Guide Screenshot of my Firebase
Database structure
{
"users" : {
"BzucCBivhiRUogK5GeNrMV6k6M83" : {
"userDetails" : {
"displayName" : "Stanislav Sergeev",
"email" : "stanislav.atos#yahoo.com",
"notifications" : true,
"phoneNumber" : "",
"profile_image" : "",
"pushToken" : "ec7iJ7Mt7Lg:APA91bFb8NK2XeaLVUgr-DEPRFuLMDCk9_tIr_eHBjmuZPnHDUvFuCsj3kez4F5-Y9CjVXOY6VlsFi5nlazSZys4KBjwCKcpINbV5S2ZEaH09aWZ6sLga8dOja-UIp3Iz3DSOAb4bcH4"
}
}
}
}
I had same issue before and it is related with your Location.
Please try to use VPN.
So, based on the comments and your database structure:
Firstly, I don't understand what the following piece of rule is for?
"threads": {
"$tid": {
"messages": {
".indexOn": ["read", "date"]
}
}
}
Secondly, can you try just with the basic rules:
{
"rules": {
".read": "auth != null",
".write": "auth != null"
}
}
Thirdly, are you sure you are looged in? What do you get if you do
var uid = info.uid;
console.log(uid);
PS: note that the method you are using is apparently going to be deprecated, see
https://firebase.google.com/docs/reference/js/firebase.auth.Auth#signInWithEmailAndPassword
EDIT: This is working, I've reproduced your case. Note the return and the data.val().
firebase.auth().signInWithEmailAndPassword("azerty#nmw.com", "****")
.then(function (info) {
var uid = info.uid;
console.log(uid);
return firebase.database().ref('users/' + uid + '/userDetails').once('value');
})
.then(function (data) {
console.log(data.val());
})
.catch(function (error) {
alert(error.message);
});

Firebase Database Rules read problems

I have problems with read permission.
It will be helpfull if someone help me.
Note: the authentification work the user is loged...
Write permissions work but read permissions are denied.
I have this code:
{
"rules": {
"user":{
"$uid":{
".read": "auth.uid==$uid", // i try with ===
".write": "auth.uid==$uid" // i try with ===
}
}
}
}
This is the javascript code:
var userRef= db.ref().child("user/"+id);
userRef.on('child_added', data=>{
console.log(data.val());
});
userRef.on('child_changed', data=>{
console.log(data.val());
});
userRef.on('child_removed', data=>{
console.log(data.val());
});
function insertUser(){
db.ref("user/"+id).set({
email:email,
name:name
});
}
I also try with:
This make me a error on JavaScript
var userRef= db.ref("user").child(id);
I put ".read": true, but nothing happen yet!
I get the id in that way:
firebase.auth().onAuthStateChanged(
function(user){
if (user) {
if (user != null) {
user.providerData.forEach(function (profile) {
name = profile.displayName;
email = profile.email;
photoUrl = profile.photoURL;
id=user.uid;
var img = document.querySelector('#simg');
var p = document.querySelector('#p');
img.src=photoUrl;
p.innerHTML=name;
pemail.innerHTML=email;
});
}
}
Thanks!

Node project works locally but fails when installing via NPM?

I have this straightforward node project, with a main.js file when I run it locally node main.js it works fine. But when I do an npm install -g cli-tweet and then try to run it, it outputs this error :
/home/USER/.npm-global/bin/tweet: 1: /home/USER/.npm-global/bin/tweet: Syntax error: "(" unexpected
The package.json looks something like this :
{
"name": "cli-tweet",
"main": "main.js",
"bin": {
"tweet": "main.js"
},
[...]
}
Any idea on how to fix this ?
Edit 1:
The code for main.js
var OAuth = require('oauth').OAuth,
colors = require('colors'),
Twitter = require('twitter'),
fs = require('fs'),
get_args = require('cli-pipe');
var CONFIG_FILE = '.tweet.json',
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token',
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token',
OAUTH_VERSION = '1.0', HASH_VERSION = 'HMAC-SHA1';
var key = "XYZ",
secret = "XYZ", tweetText;
function getAccessToken(oa, oauth_token, oauth_token_secret, pin) {
oa.getOAuthAccessToken(oauth_token, oauth_token_secret, pin,
function (error, oauth_access_token, oauth_access_token_secret, results2) {
if (error && parseInt(error.statusCode) == 401) {
throw new Error('The pin number you have entered is incorrect'.bold.red);
}
var keys = {
'ACCESS_TOKEN_KEY': oauth_access_token,
'ACCESS_TOKEN_SECRET': oauth_access_token_secret
};
fs.open(CONFIG_FILE, "wx", function (err, fd) {
try {
fs.close(fd, function (err) {
});
} catch (e) {
}
});
fs.writeFileSync(CONFIG_FILE, JSON.stringify(keys));
console.log('Try echo "test" | cli-tweet'.cyan);
process.exit(1);
});
}
function getRequestToken(oa) {
oa.getOAuthRequestToken(function (error, oauth_token, oauth_token_secret, results) {
if (error) {
throw new Error(([error.statusCode, error.data].join(': ')).bold.red);
} else {
console.log(('https://twitter.com/oauth/authorize?oauth_token=' + oauth_token).underline.blue)
console.log('Enter the pin number here:'.bold.yellow);
var stdin = process.openStdin();
stdin.on('data', function (chunk) {
var pin = chunk.toString().trim();
getAccessToken(oa, oauth_token, oauth_token_secret, pin);
});
}
});
}
function tweet(userTokens) {
var client = new Twitter({
consumer_key: key,
consumer_secret: secret,
access_token_key: userTokens.oauth_access_token,
access_token_secret: userTokens.oauth_access_token_secret
});
console.log("Tweet :" + tweetText.bold.cyan);
if (tweetText.length > 0) {
client.post('statuses/update', {status: tweetText}, function (error, tweet, response) {
if (error) {
console.log("Error :" + JSON.stringify(error));
}
process.exit(1);
});
} else {
console.log("Pipe a tweet".bold.red);
}
}
var isConfig = process.argv[2];
if (isConfig === undefined || isConfig.toLowerCase() != "config") {
try {
var contents = fs.readFileSync(CONFIG_FILE).toString(), tokens = JSON.parse(contents);
} catch (e) {
console.log("Error: Try running 'tweet config' command".bold.red);
}
if (tokens != undefined && (tokens.ACCESS_TOKEN_KEY != undefined && tokens.ACCESS_TOKEN_SECRET != undefined)) {
try {
get_args(function (args) {
tweetText = args[2];
tweet({
"oauth_access_token": tokens.ACCESS_TOKEN_KEY,
"oauth_access_token_secret": tokens.ACCESS_TOKEN_SECRET
});
});
} catch (e) {
console.log("Error: Unexpected error while tweeting".bold.red);
}
} else {
console.log("Try running 'cli-tweet config' command".bold.red);
}
} else {
var oa = new OAuth(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, key, secret, OAUTH_VERSION, 'oob', HASH_VERSION);
getRequestToken(oa);
}
Edit 2 :
Running the code like this: node /home/USER/.npm-global/lib/node_modules/cli-tweet/main.js seems to work
1) Add folder bin
2) Add file bin/tweet with
#!/usr/bin/env node
require('../main.js');
3) change package.json
"bin": {
"tweet": "./bin/tweet",
}

Firebase security per user

I'm working on a site, using firebase
The security was:
{
"rules": {
"users": {
".read": true,
".write": true
}
}
}
So everyone can add their info, but none can access the main part.
But when someone now types this in the console:
ref = new Firebase("https://xxx.firebaseio.com/users");
ref.createUser({
email: email,
password: password
}, function(error, userData) {});
ref.authWithPassword({
email: email,
password: password
}, function(error, authData) {));
ref.remove();
all userdata will be removed.
All users have their own uid (e.g. simplelogin:58) and storageID (e.g. -Js18LFoT0SmFi2Iq4GP)
could I maybe do something with those? I really don't want anyone to be able to remove all of my user data, but I need to let the users edit their own info, and to remove their account when they'd like to.
Here's some of my code:
function register() {
var ref = new Firebase("https://fiery-heat-xxx.firebaseio.com/");
ref.createUser({
email: email,
password: password
}, function(error, userData) {
if (error) {
alert("Error creating user: " + error)
} else {
console.log("Successfully created user account with uid:", userData.uid);
var uid = userData.uid
var usersRef = new Firebase("https://fiery-heat-xxx.firebaseio.com/users/" + uid)
var newUser = usersRef.set({
faveShow1: "",
faveShow2: "",
faveShow3: "",
faveShow4: "",
faveShow5: "",
faveShow6: "",
faveShow7: "",
faveShow8: "",
faveShow9: "",
faveShow10: "",
uid: uid
});
//var key = newUser.key();
//console.log(key)
login();
}
});
}
function login() {
clear();
var ref = new Firebase("https://fiery-heat-xxx.firebaseio.com/");
ref.authWithPassword({
email: email,
password: password
}, function(error, authData) {
if (error) {
alert("Login Failed!" + error);
} else {
console.log("Authenticated successfully with payload:", authData);
thisAuthData = authData.uid;
var usersRef = new Firebase("https://fiery-heat-xxx.firebaseio.com/users/" + thisAuthData);
usersRef.on("value", function(snapshot) {
for (var i = 0; i < 1; i++) {
console.log(snapshot.val())
if (true) {
globalAuthData = snapshot.val();
//globalKey = amount;
var SS = snapshot.val()
show1 = SS.faveShow1;
show2 = SS.faveShow2;
show3 = SS.faveShow3;
show4 = SS.faveShow4;
show5 = SS.faveShow5;
show6 = SS.faveShow6;
show7 = SS.faveShow7;
show8 = SS.faveShow8;
show9 = SS.faveShow9;
show10 = SS.faveShow10;
//...//
}
}
}, function(errorObject) {
alert("The read failed: " + errorObject.code);
});
}
});
}
function removeUser() {
clear();
var ref = new Firebase("https://fiery-heat-xxx.firebaseio.com/");
var refSer = new Firebase("https://fiery-heat-xxx.firebaseio.com/users/" + thisAuthData)
ref.removeUser({
email: email,
password: password
}, function(error) {
if (error === null) {
alert("User removed successfully");
refSer.remove();
logoff();
} else {
console.log("Error removing user:", error);
}
});
}
function edit() {
clear();
var fredNameRef = new Firebase('https://fiery-heat-xxx.firebaseio.com/users/' + thisAuthData);
var onComplete = function(error) {
if (error) {
console.log('Synchronization failed');
} else {
console.log('Synchronization succeeded');
console.log(thisAuthData);
console.log(globalAuthData);
login();
}
};
if (document.getElementById("form1").value != "") {
var show1 = document.getElementById("form1").value;
}
var show2 = document.getElementById("form2").value;
var show3 = document.getElementById("form3").value;
var show4 = document.getElementById("form4").value;
var show5 = document.getElementById("form5").value;
var show6 = document.getElementById("form6").value;
var show7 = document.getElementById("form7").value;
var show8 = document.getElementById("form8").value;
var show9 = document.getElementById("form9").value;
var show10 = document.getElementById("form10").value;
fredNameRef.update({
faveShow1: show1,
faveShow2: show2,
faveShow3: show3,
faveShow4: show4,
faveShow5: show5,
faveShow6: show6,
faveShow7: show7,
faveShow8: show8,
faveShow9: show9,
faveShow10: show10,
}, onComplete);
}
function logoff() {
clear()
var ref = new Firebase('https://fiery-heat-xxx.firebaseio.com/')
ref.unauth();
//...//
}
}
and my securety rules:
{
"rules": {
"users": {
"$user_id": {
".write": "$user_id === auth.uid"
},
".read": true
}
}
}
But I can't register or update right now...
To make sure a user's information can only be edited by that user, you want to use auth.uid.
https://www.firebase.com/docs/web/guide/understanding-security.html
The most important built-in variable is auth. This variable is
populated after your user authenticates. It contains data about them
and auth.uid, a unique, alphanumeric identifier that works across
providers. The auth variable is the foundation of many rules.
{
"rules": {
"users": {
"$user_id": {
".write": "$user_id === auth.uid"
}
}
}
}
To make it a little more clear, auth.uid refers to the currently logged in user, and $user_id refers to the location in database. The $ points to the $location rule variable:
https://www.firebase.com/docs/security/api/rule/path.html
{ "rules": {
"users": {
"$user": {
".read": "auth.uid === $user",
".write": "auth.uid === $user"
}
}
}
}
When a user authenticates to a Firebase app, three things happen:
Information about the user is returned in callbacks on the client
device. This allows you to customize your app's user experience for
that specific user.
The user information returned contains a uid (a
unique ID), which is guaranteed to be distinct across all providers,
and to never change for a specific authenticated user. The uid is a
String that contains the name of the provider you're authenticating
with, followed by a colon and a unique id returned from the provider.
The value of the auth variable in your app's Security and Firebase
Rules becomes defined. This variable is null for unauthenticated
users, but for authenticated users it is an object containing the
user's unique (auth.uid) and potentially other data about the user.
This allows you to securely control data access on a per-user basis.

Categories

Resources