Firebase createUserWithEmailAndPassword not working - javascript

I'm just trying to get simple email/password authentication working. As a test, trying to just create users. It's not working, when clicking the button to pass some hard-coded email/password vars to auth, I get this console error below. As far as I understand I should be able to do this from client-side without having to set up any server. I also have firebase email/password authentication enabled in firebase console.
{
"error": {
"errors": [
{
"domain": "usageLimits",
"reason": "accessNotConfigured",
"message": "Access Not Configured. Google Identity Toolkit API has not been used in project 87795057294 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project=87795057294 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry.",
"extendedHelp": "https://console.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project=87795057294"
}
],
"code": 403,
"message": "Access Not Configured. Google Identity Toolkit API has not been used in project 87795057294 before or it is disabled. Enable it by visiting https://console.developers.google.com/apis/api/identitytoolkit.googleapis.com/overview?project=87795057294 then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry."
}
}
Though I did check and Google Identity Toolkit API is enabled
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Firebase Auth Test</title>
<!-- Firebase JavaScript Link -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.1/firebase-database.js"></script>
</head>
<body>
<!-- JQuery -->
<!-- ================================================================================== -->
<script>
$(document).ready(function() {
// Initialize Firebase
// This is the code we copied and pasted from our app page
var config = {
apiKey: "AIzaSyBJOZIBC9J3MUfkLfXGKgvaNYxilplQ7fI",
authDomain: "project1-e7460.firebaseapp.com",
databaseURL: "https://project1-e7460.firebaseio.com",
projectId: "project1-e7460",
storageBucket: "project1-e7460.appspot.com",
messagingSenderId: "87795057294"
};
firebase.initializeApp(config);
var email = "geochanto#yahoo.com";
var password = "Abc1234!";
// Get a reference to the database service
var database = firebase.database();
var clickCounter = 0;
$("#clickme").on("click", function() {
console.log('clicked!');
clickCounter++;
database.ref().set({
clickCount: clickCounter,
em: email,
pa: password
});
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// ...
});
});
});
</script>
<button id="clickme">Click Me</button>
</body>
</html>

You need to login to your Firebase Console and enable the Sign-In Method.
See the point 3 of the Before You Begin section in the Authentication documentation.
Enable Email/Password sign-in:
In the Firebase console, open the Auth section.
On the Sign in method tab, enable the Email/password sign-in method and click Save.
Then try again - it should work once enabled.

Related

Recaptcha call back can be found when it is the only function but not when other ones are included

I am trying to make a discord bot verification page where users verify that they are not a robot. I have run into an error where Recaptcha cannot find my recaptchaCallBack function. It recognizes it when it is the only function and doesn't when other functions are included.
Here is the code:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-app.js";
import { getAnalytics } from "https://www.gstatic.com/firebasejs/9.6.4/firebase-analytics.js";
import { getDatabase } from "firebase/database";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
//config
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getDatabase();
function recaptchaCallback() {
set(ref(db, "verified/" + userVarFormatted), {
name: userVarSplitted[0],
discriminator: userVarSplitted[1]
});
}
<html>
<head>
<title>Jerry Bot Verication</title>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body>
<form action="?" method="post" data-callback="XXX" class="recaptchaDIV">
<div class="g-recaptcha" data-callback="recaptchaCallback" data-sitekey="my site key"></div>
</form>
<!--My js code was here-->
</body>
</html>
Do you know what is causing this?
Thanks
If you're talking about just a regular web page, there's no mechanism for require("mongodb") to work. (You'd need a bundler.)
Even if it did, a browser can't directly talk the MongoDB protocol.
Even if it could, you'd now expose your MongoDB credentials to anyone who would visit the page, so they could read and tamper with your database however they'd like, which is likely not what you want.

Firebase popup signin popup-closed-by-user error

I am trying to use the Javascript client library for Firebase auth to sign in with a Google account and popup window. However, when I try to sign in, the signin window pops up, I select my Google account, and then it spends about 10 seconds loading (with the blue progress bar moving), then the popup window closes, and shortly after I get the following error message:
code: "auth/popup-closed-by-user"
message: "The popup has been closed by the user before finalizing the operation."
I have enabled Google signin in the authentication section of the Firebase web UI. Below is the code I am using which is pretty much directly copied from the Firebase docs. I have made no other changes to the project config. I started a new project just to test this and have simply run firebase init, enabling only hosting, and enabling Google signin in the authentication web UI.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Welcome to Firebase Hosting</title>
<script src="/__/firebase/7.14.6/firebase-app.js"></script>
<script src="/__/firebase/7.14.6/firebase-auth.js"></script>
<script src="/__/firebase/init.js"></script>
</head>
<body>
<button id="signin">sign in</button>
<button id="signout">sign out</button>
<script>
const provider = new firebase.auth.GoogleAuthProvider();
const signinButton = document.querySelector("#signin");
signinButton.addEventListener("click", () =>
firebase
.auth()
.signInWithPopup(provider)
.then(function (result) {
console.log("result", result);
})
.catch(function (error) {
console.error(error);
})
);
const signoutButton = document.querySelector("#signout");
signoutButton.addEventListener("click", () =>
firebase
.auth()
.signOut()
.then(function () {
console.log("signed out");
})
.catch(function (error) {
console.error(error);
})
);
</script>
</body>
</html>
See this issue: https://github.com/firebase/firebase-js-sdk/issues/3188.
For some users, this is resolved by adding the app domain to the list of authorized domains:
Firebase Console -> Auth -> Sign-In Method -> Authorized Domains -> Add (domain)
For some users this may be caused by the Firefox Containers feature, or by the Firefox Enhanced Tracking Protection feature, specifically its isolate other cross-site cookies feature.

I am very confused on how to include Firebase into html

I recently started integrating firebase into my html project, i installed firebase-tools using npm and initialized the project, but then after I included all the scripts mentioned on the firebase website, I used firebase.auth() to sign in the user, then I got an error that firebase is undefined, so I inserted these script tags into my code:
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/firebase/init.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-app.js"></script>
<!-- If you enabled Analytics in your project, add the Firebase SDK for Analytics -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-analytics.js"></script>
<!-- Add Firebase products that you want to use -->
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.13.1/firebase-firestore.js"></script>
and below these I had my firebase config:
<script>
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "MY_API_KEY",
authDomain: "MY_PROJECT.firebaseapp.com",
databaseURL: "https://MY_PROJECT.firebaseio.com",
projectId: "MY_PROJECT",
storageBucket: "MY_PROJECT.appspot.com",
messagingSenderId: "MESSAGER_ID",
appId: "MY_APP_ID",
measurementId: "MEASUREMENT_ID"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
</script>
<script>
async function signIn(email, password){
await firebase.auth().signInWithEmailAndPassword({
email,
password
}).then(() => {window.location.href = "HomeScreen.html"}).catch((err) => {
document.getElementById('FailedSignIn').style.display = "flex";
})
}
</script>
And then I got these errors:
[2020-03-30T17:24:20.332Z] #firebase/app: Warning: Firebase is already defined in the global scope. Please make sure Firebase library is only loaded once.
Website.htmlAccess to fetch at 'https://firebaseinstallations.googleapis.com/v1/projects/MY_PROJECT/installations' from origin 'http://localhost:63342' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
https:/…base-analytics.js:1POST https://firebaseinstallations.googleapis.com/v1/projects/MY_PROJECT/installations net::ERR_FAILED
TypeError: Failed to fetch
So I would really appreciate some clarification of the ordering of these script tags, as well as how to properly initialize firebase and use it in my file without any errors.
After you’ve created your account and the Firebase project, all you need to do is add the JavaScript code to your HTML, as described in the Setup Docs
<script src="https://www.gstatic.com/firebasejs/4.0.0/firebase.js"></script>
<script>
// Initialize Firebase
// TODO: Replace with your project's customized code snippet
var config = {
apiKey: "<API_KEY>",
authDomain: "<PROJECT_ID>.firebaseapp.com",
databaseURL: "https://<DATABASE_NAME>.firebaseio.com",
storageBucket: "<BUCKET>.appspot.com",
messagingSenderId: "<SENDER_ID>",
};
firebase.initializeApp(config);
// Get a reference to the database service
var database = firebase.database();
// update the variable when the starCount is changed in the database
var starCountRef = database.ref('posts/' + postId + '/starCount');
starCountRef.on('value', function(snapshot) {
updateStarCount(postElement, snapshot.val());
});
// update the UI
function updateStarCount(el, val) {
el.innerHtml(`${val} Stars!`);
}
</script>
Then you can continue to learn about Realtime Database here
The Javascript/Node.JS SDK is introduced here.
How do you start your local web-server at http://localhost:63342?
Maybe you just have to start your web-server with using CORS request headers for external requests.
Example:
yarn serve --cors

"Request is missing authentication credential" error when calling firebase.messaging.getToken()

I am following the tutorial to add push notifications to a web app, including calling firebase.messaging.usePublicVapidKey with the VAPID key. However, when I'm calling getToken I get the following error:
Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project
I am already using VAPID key and nowhere in the tutorial did Google say that a Google OAuth login was required. How can I fix this?
var messaging = firebase.messaging();
messaging.usePublicVapidKey('redacted');
function obtenerToken() {
messaging.getToken().then(function (nuevoToken) {
if (nuevoToken) {
token = nuevoToken;
} else {
messaging.requestPermission().then(obtenerToken)
.catch(function (err) { console.log('La web no tiene permiso para recibir notificaciones ', err); });
}
}).catch(function (err) { console.log('Error al obtener token de Firebase ', err); });
}
obtenerToken();
Clear your site data!
After struggling with this for some time I cleared my site data and the auth error did not occur again. We use Firestore with custom auth tokens to retrieve realtime data in another part of the site and I suspect it caused the problem.
Did you initialize with a Firebase configuration object?
import firebase from "firebase/app";
import "firebase/messaging";
const firebaseConfig = {
apiKey: "api-key",
authDomain: "project-id.firebaseapp.com",
databaseURL: "https://project-id.firebaseio.com",
projectId: "project-id",
storageBucket: "project-id.appspot.com",
messagingSenderId: "sender-id",
};
if (!firebase.apps.length) {
firebase.initializeApp(firebaseConfig);
}
let messaging;
try {
messaging = firebase.messaging();
messaging.usePublicVapidKey("publicVapidKey");
} catch (e) {
messaging = null;
}
Have you set whitelist your production domain for browser API keys and client IDs in the Google Developer Console?
Did you setup firebase-messaging-sw.js file?
Like this.
// change your using firebase version
importScripts("https://www.gstatic.com/firebasejs/5.10.0/firebase-app.js");
importScripts("https://www.gstatic.com/firebasejs/5.10.0/firebase-messaging.js");
const messagingSenderId = "your sender id here";
firebase.initializeApp({ messagingSenderId });
try {
const messaging = firebase.messaging();
} catch (e) {}
See:
https://firebase.google.com/docs/web/setup
https://firebase.google.com/support/guides/launch-checklist
https://github.com/firebase/quickstart-js/tree/master/messaging
https://github.com/firebase/quickstart-js/blob/master/messaging/firebase-messaging-sw.js
If does not work then you should try quickstart.
Managed to fix the issue. It turns out I copied the config from one project and the VAAPI key from another project. D'oh!
I ran into the same issue, for a different reason. We are using two Firebase projects (one dev, one production). The two apps are configured in the same config file. I just learned that the firebase.messaging() function can accept one parameter: the initialized Firebase App. Without this parameter, const devMessaging was configuring with the default app settings, in my case production. Here is the fixed code:
export const app = firebase.initializeApp(config);
export const devApp = firebase.initializeApp(devConfig, "secondary");
const devMessaging = firebase.messaging(devApp);
devMessaging.usePublicVapidKey("this_is_private");
devMessaging.getToken().then(() => {
// continue with the rest of the code
});
resource: https://firebase.google.com/docs/reference/js/firebase.messaging

Firebase auth() subfunctions not recognized

I'm trying to use Firebase to allow users to create accounts and sign in to a chat app. I've copy-pasted the code on Firebase's console to add a web app and have followed the docs for creating a user account with email and password. THe docs say to pass email and password to their function firebase.auth().createUserWithEmailAndPassword(email, password), and although I've done the integration properly thus far, my IDE says that createUserWithEmailAndPassword(email, password) is an unresolved method. I am working in a separate JS file called main.js, with the required JS files from Firebase in <script> tags above the tag that links main.js to index.html.
function submitAcc() {
var email = document.getElementById("emailinput").value;
var password = document.getElementById("passinput").value;
firebase.auth().createUserWithEmailAndPassword(email, password).catch(function (error) {
console.log(error.log);
console.log(error.message);
});
}
is the problematic function in main.js and here
<script>
// Initialize Firebase
var config = {
apiKey: "censored",
authDomain: "censored",
databaseURL: "censored",
projectId: "censored",
storageBucket: "censored",
messagingSenderId: "censored"
};
firebase.initializeApp(config);
</script>
<!-- Firebase App is always required and must be first -->
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-app.js"></script>
<!-- Add additional services that you want to use -->
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-database.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-messaging.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-functions.js"></script>
<!-- Comment out (or don't include) services that you don't want to use -->
<!-- <script src="https://www.gstatic.com/firebasejs/5.8.5/firebase-storage.js"></script> -->
<!-- <script src="main.js" rel="script"></script> -->
<script src="main.js"></script>
are the Firebase script tags copy-pasted from what the docs tell me to do. It's only firebase.auth() that doesn't work; we tried firebase.database().ref() to test and that works fine.
As it turns out, there WAS no error, instead it was simply the IDE that had a problem. Upon testing the function performed as intended. For anyone else that has this error, try making an account as you would if you were a user and then checking the users under firebase > auth. This error occurred with the JetBrains WebStorm IDE.

Categories

Resources