Firebase web. No signInWithUsernameAndPassword function - javascript

I am very confused about firebase web because when I create an auth using firebase.auth() then try to call a method directly from the firebase documentation, signInWithUsernameAndPassword, it does not work. I am using
webstorm and is says it is an unrecognized method.
// Initialize Firebase
var config = {
apiKey: "AIzaSyBbmdeersid6XSA4kh_TYsGgVSgVF5BrFs",
authDomain: "eraticators-73723.firebaseapp.com",
databaseURL: "https://eraticators-73723.firebaseio.com",
projectId: "eraticators-73723",
storageBucket: "eraticators-73723.appspot.com",
messagingSenderId: "782651564720"
};
firebase.initializeApp(config);
const txtEmail = document.getElementById("user");
const txtPassword = document.getElementById("password");
const btnLogin = document.getElementById("btnLogin");
btnLogin.addEventListener("click", function() {
const email = txtEmail.value;
const pass = txtPassword.value;
const auth = firebase.auth();
firebase.auth().signInWithUsernameAndPassword(email, pass);
});
that is my javascript file. The only suggested functions are signInViaPopup() and signInViaRedirect(). Why is there not signInWithUsernameAndPassword function when that is exactly what the documentation says to use????

signInWithUsernameAndPassword does not exist. Firebase Auth does not support sign in with username and password. It only supports sign in with email and password. The equivalent method is signInWithEmailAndPassword.
The Firebase docs and references should not mention the former at all.

can you please check have you enabled authentication with Email/Password.
if you didn't enable it.
Follow the path given below:-
firebase console -> authentication -> sign-in method.
and enable signIn with email/password

You need to add the script auth tag in the html.

Related

Firebase .listUsers() is not function

I have been looking for some time, but without answers, so I ask my question:
I work with firebase and I make a function 'getAllUsers' (which must return all registered user uid) :
function getAllusers(nextPageToken){
app.auth().listUsers(1000, nextPageToken)
.then(function(listUsersResult) {
listUsersResult.users.forEach(function(userRecord) {
console.log('user', userRecord.toJSON());
});
if (listUsersResult.pageToken) {
// List next batch of users.
listAllUsers(listUsersResult.pageToken);
}
})
.catch(function(error) {
console.log('Error listing users:', error);
});
}
(yes, this is the doc example)
but I get
Uncaught TypeError: app.auth is not a function
I tested :
auth().listUsers()
getAuth.listUsers()
I think this is my imports:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-app.js";
import { getAuth, signInWithPopup, createUserWithEmailAndPassword, signInWithEmailAndPassword, GoogleAuthProvider, signOut, getAdditionalUserInfo, reauthenticateWithCredential } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-auth.js";
import { getDatabase, set, ref, update, child, onValue, get } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-database.js";
import { getStorage, ref as sRef, uploadBytes, getDownloadURL, deleteObject } from "https://www.gstatic.com/firebasejs/9.6.7/firebase-storage.js";
const firebaseConfig = {
apiKey: "XX",
authDomain: "XX",
databaseURL: "XX",
projectId: "XX",
storageBucket: "XX",
messagingSenderId: "XX",
appId: "XX",
measurementId: "XX"
};
const app = initializeApp(firebaseConfig);
const database = getDatabase(app);
const auth = getAuth(app);
const storage = getStorage(app);
I am currently researching how to use 'admin' for this
Hoping someone can help me, I keep looking, thanks in advance
The Firebase Admin SDK run code with elevated/administrative permissions and thus can only be used in a trusted environment, such as your development machine, a server that you control, or Cloud Functions/Cloud Run. They cannot be used in client-side application code, as that would be a security concern.
The regular Firebase SDKs only allow a user access to their own profile data, as doing otherwise on an SDK level would be a security concern.
If the application needs to show information about other users, you will have to build (and secure) that yourself on top of Firebase. The two most common options:
Implement the functionality in a custom server-side API that uses the Admin SDK and that you can call from your client-side application code. The custom server-side code you write should then ensure that only data that the caller is authorized to see is returned.
Have each user write to a cloud-hosted database (such as Firestore or the Realtime Database or Firebase), and then have other users read it from there. In this scenario you'll want to use Firebase's security rules to ensure each user can only access the data they're authorized for.
This topic has been covered frequently before, so I recommend also checking out:
Firebase list all users
How do I return a list of users if I use the Firebase simple username & password authentication
Can't retrieve list of all users from firebase authetication
Retrieving a list of users who have registered using Firebase Auth

Firebase multiple "apps" - client side and server side

So, I wanted to add another firebase app into the project. I already had one for SSR (firebase-admin), so server could pre-render sites. Now I want to add firebase#8, so I can start using it on client side, and later apply firestore rules to it. The problem is, when I'm trying to use it I get this error:
/node_modules/#google-cloud/storage/build/src/bucket.js:22:0
Module not found: Can't resolve 'fs'
Import trace for requested module:
./node_modules/#google-cloud/storage/build/src/index.js
./node_modules/firebase-admin/lib/storage/storage.js
./node_modules/firebase-admin/lib/app/firebase-namespace.js
./node_modules/firebase-admin/lib/default-namespace.js
./node_modules/firebase-admin/lib/index.js
./firebase/config.js
./firebase/createDocument.js
./components/form/Form.js
./pages/opinia/index.js
https://nextjs.org/docs/messages/module-not-found
Here is my config file:
import * as admin from 'firebase-admin';
import firebase from 'firebase';
import 'firebase/firestore';
// initialize firebase on CLIENT
const firebaseConfig = {
apiKey: process.env.FIREBASE_KEY,
authDomain: process.env.FIREBASE_DOMAIN,
projectId: process.env.FIREBASE_ID,
storageBucket: process.env.FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.APP_ID,
};
export const clientApp = initializeApp(firebaseConfig);
// firestore
export const projectFirestoreClient = firebase.firestore(clientApp);
// timestamp
export const timestampClient = firebase.firestore.Timestamp;
// initialize firebase on SERVER
if (!admin.apps.length) {
const serviceAccount = require('./firebase-adminsdk.json');
admin.initializeApp({
credential: admin.credential.cert(serviceAccount),
});
}
// firestore
export const projectFirestoreAdmin = admin.firestore();
// timestamp
export const timestampAdmin = admin.firestore.Timestamp;
So, my question is, how do I fix this error? And what's causing it? Thanks in advance.
Firebase Admin is not meant to be used on client side. When you run the app, Firebase Admin is also being imported and causing that error. Ideally you should initialize Firebase Admin in a different file that can be accessed on server side only.
Checkout this blog for step-by-step explanation on how to use Firebase Admin with NextJS.

Firebase Cloud Firestore Admin SDK issue

I am trying to update a Firebase document by first logging in with the admin account using Firebase Auth SDK.
Next I use the Firestore SDK to pull down the different parts of data needed from that plan.
Then push them back up to the new plan. So it’s essentially duplicating the plan.
The way I used to do it was in a self invoking function at the bottom of a HTML and just load the SDKs from their CDN.
Instructions to setup and links to CDN: https://firebase.google.com/docs/web/setup
If you try doing the
const firebaseConfig = {
apiKey: 'api-key',
authDomain: 'project-id.firebaseapp.com',
projectId: 'project-id',
}
firebase.initializeApp(firebaseConfig);
var db = firebase.firestore();
db.collection("users").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
// console.log(`${doc.othre} => ${doc.data()}`);
console.log(doc);
});
})
i get the follow error
Uncaught (in promise) FirebaseError: Missing or insufficient permissions.
If you want to use the Admin SDK from a server, please look at the doc for more details, in particular firebase.google.com/docs/admin/setup#prerequisites.

Firebase - need to fix javascript sdk auth error

I'm always getting this error:
TypeError: firebase.auth is not a function
Here is my code base, can some one help me plz?
const functions = require('firebase-functions');
var firebase = require("firebase/app");
var firebaseConfig = {
apiKey: "AIzaSyCGLNi4KMtUSC3CC3s6V-ZLQA87fDEuP-w",
authDomain: "octatradesfirebasedemo.firebaseapp.com",
databaseURL: "https://octatradesfirebasedemo.firebaseio.com",
projectId: "octatradesfirebasedemo",
storageBucket: "octatradesfirebasedemo.appspot.com",
messagingSenderId: "889486380424",
appID: "1:889486380424:ios:fb54696dc8f4a731df7e3d"
};
firebase.initializeApp({firebaseConfig});
console.log(firebase.auth);
});
If you want to use Firebase Authentication, you'll need to include firebase/app and firebas/auth.
var firebase = require("firebase/app");
require("firebase/auth");
That second require statement will add the firebase.auth() object.
Also see the Add Firebase SDKs and initialize Firebase section of the Firebase documentation.
You are going to need to add <script src="/__/firebase/6.6.1/firebase-auth.js"></script> or <script defer src="https://www.gstatic.com/firebasejs/6.6.1/firebase-auth.js"></script> to your app

Firebase credentials don't work when authenticated

I'm trying to implement an authentication for firebase in my react app. I do that with github but it's not relevant.
So I have some credentials and they work just fine. I can fetch my data from db and manilpulate it.
Until I login...
After successfully executing this: firebase.auth().signInWithPopup(githubProvider).then ...
I start constantly receiving warnings of that kind:
FIREBASE WARNING: Provided authentication credentials for the app named "[DEFAULT]" are invalid. This usually indicates your app was not initialized correctly. Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.
I can't do anything to my DB.
And this continues until I log out with firebase.auth().signOut().then ... then everything works fine again.
inb4: I am 100% confident that my credentials are correct. I have copied and pasted them several times.
Can someone give me insight on what is going on in that case?
And here's how I initialize the App
import firebase from 'firebase';
try {
const config = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
};
firebase.initializeApp(config);
} catch (e) {}
export const githubProvider = new firebase.auth.GithubAuthProvider();
export const firebaseRef = firebase.database().ref();
export default firebase;

Categories

Resources