Firebase auth emulator was blocked - node.js

I got this error when I using local firebase emulator.
blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Private-Network' header was present in the preflight response for this private network request targeting the local address space.
Initializing firebase.
export const firebaseConfig = {
apiKey: process.env.NEXT_PUBLIC_FIREBASE_APP_APIKEY,
authDomain: process.env.NEXT_PUBLIC_FIREBASE_APP_AUTHDOMAIN,
databaseURL: process.env.NEXT_PUBLIC_FIREBASE_APP_DATABASEURL,
projectId: process.env.NEXT_PUBLIC_FIREBASE_APP_PROJECT_ID,
storageBucket: process.env.NEXT_PUBLIC_FIREBASE_APP_STORAGE_BUCKET,
messagingSenderId: process.env.NEXT_PUBLIC_FIREBASE_APP_MESSAGING_SENDER_ID,
appId: process.env.NEXT_PUBLIC_FIREBASE_APP_APP_ID,
measurementId: process.env.NEXT_PUBLIC_FIREBASE_APP_MEASUREMENT_ID
};
const firebase = initializeApp(firebaseConfig);
const store = initializeFirestore(firebase, {ignoreUndefinedProperties: true})
const db = getDatabase(firebase);
const auth = getAuth(firebase);
const storage = getStorage(firebase);
// #ts-ignore
if (process.env.NEXT_PUBLIC_MODE === 'emulator' && !auth.config.emulator) {
connectDatabaseEmulator(db, "localhost", 9000);
connectFirestoreEmulator(store, "localhost", 8080);
connectAuthEmulator(auth, 'http://localhost:9099');
connectStorageEmulator(storage, 'localhost', 9199);
}
export { store, db, auth, storage };
export default firebase;
I got error when I execute this code.
const userCredential = await setPersistence(auth, browserLocalPersistence).then(async () => {
return await signInWithEmailAndPassword(auth, e.email, e.password).then((userCredential) => {
return userCredential;
}).catch((error) => {
console.log(error);
return null;
});
});
versions
node: v16.4.0
react: ^17.0.2
next: ^12.0.7
firebase: ^9.6.2
firebase-tools#10.6.0
Chrome: 100.0.4896.75(Official Build) (x86_64)

Related

Setting up firebase Admin SDK in node

I am developing a password-recovery block for my application. I found out that I could call sendPasswordResetEmail function which works fine, but I want to use my own email template so I need to use Admin SDK and call admin.auth().generatePasswordResetLink(email) to generate a link where I could extract the OobCode to use resetPassword function. But for some reason I got the following error calling admin.auth().generatePasswordResetLink(email):
errorInfo: {
code: 'auth/insufficient-permission',
message: 'Credential implementation provided to initializeApp() via the "credential" property has insufficient permission to access the requested resource.
},
codePrefix: 'auth'
}
The permissions settting should be fine in firebase, altough I am totaly new in firebase.
Here is my code what includes the firebase-client initialization, admin sdk initialization, the post request:
import config from "config"
const serviceAccount = config.get('serviceAccount')
import admin from "firebase-admin";
const dbUrl = ""
try {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
databaseURL: dbUrl
});
} catch (e) {
console.log(e)
}
export {admin}
//------------------------------------------------
import { admin } from './firebase/firAdmin.js';
import {getAuth} from "firebase/auth";
import {initializeApp} from 'firebase/app';
const {
FIR_APP_ID,
FIR_API_KEY,
FIR_PROJECT_ID,
FIR_DATBASE_URL,
FIR_AUTH_DOMAIN,
FIR_STORAGE_BUCKET,
FIR_MESSAGING_SENDER_ID
} = process.env
const firConfig = {
appId: FIR_APP_ID,
apiKey: FIR_API_KEY,
authDomain: FIR_AUTH_DOMAIN,
databaseURL: FIR_DATBASE_URL,
projectId: FIR_PROJECT_ID,
storageBucket: FIR_STORAGE_BUCKET,
messagingSenderId: FIR_MESSAGING_SENDER_ID
}
const firApp = initializeApp(firConfig)
//------------------------------------------------
app.post('/password-recovery', async(req, res) => {
const {email} = req.body;
admin.auth().generatePasswordResetLink(email).then((link) => {
console.log(link)
})
.catch((err) => {
console.log(err)
});

Node/Express post data without using app.listen

I am really new to Node and Express, for this project I was trying to post values from the node server to google Sheets which is working. The only issue I am facing now is, to post the value I always have to reload the browser or use the localhost:3000 in the browser. Is there a way that we can post the value when the node server is started?
Index.js Code
const express = require("express");
const { google } = require("googleapis");
const app = express();
var req = http.request(options, callback);
app.get("/", async (req,res) => {
const auth = new google.auth.GoogleAuth({
keyFile: "credentials.json",
scopes: "https://www.googleapis.com/auth/spreadsheets",
});
const client = await auth.getClient();
// Instance of Google Sheets API
const googleSheets = google.sheets({version: "v4", auth: client});
const spreadsheetId = "1SwZvn0L_wqswv";
// get meta data about spreadsheet
const metaData = await googleSheets.spreadsheets.get({
auth,
spreadsheetId,
});
await googleSheets.spreadsheets.values.append({
auth,
spreadsheetId,
range: "Sheet1!A:B",
valueInputOption: "USER_ENTERED",
resource: {
values: [
["Man", "PostSheet"],
] // end of values array
}
})
});
app.listen(3000, (req,res) => console.log("running on 3000"));
Reference Link
As for reference I used the link from stackoverflow. I was able to post data using the link but unable to post data without using a browser. Basically I just want to post the data when the server is started.
Remove everything related to express and add everything else to an asynchronous function (because you're using await), then call that function in the same file. Example:
const { google } = require("googleapis");
async function FUNCTIONNAMEHERE () {
const auth = new google.auth.GoogleAuth({
keyFile: "credentials.json",
scopes: "https://www.googleapis.com/auth/spreadsheets",
});
const client = await auth.getClient();
// Instance of Google Sheets API
const googleSheets = google.sheets({version: "v4", auth: client});
const spreadsheetId = "1SwZvn0L_wqswv";
// get meta data about spreadsheet
const metaData = await googleSheets.spreadsheets.get({
auth,
spreadsheetId,
});
await googleSheets.spreadsheets.values.append({
auth,
spreadsheetId,
range: "Sheet1!A:B",
valueInputOption: "USER_ENTERED",
resource: {
values: [
["Man", "PostSheet"],
] // end of values array
}
})
}
FUNCTIONNAMEHERE()
After that run the file with node index.js

DB.collection is not a function in firebase?

I am trying to connect to firebase realtime database (not firestore) but I get the error that db.collection is not a function. Other answers in StackOverflow are mentioned with respect to Firestore. Thanks for your help.
const admin = require('firebase-admin');
// Firebase configuration - this should not be public.
// Please use your own config if you intend to use this code.
var firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxx",
databaseURL: "xxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxx",
}
// Initialize Firebase
admin.initializeApp(firebaseConfig)
const db = admin.database();
console.log("Database setup");
(async () => {
try {
let query = db.collection('users');
console.log("Doing database query now");
await query.get().then(querySnapshot => {
console.log(querySnapshot);
});
} catch (error) {
console.log(error);
}
})();
const db = admin.database() is an instance of Firebase realtime database and not Firestore. To get an instance of Firestore, use admin.firestore().
const admin = require('firebase-admin');
admin.initializeApp(/* service account */)
const db = admin.firestore();
console.log("Firestore setup");
Admin SDK uses a service account and not the same public credentials. You can refer to the documentation for detailed information. You can get a service account from project settings.
Do note that if you are using Cloud functions then you can leave initializeApp() empty.

How do I solve CORS issues in Apollo, Node, and Next.js?

I need help troubleshooting I CORS error I am having in Apollo, Node, and Next.js. I am not sure what change I have made, but suddenly I am unable to fetch the data from my Prisma database. I am currently running dev mode. My Yoga server which pulls in my data from Prisma run at localhost:4444. My frontend is run on localhost:7777.
Here is my CORS setup:
import withApollo from "next-with-apollo";
import ApolloClient from "apollo-boost";
import { endpoint, prodEndpoint } from "../config";
import { LOCAL_STATE_QUERY } from "../components/Cart";
function createClient({ headers }) {
return new ApolloClient({
uri: process.env.NODE_ENV === "development" ? endpoint : prodEndpoint,
request: (operation) => {
operation.setContext({
fetchOptions: {
credentials: "include",
},
headers,
});
},
// local data
clientState: {
resolvers: {
Mutation: {
toggleCart(_, variables, { cache }) {
// read the cartOpen value from the cache
const { cartOpen } = cache.readQuery({
query: LOCAL_STATE_QUERY,
});
// Write the cart State to the opposite
const data = {
data: { cartOpen: !cartOpen },
};
cache.writeData(data);
return data;
},
},
},
defaults: {
cartOpen: false,
},
},
});
}
export default withApollo(createClient);
variables.env
FRONTEND_URL="localhost:7777"
PRISMA_ENDPOINT="https://us1.prisma.sh/tim-smith-131869/vouch4vet_dev_backend/dev"
PRISMA_SECRET="..."
APP_SECRET="..."
STRIPE_SECRET="..."
PORT=4444
backend index.js
const server = createServer();
server.express.use(cookieParser());
// decode the JWT so we can get the user Id on each request
server.express.use((req, res, next) => {
const { token } = req.cookies;
if (token) {
const { userId } = jwt.verify(token, process.env.APP_SECRET);
// put the userId onto the req for future requests to access
req.userId = userId;
}
next();
});
I have tried rolling back to previous commit and I have had no luck. I have not ruled out internet problems.
Let me know if you need to see the rest of my repo.
Thanks

How to get user using email and password firebase with nodejs [duplicate]

This question already has answers here:
Firebase Admin SDK to Log user in from Server
(3 answers)
Closed 3 years ago.
how can I get a user data using firebase authentication with email and password of an user?
the only way I was able to capture the user was to use the
firebase.auth() function.getUserByEmail(email)
but I don't find how to perform that call passing the email and password of the user, any help with this question?
my source code:
var express = require('express');
var app = express();
const firebase = require('firebase-admin');
const inquirer = require('inquirer')
const serviceAccount = require('...')
var currentUser;
var userProfile;
var config = {
credential: firebase.credential.cert(serviceAccount),
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "..."
};
firebase.initializeApp(config);
let server = app.listen('8081', function (err) {
if (err) {
console.log(err);
}
console.log("App listening on port " + "8081");
var authentication = [
{
type: 'input',
name: 'email',
message: "Type your email:",
},
{
type: 'password',
name: 'password',
message: "Type your password:",
},
]
inquirer.prompt(authentication).then(answers => {
console.log(`Hello! The application is starting!`)
startCrawler(answers['email'], answers['password'])
})
async () => {
await firebase.auth().getUserByEmail(email) //Here where I want to grab the user with email and password
.then((user) => {
currentUser = user.toJSON();
}).catch(err => {
console.log('Email or password invalid!');
});
if (!currentUser) { return };
}
});
It looks like you're trying to sign the user in on a Node.js app that uses the Firebase Admin SDK. The Firebase Admin SDK doesn't have the concept of a signed in user. If you need that, consider using the regular Firebase SDK for web applications.
Also see my answer here: Firebase Admin SDK to Log user in from Server

Resources