HTTP request: PUT 401 (Unauthorized) - angularjs

I start to learn how to use firebase in my app. I follow the instruction in angular website and set the snippet in the index.html like:
<!-- The codes to add firebase -->
<script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script>
<!-- The core firebase client (required) -->
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-app.js"></script>
<!-- firebase-auth - Firebase Authentication (optional) -->
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-auth.js"></script>
<!-- firebase-database - The Firebase Realtime Database (optional) -->
<script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js"></script>
<script>
var config = {
apiKey: ...,
authDomain: ...,
databaseURL: "https://...",
storageBucket: "...",
};
firebase.initializeApp(config);
</script>
And then I try to use HTTP request to put data like:
submitForm(personalInfo: PersonalInfo, educationsInfo: Education[], experiencesInfo: Experience[]): Observable<string>{
let body = JSON.stringify({personalInfo, educationsInfo, experiencesInfo});
let headers = new Headers({'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers});
console.log(body);
let url = this.firebaseUrl + 'apply-form.json';
return this.http.put(url, body)
.map((response) => {
return response;
})
.catch(this.handleError);
}
However, I got the following error:
PUT https://XXX.firebaseio.com/apply-form.json 401 (Unauthorized)
I don't know what the problem is. I'm new in using firebase and really need someone to help me. Thank you!

Your Firebase Database is by default only writeable by authenticated users. See the warning in the first blue box on the page on saving data to the database.
To work around this you can of course configure the security rules of your database to allow public access. But while that is typically fine during development, it's a bad idea as you get your app ready for release to people other than yourself.
The proper way to post data securely is to require the user to sign in with Firebase Authentication and then use that information to ensure they can only access data that they're authorized to. By using HTTP to access the Firebase Database, you've made this more difficult for yourself than needed. I recommend using the Firebase JavaScript SDK for both authentication and accessing the database.

Related

React Firebase Auth initialization problem - No Firebase App '[DEFAULT]' has been created

Feature: I want to automatically sign in with the user's profile if he or she successfully signed-in the previous web session.
Problem: I'm getting "No Firebase App" error in my React project while trying to execute firebase.auth(). The main firebase object initialization is triggered at the end of my index.js file with firebase.initializeApp(firebaseConfig). From what I can gather the firebase instance isn't properly initialized while executing authentication portion of code. Nomrally I would expect to perform the auth on the callback from the init function but there's none. So my question is what would be the best place to do the aforementioned automatic authentication/signing-in during the webpage load? Currently the authentication is performed on componentDidMount which obviously doesn't do the trick...
componentDidMount = () => {
if (localStorage.getItem("auth") == "google")
this.authenticate();
};
authenticate = () => {
var provider = new firebase.auth.GoogleAuthProvider();
firebase // <- exception
.auth()
.signInWithPopup(provider)
.then(function (result) {
// #ts-ignore
var token = result.credential.accessToken;
user = result.user;
localStorage.setItem("auth", "google");
Add in the body of your index.html:
<!-- Firebase App (the core Firebase SDK) is always required and must be listed first -->
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-app.js"></script>
<!-- Add analytics if you need them -->
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-analytics.js"></script>
<!--Add firebase dependencies you need (here i added auth and firestore) -->
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/8.1.1/firebase-firestore.js"></script>
<script>
// TODO: Replace the following with your app's Firebase project configuration
// For Firebase JavaScript SDK v7.20.0 and later, `measurementId` is an optional field
var firebaseConfig = {
// ... You can find config in settings, scroll down and click on cdn
// I use cdn since it allows both external and firebase hosting
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
</script>
Then you are ready to go

TypeError: firebase.auth() is not a function

I am setting a new firebase project. In the project I try to use firebase.auth() to create a new user with user email and password. However, when I use firebase serve and do a post request with the link in postman, i get an error which says firebase.auth is not a function.
I believe that there are questions regarding this issue, however I tried all the solutions that they have provided but none of the worked for me.
I tried:
- Adding require firebase/auth
- Deleting node modules and reinstalling firebase and firebase functions
- Import firebase and functions in different order
- Install firebase and functions in a different order
- Create a new project and install firebase and functions from scratch
const firebase = require('firebase');
const config = {
apiKey: "xxxxx,
authDomain: "xx",
databaseURL: "xxxx",
projectId: "xxxx",
storageBucket: "xxxx",
messagingSenderId: "xxx",
appId: "xxxxxx"
};
firebase.initializeApp(config);
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const app = require('express')();
admin.initializeApp();
//Signup route
app.post('/signup', (req, res) => {
const newUser = {
email: req.body.email,
password: req.body.password,
confirmPassword: req.body.confirmPassword,
handle: req.body.handle,
}
// TODO: validate data
firebase.auth().createUserWithEmailAndPassword(newUser.email, newUser.password)
.then(data => {
return res.status(201).json({ message: `user ${data.user.uid} signed up successfully`})
})
.catch(err => {
console.error(err);
return res.status(500).json({error: err.code});
});
});
Expected results: get status 201 on postman and created new user in firebase
Actual results: TypeError: firebase.auth is not a function. In the console and postman.
You should understand the difference of Firebase JavaScript SDK and Firebase Admin SDK for Node.
The Firebase JavaScript SDK is for the client side.
Firebase Admin SDK is for the server side(like the Cloud Functions).
So in your case, you should use admin.auth().createUser() .
See:
https://firebase.google.com/docs/web/setup
https://firebase.google.com/docs/admin/setup
It seems you want to instantiate the application using the client sdk instead of the server.
You need to use a private key instead, to get one go to your firebase console -> Project Overview -> Service accounts -> Generate new private key
then after you download and include the key in your project:
const admin = require('firebase-admin')
const serviceAccount = require('your_firebase_key/path/goes/here')
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
})
Good luck!
I was able to resolve this issue by installing firebase as well as firebase-tools. I had initially only installed firebase-tools. Try running npm i firebase, restart the server firebase serve and see if you're still having the issue.

using axios with firebase , do i have to install firebase from npm?

I have setup axios in my project like so,
In my src/ folder created a axios.js file that looks like so:
import axios from 'axios';
const instance = axios.create({
baseURL : 'https://myprojectname-11651.firebaseio.com/'
});
export default instance;
Then in my main component where i use axios i use it like so:
import axios from '../axios.js';
// removing code thats not necessary for this example
componentDidMount() {
// alert();
axios.get('/habits/badHabits.json')
.then( (resp) => {
console.log(resp);
})
}
I get a 401 error in my console, The dashboard for firebase seems to have changed from a year back and i am not unable to use axios with firebase like i used it over a year ago.
My database look like so:
How exactly do i use axios with firebase ? do i have to install firebase from npm ?
Yes you have to install firebase in your project using npm. It is initial process to configure your app with firebase. Then you have to add firebase credentials like
<script>
// Initialize Firebase
var config = {
apiKey: <YOUR_APP_KEY>,
authDomain: "<YOUR_APP_DOMAIN>",
databaseURL: "<YOUR_DATABASE_URL>",
projectId: "<YOUR_PROJECT_ID>",
storageBucket: "<YOUR_STORAGE_URL>",
messagingSenderId: "<YOUR_MESSENGER_ID>"
};
firebase.initializeApp(config);
</script>
Instruction:- You can find the above code here,
Firebase console > Project Settings (This is the gear icon opposite of "Project overview" text) > Your apps > (On same page you will have three choices to either use it for android, ios , web) > Add Firebase to your web app
Now that you have added these things you just need to use firebase functions to access the firebase storage, authentication, database.
Here is the link where you can find all your details
https://firebase.google.com/docs/web/setup
It will help you.
I have the feeling you are mixing up the Real Time Database REST API and the Firestore one.
From the picture in your question, you are using Firestore.
And for Firestore, "all REST API endpoints exist under the base URL https://firestore.googleapis.com/v1beta1/", see the doc here.
On the other hand, as detailed here, the Real Time DB REST API endpoints have a base URL like https://docs-examples.firebaseio.com/rest/.... which is similar to the URL in your question.

Set firebase messaging issue messaging/only-available-in-sw

I'm trying to set up firebase in my angularJS project to use background notification and in app notification.
What I did:
install firebase by npm install --save firebase
add manifest.json with sender id to root directory
put this scripts in <head>:
<script src="node_modules/firebase/firebase-app.js"></script>
<script src="node_modules/firebase/firebase-messaging.js"></script>
Add this script just after <body> is open:
<script>
var config = {
apiKey: "AIzaSyDAVuWKUL-aPoGasdEi-EMR7uFN1gtgk0s",
authDomain: "testproject-d71.firebaseapp.com",
databaseURL: "https://testproject-12d71.firebaseio.com",
projectId: "testproject-12d71",
storageBucket: "",
messagingSenderId: "123128116401"
};
firebase.initializeApp(config);
</script>
Add this script at the end of <body>
<script src="js/configFcm.js"></script>
which is:
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
const notificationTitle = 'Title';
const notificationOptions = {
body: 'body.',
icon: '/firebase-logo.png'
};
return self.registration.showNotification(notificationTitle,
notificationOptions);
});
That's all what I did I didn't configure in app notification yet only background ones. I got error in console:
Uncaught code:
"messaging/only-available-in-sw"
message:
"Messaging: This method is available in a service worker context (messaging/only-available-in-sw)."
stack:
"FirebaseError: Messaging: This method is available in a service worker context. (messaging/only-available-in-sw)
What is service-worker? Is it just client side? I'm executing this scripts from index.html so I'm confused.
You are currently using default firebase library. Instead, use it with the angularfire library which will take care of most of the things related to firebase.
Below is the basic tutorial to use firebase with angularfire:
Initialisation steps are fine.
Inject angularfire in your index.html.
<!-- AngularFire -->
<script src="https://cdn.firebase.com/libs/angularfire/2.3.0/angularfire.min.js"></script>.
Register firebase as a module in the application.
var app = angular.module("sampleApp", ["firebase"])
Now you are good to go.
Please follow the references below for more information on how to use angularfire with firebase.
https://github.com/firebase/angularfire/
https://code.tutsplus.com/tutorials/creating-a-web-app-from-scratch-using-angularjs-and-firebase--cms-22391

Twilio push notification for programmable chat failed

I'm working on an app that uses the Twilio Programmable Chat API using node.js and angular js. I have enabled push configuration inside twilio chat instance. And i have created push credentilals in twilio with the firebase secret key. After this i have fetched the twilio token using chatGrant with the twilio credential sid. I have included the firebase.js file and initialised firebase. After this I got permission from user to show notification. This all works fine. But when I am trying to get device token to register with chatclientinstance, it is getting failed.
Here is my code which initialising the firebase and taking permission,
var config = {
apiKey: "my_key",
authDomain: "example.firebaseapp.com",
databaseURL: "https://example.firebaseio.com",
projectId: "example",
storageBucket: "example.appspot.com",
messagingSenderId: "861813283864"
};
if (firebase) {
firebase.initializeApp(config);
console.log("firbase initialized.");
}
if (firebase && firebase.messaging()) {
// requesting permission to use push notifications
firebase.messaging().requestPermission().then(() => {
// getting FCM token
console.log("got permission for showing notification.");
firebase.messaging().getToken().then((fcmToken) => {
// continue with Step 7 here
console.log("got fcm token.",fcmToken);
// ...
// ...
}).catch((err) => {
// can't get token
console.log("error in getting token for notification.",err);
});
}).catch((err) => {
// can't request permission or permission hasn't been granted to the web app by the user
console.log("error in getting permission for notification.",err);
});
} else {
// no Firebase library imported or Firebase library wasn't correctly initialized
console.log("no Firebase library imported or Firebase library wasn't correctly initialized");
}
}
I got this in console,
firbase initialized.
got permission for showing notification.
The script has an unsupported MIME type ('text/html').
Failed to load resource: net::ERR_INSECURE_RESPONSE firebase-messaging-sw.js
error in getting token for notification.
e {code: "messaging/failed-serviceworker-registration", message: "Messaging: We are unable to register the default s…). (messaging/failed-serviceworker-registration).", browserErrorMessage: "Failed to register a ServiceWorker: The script has an unsupported MIME type ('text/html').", stack: "FirebaseError: Messaging: We are unable to registe…o/polyfills.bundle.js:3152:35)↵ at <anonymous>"}
I have did everything as twilio docs says at PUSH NOTIFICATIONS ON WEB
But I did not added "firebase-messaging-sw.js" in my server. Is there any need to add this js file or twilio will automatically create and initialise it?
Please find me a solution for this. Thanks in advance.
I found this confusing too, since the docs don't explain what the notification support actually does. The code you included (from their chat SDK docs) only does two basic things:
client.setPushRegistrationId('fcm', fcmToken) makes sure the browser is registered with the FCM service and requests Twilio Programmable Chat notifications.
messaging.onMessage(function(payload{client.handlePushNotification(payload);}); seems to do very little--it simply lets the Chat client emit an event when FCM receives a message.
What it does not do, though, is create a service that listens for notifications. That's where the missing file comes in. First, create this file, firebase-messaging-sw.js somewhere. I used the following example from the Firebase docs:
// firebase sample code snippets from https://firebase.google.com/docs/cloud-messaging/js/client
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/5.0.4/firebase-messaging.js');
// Initialize the Firebase app in the service worker by passing in the essagingSenderId.
console.log("Initializing service worker...");
firebase.initializeApp({
messagingSenderId: "<FILL IN FROM YOUR FIREBASE CONFIG>"
});
// Retrieve an instance of Firebase Messaging so that it can handle background messages.
var messaging = firebase.messaging();
// Listen for push messages and create notifications
messaging.setBackgroundMessageHandler(function(payload) {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
// Customize notification here
var notificationTitle = "My Notification Title";
var notificationOptions = {
body: "My Notification Text"
};
return self.registration.showNotification(notificationTitle, notificationOptions);
});
This is a basic service worker that listens for notifications and then displays them.
Next, from the error message, you might have noticed that FCM is looking for this file to be served from your web root directory. If that's not the case, tweak your Twilio code slightly to look for this service worker at a specified URL (from https://stackoverflow.com/a/41701594/4006592):
var messaging = firebase.messaging();
if (messaging) {
navigator.serviceWorker.register("<URL FOR firebase-messaging-sw.js>").then(function(registration) {
messaging.useServiceWorker(registration);
// requesting permission to use push notifications
messaging.requestPermission().then(function() {
...
});
});
}
With the above change, you can explicitly specify where firebase-messaging-sw.js is located, and FCM/Twilio Chat will then work as expected.

Resources