Firebase: Error (auth/unauthorized-domain) on localhost - firebase

I'm getting Firebase: Error (auth/unauthorized-domain) on localhost during google auth. I found that this error is caused when domain is not added to Authorized domains in Firebase. But when i checked Authorized domains there is localhost, and don't know who is causing this error...
`
const signInWithGoogle = () => {
const provider = new GoogleAuthProvider()
signInWithPopup(getAuth(), provider)
.then((result) => {
console.log(result.user)
router.push("/login")
})
.catch((error) => {
console.log(error)
alert(error.body + ": " + error.message)
})
}
`

If it is a Vite Project.
Add
1 . import dns from 'dns'
2 . dns.setDefaultResultOrder('verbatim')
command in vite.config.js
run ''' npm run dev '''
it will give you the link to localhost in your terminal to open your app and run it. It will work for sure.
Many thanks for considering my request.

As mentioned above, the url to visit is localhost/ not 127.0.0.1 as that is a different domain than localhost/ although it is effectively the same to your machine.

Related

"error - unhandledRejection: Error: listen EADDRINUSE: address already in use :::3000" when I use Slack Bolt for JavaScript with ngrok and Next.js

Background
We are developing a Slack Bot. This time we are using Bolt for JavaScript (Node.js) provided by Slack, React, Next.js, and ngrok. Here is what each of them does.
Bolt for JavaScript: I don't want to use Slack's bare-bones API, but want to benefit from the function that wraps it.
React: Needed to use Next.js
Next.js: Slack needs a request URL to notify my bot app when events such as mentions occur in Slack, but Next.js makes it easy to create an API endpoint to be set to that URL (e.g. /api/something)
ngrok: In the local development environment, that URL will be http://localhost:3000, so the protocol will be http instead of https. Slack does not allow this, so we need a URL that starts with https that tunnels to the local http://localhost:3000. ngrok provides that easily!
Problem to be solved.
I have already confirmed that if I type #xxxx in a certain workspace in Slack, the event is notified to https://xxxx.jp.ngrok.io/api/slack/events. However, in this API file
app.event("app_mention", async ({ event, say }) => {
.
.
.
}
is not invoked and the following error occurs
error - unhandledRejection: Error: listen EADDRINUSE: address already in use :::3000
I would like to know why and how to resolve this.
Source code
/api/slack/events.ts
import type { NextApiRequest, NextApiResponse } from "next";
require("dotenv").config();
import app from "../../../config/slackAuth";
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
// Unique case for Slack challenge
if (req.body.challenge) return res.status(200).json(req.body);
// Subscribe to 'app_mention' event in your App config
// See https://api.slack.com/tutorials/tracks/responding-to-app-mentions
app.event("app_mention", async ({ event, say }) => {
try {
// Response to the message in the thread where the event was triggered with #${message.user}
// See https://slack.dev/bolt-js/concepts#message-sending
await say({
text: `Hi <#${event.user}>!`,
thread_ts: event.ts,
});
} catch (error) {
await say({
text: `<#${event.user}> ${error.message}.`, // #userName Request failed with status code 429.
thread_ts: event.ts,
});
}
});
(async () => {
// Start this app
await app.start(process.env.PORT || 3000);
console.log("⚡️ Bolt app is running!");
})();
return res.status(404).json({ message: "Unknown event type" });
}
Error code
error - unhandledRejection: Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (net.js:1331:16)
at listenInCluster (net.js:1379:12)
at Server.listen (net.js:1465:7)
at C:\Users\81906\Documents\slackGpt3\node_modules\#slack\bolt\dist\receivers\HTTPReceiver.js:176:25
at new Promise (<anonymous>)
at HTTPReceiver.start (C:\Users\81906\Documents\slackGpt3\node_modules\#slack\bolt\dist\receivers\HTTPReceiver.js:142:16)
at App.start (C:\Users\81906\Documents\slackGpt3\node_modules\#slack\bolt\dist\App.js:241:30)
at eval (webpack-internal:///(api)/./pages/api/slack/events.ts:69:69)
at handler (webpack-internal:///(api)/./pages/api/slack/events.ts:71:7)
at Object.apiResolver (C:\Users\81906\Documents\slackGpt3\node_modules\next\dist\server\api-utils\node.js:363:15) {
code: 'EADDRINUSE',
errno: -4091,
syscall: 'listen',
address: '::',
port: 3000
}
Issue
Using Slack Bolt for JavaScript with Next.js is not straightforward due to the following reasons:
Running npm run dev in a Next.js project starts a server at localhost:3000.
Running app.start() in Slack Bolt for JavaScript starts a server using Express.js, which also tries to use localhost:3000.
This causes an error because two servers are trying to use the same port.
This information was provided by someone at Slack, and the source can be found at https://github.com/slackapi/bolt-js/issues/1687.
Solution
You can change the port number used by Bolt to, for example, 3001.
However, this will make it difficult for the two servers at localhost:3000 and 3001 to communicate with each other.
The request URL registered in the Slack Bolt for JavaScript console is set to 3000, so events received there will not be able to flow to port 3001.

CORS error when making Axios calls to Cloudrun service from Firebase hosted app

This looks to be pretty obvious but I've been trying to figure it out for a couple of days now and still can't get it to work. Please, can someone point out what I'm missing.
I'm trying to make an axios call to my cloud run service from my firebase hosted SPA. To isolate the issue I followed the steps outlined in the [firebase tutorial for cloud run] (https://firebase.google.com/docs/hosting/cloud-run#node.js)
Step 4 of the tutorial talks about setting up rewrite to use the firebase domain as a proxy to your cloud run service. It says that the helloworld service would be reachable via
Your Firebase subdomains:
projectID.web.app/helloworld and projectID.firebaseapp.com/helloworld
So I follow the steps and deploy the service. Then I try to make an axios call to the service from the SPA like below
testHelloWorld () {
axios.get(`https://myProjectId.firebaseapp.com/helloworld`)
.then((data) => {
console.log(data)
})
.catch(ex => {
console.error(ex)
})
})
}
But then I get the CORS error
Access to XMLHttpRequest at 'https://myProjectId.firebaseapp.com/helloworld' from origin 'https://myFirabaseApp.firebaseapp.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
This answer states that this should be possible so I'm not sure what I'm doing wrong.
N.B:
While debugging, I updated the node app from the tutorial to add cors support like below. Still didnt work.
const express = require('express');
const app = express();
const cors = require('cors'); //Imported and added this
app.use(cors()); // Used here
app.get('/', (req, res) => {
console.log('Hello world received a request.');
const target = process.env.TARGET || 'World';
res.send(`Hello ${target}!`);
});
const port = process.env.PORT || 8080;
app.listen(port, () => {
console.log('Hello world listening on port', port);
});
So the question here is, how do I make an Axios/AJAX call to my cloud run service using the firebase rewrite rule?
Please check if you have installed cors: npm install cors.
Please check if the 2 following options can solve your issue:
1= Use the following code :
app.use(cors({origin:true,credentials: true}));
2) If the previous didn't work, please use the following code:
app.get('/', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
console.log('Hello world received a request.');
}
Please let me know if it works for you.

Serving files on a local network with Deno

I recently decided to play around with Deno a bit.
Right now I am trying to set up a basic file server on my local network, but it will only serve files to my computer and not the rest of the network (I can't even send a http request to the server from outside my computer). I can not, for the life of me, figure out why it only works locally.
I have added the code I am using at the moment below just in case, but I'm pretty sure the problem is somewhere else, because I have the same problem with this file_server example and when I create a file server with oak
import { serve } from 'https://deno.land/std#v0.42.0/http/server.ts';
const server = serve({ port: 3000 });
const decoder = new TextDecoder('utf-8');
for await (const req of server) {
const filePath = 'public' + req.url;
try {
const data = await Deno.readFile(filePath);
req.respond({ body: decoder.decode(data) });
} catch (error) {
if (error.name === Deno.errors.NotFound.name) {
console.log('File "' + filePath + '" not found');
req.respond({ status: 404, body: 'File not found' });
} else {
req.respond({ status: 500, body: 'Rest in pieces' });
throw error;
}
}
}
The command I'm using to run the file is:
deno --allow-all server.ts
When I create a simple file server in Node.js everything works just fine. It can serve files to my computer and any other device on the network.
I think the fault is with my understanding of Deno and it's security concepts, but I don't know. I would greatly appreciate any help and can supply more details if required.
You need to bind the hostname to 0.0.0.0 like so :
const server = serve({ hostname: '0.0.0.0', port: 3000 });
By default, your webserver only responds to localhost and 127.0.0.1.
Binding to 0.0.0.0 tells Deno to bind to all IP addresses/interfaces on your machine. Which makes it accessible to any machine on your network.
Your network IP address in the format of 192.168.x.y. gets also bind to the Deno webserver which allows another computer in your network to access the webserver with your local IP address.

TypeError: Redirected path should match configured path, but got: /callback

I have deployed the ExpressJs app on firebase function and trying to trigger the express app with an HTTP trigger.
I am trying to authorize my express app with OAUTH2.0 to use QuickBooks API. However, I am getting the following error:
TypeError: Redirected path should match configured path, but got: /callback
at CodeFlow.getToken (/srv/node_modules/client-oauth2/src/client-oauth2.js:597:7)
at /srv/routes/callback.js:12:25
at Layer.handle [as handle_request] (/srv/node_modules/express/lib/router/layer.js:95:5)
at next (/srv/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/srv/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/srv/node_modules/express/lib/router/layer.js:95:5)
at /srv/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/srv/node_modules/express/lib/router/index.js:335:12)
at next (/srv/node_modules/express/lib/router/index.js:275:10)
at Function.handle (/srv/node_modules/express/lib/router/index.js:174:3)
The error is in following file:
callback.js
router.get('/', function (req, res) {
// Verify anti-forgery
console.log("OriginalURL "+req.originalUrl)
console.log("base URL "+req.baseUrl)
// Exchange auth code for access token
tools.intuitAuth.code.getToken(req.originalUrl).then(function (token) { //This is where promise is failing
I am using npm package called "client-oauth2".
client-oauth2.js
if (
typeof options.redirectUri === 'string' &&
typeof url.pathname === 'string' &&
url.pathname !== Url.parse(options.redirectUri).pathname
) {
return Promise.reject(
new TypeError('Redirected path should match configured path, but got: ' + url.pathname) //The source of Error. I am not able to find out the value of options.redirectUri
)
}
Following are my configuration details:
"redirectUri": "us-central1-thematic-runner-245505.cloudfunctions.net/createEstimate/callback"
I have made sure that this URL matches with Quickbooks side redirect URL. In the case of localhost it works just fine.
Localhost URL: http://localhost:5001/thematic-runner-245505/us-central1/createEstimate/
The value of req.originalUrl from callback.js is
OriginalURL /thematic-runner-245505/us-central1/createEstimate/callback?code=AB11585447829JwgpXMEpWOR6irwprMe9Z8aqRoSK4npFDKmte&state=Z0t9yRkl-dWaO2J5sJRDaTB9eZKvyyyVcHYQ&realmId=4620816365002391850
Could somebody help me with this error? I don't know what I am doing wrong in the case of production. The callback URL seems to be fine. Any help would be appreciated.
This isn't a valid URL:
"redirectUri": "us-central1-thematic-runner-245505.cloudfunctions.net/createEstimate/callback"
There's no scheme/protocol portion to that URL (e.g. https://). It should start with https:// but instead you're jumping right into the domain.
It needs to be a valid URL, including the protocol/scheme.

Amplify Auth SignUp auto send another request and throw Error: No credentials, applicationId or region

I have 2 projects which are using the same code like this:
Auth.signUp({ username, password, attributes })
.then(data => console.log(data))
.catch(error => console.log(error))
.finally(() => console.log('done'));
Just like this: https://aws-amplify.github.io/docs/js/authentication#sign-up
Here is the problem show out:
In my old project, everything is ok, just 1 request is sign up send to AWS and got some data from it: https://cognito-idp.ap-southeast-2.amazonaws.com/
In my new project, I have another request go to AWS after the sign up request. There are:
https://cognito-idp.ap-southeast-2.amazonaws.com/
And : https://cognito-identity.ap-southeast-2.amazonaws.com/ which is after the first one and its response is :
message: "Unauthenticated access is not supported for this identity pool."
__type: "NotAuthorizedException"
After that, I got the error in console: Error: No credentials, applicationId or region.
Not sure why is the old project is working fine but with this one, this error show up. Is it because the different in amplify ?
Thanks.
I think the problem is with the Analytics package of AWS from my understanding of this link. Disabling it like so worked for me
import config from './aws-exports';
Amplify.configure({
...config,
Analytics: {
disabled: true
}
});
I solved it by using
import Amplify from '#aws-amplify/core';
import Auth from '#aws-amplify/auth';
istead of
import Amplify, { Auth } from 'aws-amplify';

Resources