React Native Firebase Auth function - firebase

I'm using react native crud application with using firebase real time storage. I use firebase auth functionality with email and password logging. but my firebase auth is not working. It gets more issues with firebase connection. I used this function to connect firebase.
componentWillMount() {
firebase.initializeApp({
apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxx',
authDomain: 'xxxxxxxxxxxxxxxxxxxxxx',
databaseURL: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
projectId: 'xxxxxxxxxxxxxxxxxxxxx',
storageBucket: 'xxxxxxxxxxxxxxxxxxxxxxxx',
messagingSenderId: 'xxxxxxxxxxxxxxx'
});
}
My log in button auth functionality is looks like this one:
state = { email: '', password: '', error: '' };
onButtonPress() {
const { email, password } = this.state;
firebase.auth().signInWithEmailAndPassword(email, password)
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.catch(() => {
this.setState({ error: 'Authenticaton Failed.' });
});
});
}
I import firebase libraries like this:
import * as firebase from 'firebase';
import 'firebase/firestore';
import 'firebase/auth';
But this configurations are not working. It shows me this error:
undefined is not a function (evaluating 'firebase.auth()')
I used to get text input values this method:
value={this.state.password}
onChangeText={password => this.setState({ password })}

your firebase config only exists in your componentDidMount. Try like this:
Create a file <namefile>.js wherever you want and add:
import * as firebase from 'firebase'
import 'firebase/auth';
const config = {
apiKey: "your key",
authDomain: "domain",
databaseURL: xxxx",
projectId: "xxxx",
storageBucket: "xxx",
messagingSenderId: "xxxx"
};
if (!firebase.apps.length) {
firebase.initializeApp(config);
}
const auth = firebase.auth();
export {
auth
};
import auth in your component and in your button method change your code by:
auth.signInWithEmailAndPassword
it should work and every time you need to use auth, you just need to import it

Related

Firebase authentication not working in NuxtJs application

In am using Firebase Authentication in my Nuxt App. I am following the Firebase Documentation for setting up Authentication using GoogleAuthProvider. In my case, onAuthStateChanged() listener returns null even after successfull redirect.
When the user enter my web application, Nuxt will execute the plugin in the client side. There the firebase configuration is initialized. Then the initUser() function defined in useFirebaseAuth.ts composable is called. If user successfully logged In, log the user details.
Note : After I encountered this error, I replaced signInWithRedirect to signInWithPopup, it works very well.
// plugins/firebase.client.ts
import { initializeApp } from "firebase/app";
import { initUser } from "~~/composables/useFirebaseAuth";
export default defineNuxtPlugin(() => {
const config = useRuntimeConfig();
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
projectId: "...",
appId: "...",
messagingSenderId: "...",
};
// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
initUser(firebaseApp);
})
// composables/useFirebaseAuth.ts
import { FirebaseApp } from "firebase/app";
import { getAuth,signInWithPopup, GoogleAuthProvider, onAuthStateChanged, signInWithRedirect, signOut, User } from "firebase/auth";
import { equalTo, getDatabase, onValue, orderByChild, query, ref as dbRef } from "firebase/database";
export const signInUser = async () => {
const provider = new GoogleAuthProvider();
const auth = getAuth();
await signInWithRedirect(auth, provider)
}
export const initUser = async (firebaseApp: FirebaseApp) => {
const auth = getAuth(firebaseApp)
const db = getDatabase()
onAuthStateChanged(auth, user => {
if (user) {
console.log(user)
} else {
console.log("user not logged in"
return navigateTo('/login')
}
});
}
export const signOutUser = async () => {
const auth = getAuth();
await signOut(auth)
}
In the above code, I always get the user value as null. I am working on the project for 2 months. The authentication works fine almost one month ago. But it is not working now. Please help me to resolve the issue.
# node --version
v19.5.0
# npm version
{
npm: '9.3.1',
node: '19.5.0',
v8: '10.8.168.25-node.11',
uv: '1.44.2',
zlib: '1.2.13',
brotli: '1.0.9',
ares: '1.18.1',
modules: '111',
nghttp2: '1.51.0',
napi: '8',
llhttp: '8.1.0',
uvwasi: '0.0.14',
acorn: '8.8.1',
simdutf: '3.1.0',
undici: '5.14.0',
openssl: '3.0.7+quic',
cldr: '42.0',
icu: '72.1',
tz: '2022g',
unicode: '15.0',
ngtcp2: '0.8.1',
nghttp3: '0.7.0'
}
I have gone through many answers posted for same question in the stackoverflow website. But those answers didn't solved my issues.

I can't authenticate Firebase with correct details. Get error: Make sure to initialize the SDK with a service account credential

I have followed these instructions and copied my Firebase config details, yet I keep getting told it can't be authenticated. I have tried both service account json file and ID. No idea why I get error because the Firebase details are correct.
Setup:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/database';
import 'firebase/compat/firestore';
import { attachCustomCommands } from 'cypress-firebase';
// import * as serviceAccount from '../support/serviceAccountKey.json'
const fbConfig = {
// Your config from Firebase Console
apiKey: "",
authDomain: ".firebaseapp.com",
// credential: serviceAccount,
databaseURL: "firebaseio.com",
projectId: "test-dev",
serviceAccountId: 'cypress#test-dev.iam.gserviceaccount.com',
storageBucket: "test-dev.appspot.com",
messagingSenderId: "",
appId: "",
measurementId: ""
};
firebase.initializeApp(fbConfig);
attachCustomCommands({ Cypress, cy, firebase });
Login:
before(() => {
cy.clearFirebaseAuth()
// cy.visit(Cypress.env("baseUrl"))
// cy.completeLoginScreen(Cypress.env("standardUserEmail"), Cypress.env("standardUserPassword"))
// cy.verifyLogin()
cy.request('POST', Cypress.env("baseUrlApi") + "auth", {
email: Cypress.env("standardUserEmail"),
password: Cypress.env("standardUserPassword"),
}).then((response) => {
cy.login(response.body.uid)
// cy.setCookie('token', response.body.token)
// window.localStorage.setItem("token", response.body.token)
// window.localStorage.setItem(response.body.token, response.body.uid);
})
})
Error message:
cy.task('createCustomToken') failed with the following error:
> Failed to determine service account. Make sure to initialize the SDK with a service account credential.
I got it working by posting in cypress config file instead:
export default defineConfig({
e2e: {
async setupNodeEvents(on, config) {
cypressFirebasePlugin(on, config, admin, {
credential: admin.credential.cert(serviceAccount as admin.ServiceAccount)
});

How can I get a valid Firebase user JWT token

Given that I have a Firebase project, but no development environment that supports the Firebase SDK, how can I get a valid Firebase JWT for one of the users in the Firebase project? I am able to create cloud functions in the project, and I tried making a function for this (in TypeScript), but to no avail:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
export const login = functions.https.onRequest((req, res) => {
const email: string = req.query.email || req.body.email;
const password: string = req.query.password || req.body.password;
admin.auth().signInWithEmailAndPassword(email, password);
admin.auth().currentUser.getIdToken(true).then((idToken: any) => {
functions.logger.info("token: " + idToken, {structuredData: true});
res.status(200).send(idToken);
}).catch((error: any) => {
functions.logger
.info("could not get token: " + error, {structuredData: true});
res.status(500).send(error);
});
});
This code wont deploy due to these errors:
Property 'signInWithEmailAndPassword' does not exist on type 'Auth'.
Property 'currentUser' does not exist on type 'Auth'.
Here's the JS script I got from a colleague for this:
// Import the functions you need from the SDKs you need
const { initializeApp } = require("firebase/app");
const { getAuth, signInWithEmailAndPassword } = require("firebase/auth");
// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
apiKey: "API-key-here",
authDomain: "my-app.firebaseapp.com",
databaseURL: "https://my-app-default-rtdb.firebaseio.com",
projectId: "my-app",
storageBucket: "my-app.appspot.com",
messagingSenderId: "sender-id-here",
appId: "app-id-here",
measurementId: "measurement-id-here"
};
const app = initializeApp(firebaseConfig);
const auth = getAuth();
signInWithEmailAndPassword(auth, "user#example.com", "user-password-here")=
.then((userCredential) => {
console.log(userCredential.user.accessToken);
})
.catch((error) => {
console.log(error.message);
});

firebaseConfig.default.auth promise rejection error

I am trying to signup user with facebook but i am seeing very rigid error and it seems there is no solved help out there so i am asking again
thats my code
async function signInWithFacebook() {
// const appId = Expo.Constants.manifest.extra.facebook.appId;
Facebook.initializeAsync(appid)
const permissions = ['public_profile']; // Permissions required, consult Facebook docs
const {
type,
token,
} = await Facebook.logInWithReadPermissionsAsync(
{permissions}
);
if(type == "success"){
const credential = initFirebase.auth.FacebookAuthProvider.credential(token);
initFirebase.auth().signInWithCredential(credential)
.catch(err => {
console.log(err)
})
}
}
i am using appid in strings but i have not added it here hope you understand that.
and the error is this
this is my firebase config file code
import firebase from "firebase/app"
import "firebase/firestore"
import "firebase/auth"
// Your web app's Firebase configuration
var firebaseConfig = {
apiKey: "xxxxxxxx",
authDomain: "xxxxxx",
databaseURL: "xxxxxx",
projectId: "xxxx",
storageBucket: "xxxxx",
messagingSenderId: "xxxxx",
appId: "xxxxx"
};
// Initialize Firebase
const initFirebase = firebase.initializeApp(firebaseConfig);
export default initFirebase
variable values are hidden because of privacy .i worked with firestore and that worked but i am seeing issue with auth with facebook .
i am using react native , firebase , expo and not firebase sdk
You don't have to register a Facebook App for Login with Facebook using Firebase. You can use the below code with Firebase Facebook Authentication enabled in the console.
export const loginWithFacebook = (accessToken) => {
const credential = initFirebase.auth.FacebookAuthProvider.credential(accessToken);
return new Promise((resolve, _reject) => {
signInWithCredential(credential).then(response => {
resolve(response);
});
});
};

Setting up firebase with react native

I am having difficulties setting up firebase with react native.
src/components/firebase.js
import firebase from '#firebase/app';
import '#firebase/auth';
const firebaseConfig = {
apiKey: "AIzaSyCJshsr47p3IriQGF0V4gaVd-bCuo_HN6A",
authDomain: "auth-8f2ec.firebaseapp.com",
databaseURL: "https://auth-8f2ec.firebaseio.com",
projectId: "auth-8f2ec",
storageBucket: "auth-8f2ec.appspot.com",
messagingSenderId: "1013084520551"
};
const Firebase = firebase.initializeApp(firebaseConfig);
export default Firebase;
src/components/LoginForm.js
First I import Firebase
import Firebase from './firebase';
then authentication is done this way.
Firebase.auth().signInWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(() => {
Firebase.auth().createUserWithEmailAndPassword(email, password)
.then(this.onLoginSuccess.bind(this))
.catch(this.onLoginFail.bind(this));
});
};
src/App.js
Firebase is imported in this way
import Firebase from './components/firebase';
The component will mount method runs this way.
componentWillMount(){
Firebase.auth().onAuthStateChanged((user) => {
console.log(Firebase.auth());
if(user){
console.log('firebase login success');
this.setState({ loggedIn: true});
}
else{
console.log('firebase login failed');
this.setState({ loggedIn: false });
}
});
};
The result is a spinner. Something is wrong with the way firebase is being imported.
Help would be appreciated. Thanks in advance.
Thanks in advance.
Strange you're importing with "#" at the beginning. Try to import this way:
import * as firebase from 'firebase/app';
import 'firebase/auth';

Resources