Getting code: "auth/network-request-failed" in Chrome Extension - firebase

I am getting following exception, while calling signInWithEmailAndPassword method of firebase:
Following is the code of my content.js file:
var config = {
apiKey: "******",
authDomain: "******",
databaseURL: "******",
projectId: "******",
storageBucket: "******",
messagingSenderId: "******"
};
var firebase_email = "firebase_email"; var firebase_password = "firebase_password";
firebase.initializeApp(config);
firebase.auth().signInWithEmailAndPassword(firebase_email, firebase_password)
.then((result) => console.log('Signin result', result))
.catch(function (error) {
var errorCode = error.code;
var errorMessage = error.message;
if (errorCode === "auth/wrong-password") {
alert("Wrong password for Firebase API in config.");
} else {
console.log(errorMessage);
}
console.log(error);
});
And following is the code of my manifest.json file:
{
"manifest_version": 2,
"name": "Firebase Auth in Chrome Extension Sample",
"description": "This sample shows how to authorize Firebase in a Chrome extension using a Google account.",
"version": "0.1",
"content_scripts": [{
"matches": [
"https://some websitename*",
],
"js": ["jquery-3.2.1.min.js", "firebase.js", "content.js"]
}],
"browser_action": {
"default_icon": "icon.png",
"default_title": "My Extension!"
},
"permissions": [
"identity",
"https://*/*",
"activeTab",
"background",
"storage"
],
"content_security_policy":"script-src 'self' https://www.gstatic.com/ https://*.firebaseio.com https://www.googleapis.com; object-src 'self'"
}
Strange, the same code works when I run it as JavaScript Application, see the below screenshot:
I tried various things, but could not identify the reason behind this.
Please guide me in right direction.
Thanks

Related

I got this Error from chokidar when running code with firebase

I'm running my firebase project and got this error in the terminal
This dependency was not found:
firebase in ./src/firebaseInit.js
To install it, you can run: npm install --save firebase
Error from chokidar (C:): Error: EBUSY: resource busy or locked, lstat 'C:\DumpStack.log.tmp
inside my firebaseInit.js
import firebase from 'firebase';
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
measurementId: "xxxxxxxxxxxxxxxxxx"
};
export default firebase.initializeApp(firebaseConfig);
and here's my package.json
{
"name": "mevnproject",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.25.0",
"core-js": "^3.6.5",
"firebase": "9.6.11",
"socket.io": "^4.4.1",
"vue": "^2.6.11",
"vue-chat-scroll": "^1.4.0",
"vue-google-charts": "^0.3.3",
"vue-router": "^3.5.3",
"vue2-google-maps": "^0.10.7",
"vuetify": "^2.6.2",
"vuex": "^3.6.2",
"vuex-persistedstate": "^4.1.0"
},
"devDependencies": {
"#mdi/font": "^6.5.95",
"#mdi/js": "^6.5.95",
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"material-design-icons-iconfont": "^6.1.1",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
I tried to uninstall and reinstall the firebase but still got the same error.
edit: in my components i've the script looks like this
<script>
import { db } from "../../firebaseInit";
export default {
data() {
return {
message: null,
};
},
methods: {
saveMessage() {
db.firestore()
.collection("chat")
.add({
message: this.message,
})
.then(() => {
console.log("Document Written");
})
.catch((error) => {
console.error(error);
});
},
},
};
</script>
From your package.json file we can see that you use the Firebase SDK version 9. You therefore need to adapt your firebaseInit.js file. I recommend exporting only the services you need, i.e. Firestore in your case (see your comment below).
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
measurementId: "xxxxxxxxxxxxxxxxxx"
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
export { db };
Then, in your component you do like:
import { db } from '../firebaseInit';
import { collection, addDoc } from 'firebase/firestore'; // Example
export default {
data() {
return {
message: null,
};
},
methods: {
saveMessage() {
addDoc(collection(db, 'chat'),
{
message: this.message,
})
.then(() => {
console.log("Document Written");
})
.catch((error) => {
console.error(error);
});
},
},
};
If you need to use several services, do as follows (for example):
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { getAuth } from "firebase/auth";
import { getStorage } from "firebase/storage";
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxxxxxxxx",
measurementId: "xxxxxxxxxxxxxxxxxx"
};
const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const auth = getAuth(firebaseApp);
const storage = getStorage(firebaseApp);
export { db, storage, auth };
and in the component
import { db, auth } from '../firebaseInit';
import { doc, getDoc } from 'firebase/firestore'; // Example
import { signInWithEmailAndPassword } from '#firebase/auth'; // Example
More details in the doc.

Getting a fetch error using redux toolkit and RTK-Query

I am using RTK-Query, and Redux-toolkit for this app, and I created an api-slice with createApi, as per the docs.
When I run a request to the backend, I get a "FETCH_ERROR"; however, when I run the same request using Axios, I get the data correctly from the backend, which leads me to believe I have an error in my code. I am just not sure where exactly it is.
Here is the error:
Object {
"api": Object {
"config": Object {
"focused": true,
"keepUnusedDataFor": 60,
"middlewareRegistered": true,
"online": true,
"reducerPath": "api",
"refetchOnFocus": false,
"refetchOnMountOrArgChange": false,
"refetchOnReconnect": false,
},
"mutations": Object {},
"provided": Object {},
"queries": Object {
"test(undefined)": Object {
"endpointName": "test",
"error": Object {
"error": "TypeError: Network request failed",
"status": "FETCH_ERROR",
},
"requestId": "BWOuLpOxoDKTzlUYFLW4x",
"startedTimeStamp": 1643667104869,
"status": "rejected",
},
},
"subscriptions": Object {
"test(undefined)": Object {
"QJSCV641RznGWyudGWuMb": Object {
"pollingInterval": 0,
"refetchOnFocus": undefined,
"refetchOnReconnect": undefined,
},
},
},
},
"test": Object {
"data": Array [],
},
}
Here is the test slice:
import { createSlice } from "#reduxjs/toolkit";
const testSlice = createSlice({
name: "test",
initialState: {
data: [],
},
reducers: {
getData: (state) => {
state;
},
},
});
export const { getData } = testSlice.actions;
export default testSlice.reducer;
Here is the apiSlice:
import { createApi, fetchBaseQuery } from "#reduxjs/toolkit/query/react";
export const apiSice = createApi({
reducerPath: "test",
baseQuery: fetchBaseQuery({ baseUrl: process.env.REACT_APP_backend_url }),
endpoints: (builder) => ({
test: builder.query({
query: () => "/test",
}),
}),
});
export const { useTestQuery } = apiSice;
I solved it by changing the backend URL to my current ipv4 (for expo development, otherwise just your whatever your backend URL is) address in my .env file, then deleting cache, and restarting my app. In my case I was using expo so, expo r -c, and it worked.

How to setup Firebase Offline Authentication with Nuxt SSR

I'm trying to build a Nuxt SSR application using #nuxtjs/firebase and #nuxtjs/pwa
My authentication works as expected when online but when when the user is offline I get this error in console
asyncToGenerator.js:8 Uncaught (in promise) t {code: "auth/network-request-failed", message: "A network error (such as timeout, interrupted connection or unreachable host) has occurred.", a: null}
Here's the screenshot of the error message:
This error freezes my app (my navigation hamburger menu doesn't respond)
PWA config in nuxt.config.js:
pwa: {
manifest: {
lang: 'en',
background_color: '#000000',
},
meta: {
nativeUI: true,
appleStatusBarStyle: 'black',
theme_color: '#000000',
},
config: {
enabled: true
},
workbox: {
importScripts: [
'/firebase-auth-sw.js'
],
dev: process.env.NODE_ENV === 'development',
}
}
Here is my Firebase config in nuxt.config.js
firebase: {
config: {
apiKey: process.env.apiKey,
authDomain: process.env.authDomain,
databaseURL: process.env.databaseURL,
projectId: process.env.projectId,
storageBucket: process.env.storageBucket,
messagingSenderId: process.env.messagingSenderId,
appId: process.env.appId,
measurementId: process.env.measurementId
},
services: {
auth: {
ssr: true,
initialize: {
// use authData from action in custom mutation
// onAuthStateChangedMutation: 'ON_AUTH_STATE_CHANGED_MUTATION',
onAuthStateChangedAction: 'onAuthStateChangedAction'
}
}
}
}
My onAuthStateChangedAction in store/index.js:
async onAuthStateChangedAction({ dispatch, commit }, { authUser }) {
if(!authUser) return commit(MUTATION_TYPE.REMOVE_USER)
// if user is already authenticated
// get authenticated user profile from firestore
dispatch('getUser', authUser)
if(process.browser) commit(MUTATION_TYPE.SET_TOKEN, localStorage.token)
}

Secure App-Engine Backend with GCP API-Gateway and Firebase Auth

My purpose is to secure my backend, which is deployed as GCP App Engine, with an API-Gateway, provided by Google, to only let Firebase authenticated users have access to it.
I set everything up, as stated in the documents:
API-Gateway config:
{
"swagger": "2.0",
"info": {
"title": "PROJECT_NAME",
"version": "1.0"
},
"securityDefinitions": {
"firebase": {
"authorizationUrl": "",
"flow": "implicit",
"type": "oauth2",
"x-google-issuer": "https://securetoken.google.com/PROJECT_ID",
"x-google-jwks_uri": "https://www.googleapis.com/service_accounts/v1/metadata/x509/securetoken#system.gserviceaccount.com",
"x-google-audiences": "PROJECT_ID"
}
},
"security": [
{
"firebase": [ ]
}
],
"paths": {
"/hello-spring": {
"get": {
"produces": [
"application/json"
],
"operationId": "helloSpring",
"parameters": [],
"responses": {
"200": {
"description": "OK",
"schema": {
"type": "string"
}
}
},
"x-google-backend": {
"address": "https://URI-TO-APP-ENGINE-SERVICE",
"path_translation": "APPEND_PATH_TO_ADDRESS"
"jwt_audience": "API_CREDENTIALS_FROM_IAP_APP_ENGINE_APP"
}
}
}
},
"definitions": {
"User": {
"properties": {
"creationTimestamp": {
"format": "date-time",
"type": "string"
},
"id": {
"format": "int32",
"type": "integer"
},
"name": {
"type": "string"
},
"updateTimestamp": {
"format": "date-time",
"type": "string"
},
"uuid": {
"type": "string"
}
},
"type": "object"
}
},
"x-components": {}
}
When I send a request - without a jwt token - to this api-gateways url, it correctly responds with
{
"message": "Jwt is missing",
"code": 401
}
Firebase jwt
"Default" firebase backend is used, no custom tokens are created. Firebase is used to create the JWT token. From the client following code snippet is used to receive a valid JWT:
final FirebaseAuth _auth = FirebaseAuth.instance;
....
final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
final GoogleSignInAuthentication googleSignInAuthentication = await googleSignInAccount.authentication;
final AuthCredential credential = GoogleAuthProvider.credential(
accessToken: googleSignInAuthentication.accessToken,
idToken: googleSignInAuthentication.idToken,
);
final UserCredential authResult = await _auth.signInWithCredential(credential);
final String token = await _auth.currentUser.getIdToken();
But as soon as I add the JWT (final String token in code above), which is created by a firebase client app and add it to the request header with
Authorization: Bearer TOKEN_CODE
gateway responds with
{
"code": 401,
"message": "Jwt verification fails"
}
The most detailed LOG I can see in GCP is:
response_code_detail: jwt_authn_access_denied{Jwt_verification_fails}
I also created a service account linked to this API-Gateway with following roles:
roles/appengine.appViewer
roles/iam.serviceAccountUser
roles/run.invoker
roles/apigateway.viewer
But still, the same error: "401 - Jwt verification fails". What am I missing,how can I see more details about this issue in GCP and what could be a solution?

Implementing Push notification using Strongloop

I am trying to use strongloop loopback sdk 2.0. I tried to use the following code https://github.com/strongloop/loopback-component-push/tree/master/example/server which is loopback version 1.7.0. But when i try compile with version 2.0, it throws me error
Error: The data in model-config.json is in the unsupported 1.x format.
I had also tried as per the strong loop tutorial, but still it does not work. Anyone has suggestion or sample code on how to implement PUSH notification using loopback 2.0?
Create 4 models application, installation, notification, push
In common/models/application.json
{
"name": "push",
"plural": "Push",
"base": "Model",
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
In common/models/installation.json
{
"name": "installation",
"base": "Installation",
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
In common/models/notification.js
{
"name": "notification",
"base": "Notification",
"properties": {},
"validations": [],
"relations": {},
"acls": [
{
"principalType": "ROLE",
"principalId": "$everyone",
"permission": "ALLOW",
"property": "sendMessage"
}
],
"methods": []
}
In common/models/push.json
{
"name": "push",
"plural": "Push",
"base": "Model",
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": []
}
server/datasource.json
...
...
"push": {
"name": "push",
"connector": "loopback-component-push",
"installation": "installation",
"notification": "notification",
"application": "application"
}
In common/models/notification.js
module.exports = function(Notification) {
var badge = 1;
//DEFINING A PROPERTY IN NOTIFICATION FOR SENDING PUSH MESSAGE
Notification.sendMessage = function(message, registrationId, from, callback) {
var app = this.app;
from = from? from:'COMPANY_NAME';
sendMessage(app, message, registrationId, from, callback);
}//sendMessage Notification method..
//FUNCTION FOR SENDING PUSH MESSAGE..
var sendMessage = function(app, message, registrationId, from, callback){
var Application = app.models.application;
var PushModel = app.models.push;
var note = new Notification({
expirationInterval: 3600, // Expires 1 hour from now.
badge: badge++,
// sound: 'ping.aiff',
message: message,
messageFrom: from
});
PushModel.notifyById(registrationId, note, function (err) {
if (err) {
console.error('Cannot notify %j: %s', registrationId, err.stack);
return callback(err);
}
console.log('Pushing notification to %j', registrationId);
callback(null, []);
});
}//sendMessage function
//Now registering the method
Notification.remoteMethod(
'sendMessage',
{
accepts: [{arg: 'message', type: 'string', required:true},
{arg: 'registrationId', type: 'string', required:true},
{arg: 'from', type: 'string', required:true}],
description: "Sending message from notification.."
}
)
}//module.exports
Now inside server/ folder create a file push-service.js
module.exports = function(app) {
var Notification = app.models.notification;
var Application = app.models.application;
var PushModel = app.models.push;
function startPushServer() {
PushModel.on('error', function(err) {
console.error('Push Notification error: ', err.stack);
});
// Pre-register an application that is ready to be used for testing.
// You should tweak config options in ./config.js
var loopbackApp = {
id: 'loopback-push-application',
userId: 'strongloop',
name: config.appName,
description: 'loopback Push Notification Service',
pushSettings: {
apns: {
certData: "APPLE CERT. DATA",
keyData: "APPLE KEY DATA",
pushOptions: {
// Extra options can go here for APN
},
feedbackOptions: {
batchFeedback: true,
interval: 300
}
},
gcm: {
serverApiKey: "PASTE YOUR GOOGLE GCM KEY HERE"
}
}
};
updateOrCreateApp(function(err, appModel) {
if (err) {
throw err;
}
console.log('Application id: %j', appModel.id);
});
function updateOrCreateApp(cb) {
Application.findOne({
where: {
id: loopbackApp.id
}
},
function(err, result) {
if (err) cb(err);
if (result) {
delete loopbackApp.id;
result.updateAttributes(loopbackApp, cb);
} else {
return registerApp(cb);
}
});
} //updateOrCreate function
Application.beforeSave = function(next) {
if (this.name === loopbackApp.name) {
this.id = 'loopback-push-application';
}
next();
};
Application.register(
loopbackApp.userId,
loopbackApp.name, {
description: loopbackApp.description,
pushSettings: loopbackApp.pushSettings
},
function(err, app) {
if (err) {
return cb(err);
}
return cb(null, app);
}
);
} //register App
} //startPushServer
startPushServer();
};
Now finally in server.js
....
....
//Adding push service to the backend..
require('./push-service')(app);
....
Now run the loopback server open api explorer and go to NOTIFICATION->SendMessage method and type any message and it will send push notification on connected devices.
NOTE: You also need to configure push services from android/iphone to enable sending push application. For detail check loopback documentation.
Please check out this example - https://github.com/strongloop/loopback-component-push/tree/master/example/server-2.0

Resources