The current domain is not authorized for OAuth operations - reactjs

hello everyone i have vite app and i used firebase google auth . it works fine but when i deploy it on vercel it give me this error :
The current domain is not authorized for OAuth operations. This will prevent signInWithPopup, signInWithRedirect, linkWithPopup and linkWithRedirect from working. Add your domain (todomarwenlabidi.vercel.app) to the OAuth redirect domains list in the Firebase console -> Auth section -> Sign in method tab.
this is my app link : https://todomarwenlabidi.vercel.app/
and i added the domain to authorized domains
look this photo
and this is my firebase config file :
const firebaseConfig = {
apiKey:import.meta.env.VITE_API_KEY ,
authDomain: "todo-app-97ae2.firebaseapp.com",
projectId: "todo-app-97ae2",
storageBucket: "todo-app-97ae2.appspot.com",
messagingSenderId: "540711457418",
appId:import.meta.env.VITE_APP_ID ,
};

You have to add the domains you use in the firebase authorized domains (see picture)

Related

Can I use Firebase Auth without a database?

I'm trying to add Authentication to a React Web App (typescript) and I see that "firebase/auth" could be all I need. But this is the configuration:
var firebaseConfig = {
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxx",
databaseURL: "xxxxxxxxxx",
projectId: "xxxxxxxxxx",
storageBucket: "xxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxx",
appId: "1:xxxxxxxxx:web:xxxxxxxxxxxxxx",
measurementId: "xxxxxxxxx"
};
Do I need databaseURL? or storageBucket? My intention is to JUST AUTHENTICATE using Google auth for now and match the user in my database with a google ID or whatever Firebase Auth unique id has. What are the consecuences to skip databaseURL and/or storageBucket when configuring.?
All Firebase services are independent of each other and that means you can use only Authentication. The other keys in the JSON are just for identification purposes. But if you have not enabled those services from the console, they are redundant. If you remove databaseUrl, you can still use Authentication.
That being said, if you don't use Firebase Authentication then you may not be able to use some features in Firebase Databases or Storage such as authentication in security rules.

In Gatsby, how do I redirect authenticated users from the homepage / to /app without a flash of content?

I'm trying to implement a common user experience for web apps in which authenticated users are automatically redirected from the home page to the app.
For example, upon typing https://example.com/ in the browser, if I'm not logged in I see the home page. But if I am logged in, I'm redirected automatically to https://example.com/app/
I currently have this in my pages/index.js:
if (auth.user) return <Redirect noThrow from="/" to="/app" />;
where Redirect is from #reach/router.
However, when I do this, the non-authenticated home page flashes briefly before the redirect kicks in. Is there a way to do this such that:
There is no flash of content before the redirect happens AND
The home page is still statically generated so that it is indexed properly by Google for SEO
Thanks!
You would need your server to respond to the request for the homepage with a 301–303 response code and a Location header pointing to the desired URL (e.g. /app/).
Gatsby does not run any kind of server to respond to requests in production, alas, so you can't address this using Gatsby alone without some significant hacks, like hiding all of your content by default, which would result in no content being indexed by Google.
module.exports = {
plugins: [
{
resolve: "gatsby-theme-firebase",
options: {
credentials: {
apiKey: process.env.FIREBASE_API_KEY,
authDomain: process.env.FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.FIREBASE_DATABASE_URL,
projectId: process.env.FIREBASE_PROJECT_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.FIREBASE_APP_ID,
},
loginPath: "/login",
loginRedirectPath: "/dashboard",
socialLogins: ["google", "twitter", "facebook", "github"],
},
},
],
};
or check https://www.gatsbyjs.com/plugins/gatsby-theme-firebase-storage/

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.

Possible to do Firebase social login + still have option to instead use manual email/password for creating/auth-ing accounts?

I'm thinking about implementing social authentication for an React app I want to create.
I see Firebase handles alot of that work for you for Google/Twitter/FB/GitHub auth.
But i still want to have an option to offer a manual signup (and for those users offer a manual login).
Is that possible? Like will Firebase store/auth manual users via their Authentication system? Or i need to have a separate auth system for that (with my own database/auth check outside of Firebase)?
I'm very new to this so just thought I'd ask. Some links to some React articles would be great. I only saw ones that implement social but not social+manual authentication (preferably via Firebase to cover all social logins vs manually setting each OAUTH system).
Thanks!
A single user account in Firebase Authentication can be linked with multiple providers. You can link those providers together after the user signs in with them.
For more on this, see the Firebase documentation on account linking. From there:
You can allow users to sign in to your app using multiple authentication providers by linking auth provider credentials to an existing user account. Users are identifiable by the same Firebase user ID regardless of the authentication provider they used to sign in. For example, a user who signed in with a password can link a Google account and sign in with either method in the future. Or, an anonymous user can link a Facebook account and then, later, sign in with Facebook to continue using your app.
Yes, its possible to make the authentication using firebase. Few dependencies you need to have in mind like, "react-native-firebase", for google sign-in "react-native-google-signin"
For Checking with Provider refer here
Android Setup
I am sharing sample code for Google Sign-in:
import { GoogleSignin } from 'react-native-google-signin';
import firebase from 'react-native-firebase'
const firebaseConfig = {
apiKey: firebaseConfigg.API_KEY,
authDomain: firebaseConfigg.AUTH_DOMAIN,
databaseURL: firebaseConfigg.DATABASE_URL,
projectId: firebaseConfigg.PROJECT_ID,
storageBucket: firebaseConfigg.STORAGE_BUCKET,
messagingSenderId: firebaseConfigg.GCM_SENDER_ID
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
login = async() => {
await GoogleSignin.hasPlayServices({ autoResolve: true });
const sigin = await GoogleSignin.configure({
iosClientId: '',
forceConsentPrompt: true,
scopes: ['profile', 'email']
}).then(async (success) => {
if (success) {
GoogleSignin.signIn().then((data) => {
console.log("--->> ", data);
const credential = firebase.auth.GoogleAuthProvider.credential(data.idToken, data.accessToken);
firebase.auth().signInAndRetrieveDataWithCredential(credential).catch((error) => {
});
})
}
})
}

Resources