I guess that my store from vuejs is resetting my authorization. I also get the error message Cannot read property 'home' of undefined in the header component. I don't know why this is not working. I tried debugging.
This is what i have:
In my nuxt.config.js i set plugins to firebase:
plugins: [
'~/plugins/firebase.js'
],
Then here is my firebase.js file:
import firebase from 'firebase/app'
import 'firebase/auth'
var firebaseConfig = {
apiKey: "MYAPIKEY",
authDomain: "AUTHDOMAIN",
databaseURL: "DBURL",
projectId: "PROJECTID",
storageBucket: "STORAGEBUCKET",
messagingSenderId: "MESSAGINGSENDERID",
appId: "APPID",
measurementId: "MEASUREMENTID"
};
!firebase.apps.length ? firebase.initializeApp(firebaseConfig) : ''
export const auth = firebase.auth()
export default firebase
I don't know if it has anything to do with my error but for purpose i just put it in.
Then for my registration page i registrate users with their gmail account i have a function in methods like this:
async registersocial() {
try {
const provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then((result) => {
this.account.email = result.user.email
this.account.naam = result.additionalUserInfo.profile.given_name
this.account.achternaam = result.additionalUserInfo.profile.family_name
this.$store.dispatch('users/registersocial', this.account).catch(err => {
this.errmsg = err
})
});
} catch(err) {
this.errmsg = err
}
}
And this fires to the store to register a user set a cookie and set the user in the store i do it like so:
async registersocial({ commit }, account) {
const token = await auth.currentUser.getIdToken();
const { email, uid } = auth.currentUser;
Cookie.set('access_token', token);
commit('SET_USER', {
email,
uid
});
this.$router.push('profiel')
const users = firebase.database().ref('Gebruikers/')
users.once('value', function(snapshot){
const naam = account.naam
const achternaam = account.achternaam
const email = account.email
const google = "Google"
var sameemail = null
snapshot.forEach(function(childSnapshot) {
const data = childSnapshot.exportVal()
if(data.Email == email) {
sameemail = email
}
})
if(sameemail != email) {
users.push({
Voornaam: naam,
Achternaam: achternaam,
Email: email,
registerMethod: google
})
}
})
}
And then for the cookie i set i do this:
import JWTDecode from 'jwt-decode';
import cookieparser from 'cookieparser';
export const actions = {
nuxtServerInit({commit}, {req}) {
if(process.server && process.static) return;
if(!req.headers.cookie) return;
const parsed = cookieparser.parse(req.headers.cookie);
const accessTokenCookie = parsed.access_token;
if(!accessTokenCookie) return;
const decoded = JWTDecode(accessTokenCookie);
if(decoded) {
commit('users/SET_USER', {
uid: decoded.user_id,
email: decoded.email
})
}
}
}
Please let me know what i am doing wrong. If u need any more code please let me know.
Related
The error appears on line 49! I've already looked to see if it was a spare key and apparently it isn't... I've tried to add a key and I couldn't either, I've tried to put ; And it didn't work either, I don't know what else to try...
I can't find the error at all and I didn't find help with similar errors...
Thanks in advance for your help!
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "/firebase-app.js";
import { getFirestore, doc, setDoc, getDoc, collection, addDoc, query, where } from "/firebase-firestore.js";
// 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
const firebaseConfig = {
apiKey: "",
authDomain: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
const db = getFirestore(app);
const q = query(collection(db, "pacientes"));
const x = query(q, where("cpf", "==", true));
async function GetADocument(){
const querySnapshot = await getDoc(x);
const docSnap = await getDocs(querySnapshot);
querySnapshot.forEach((doc) => {
then(docSnap.exists(pesquisa = cpf))
nome.value = docSnap.data().nome;
endereco.value = docSnap.data().endereco;
bairro.value = docSnap.data().bairro;
cidade.value = docSnap.data().cidade;
uf.value = docSnap.data().uf;
cep.value = docSnap.data().cep;
rg.value = docSnap.data().rg;
cpf.value = docSnap.data().cpf;
nascimento.value = docSnap.data().nascimento;
tel.value = docSnap.data().tel;
cel.value = docSnap.data().cel;
titulo.value = docSnap.data().titulo;
zona.value = docSnap.data().zona;
secao.value = docSnap.data().secao;
pai.value = docSnap.data().pai;
mae.value = docSnap.data().mae;
cath
alert("usuário não encontrado");
});
} // line 49
btnbuscar.addEventListener("click", GetADocument);
</script>
I got an error "_config.firebase.auth is not a function. (In '_config.firebase.auth()','_config.firebase.auth' is undefined)
This error appears when submitting a registration form.
I run Firebase version 9.6.5
Can anyone spot where I went wrong in my config.js and RegScreen.js files?
import firebase from 'firebase/compat/app';
import '#firebase/auth';
import '#firebase/firestore';
const firebaseConfig = {
apiKey: '',
authDomain: 'to-do-weather.firebaseapp.com',
databaseURL: 'https://DATABASE_NAME.firebaseio.com',
projectId: 'to-do-weather',
storageBucket: 'to-do-weather.appspot.com',
messagingSenderId: '',
appId: '',
};
let app;
if (firebase.apps.length === 0) {
app = firebase.initializeApp(firebaseConfig)
} else {
app = firebase.app();
}
export { firebase };
const onRegPress = () => {
if (password !== confirmPassword) {
alert("Passwords don't match.")
return
}
firebase
.auth()
.createUserWithEmailAndPassword(email, password)
.then((response) => {
const uid = response.user.uid
const data = {
id: uid,
email,
fullName,
};
const usersRef = firebase.firestore().collection('users')
usersRef
.doc(uid)
.set(data)
.then(() => {
navigation.navigate('Home', {user: data})
})
.catch((error) => {
alert(error)
});
})
.catch((error) => {
alert(error)
});
}
If you are trying to use namespaced syntax then you must import compat versions of all Firebase services too. Try changing your imports to:
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
// add /compat ^
The compat version would be removed eventually so I would recommend updating your code and following the new syntax as mentioned in the documentation
i have i problem with this file.js ; i try to start the application but the console give me the error on the title of this post (TypeError: _firebase.default.analytics is not a function. (In '_firebase.default.analytics()', '_firebase.default.analytics' is undefined)). I'm using firebase ase database and React Native to create this app based on a common chat where differents user can join and pass messages; This is the code:
import firebase from 'firebase';
import { useCallback } from 'react';
class Fire {
constructor() {
this.init()
this.checkAuth()
}
init = () => {
if(!firebase.apps.length){
var firebaseConfig = {
apiKey: "AIzaSyCSptHIogcurTROMvzp_QB7vQ8srIbnwBk",
authDomain: "login-with-firebase-23e8e.firebaseapp.com",
projectId: "login-with-firebase-23e8e",
storageBucket: "login-with-firebase-23e8e.appspot.com",
messagingSenderId: "1099034898191",
appId: "1:1099034898191:web:b8a3a66be2d5a49d83987a",
measurementId: "G-73M58E50QL"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
firebase.analytics();
}
};
checkAuth = () =>{
firebase.auth().onAuthStateChanged(user => {
if(!user){
firebase.auth().signInAnonymously();
}
});
};
send = messages => {
messages.forEach(item => {
const message = {
text: item.text,
timestamp: firebase.database.ServerValue.TIMESTAMP,
user: item.user
}
this.db.push(message)
})
};
get db() {
return firebase.database().ref("messages");
};
parse = message => {
const {user, text, timestamp} = message.val()
const {key: _id} = message;
const createdAt = new Date(timestamp);
return {
_id,
createdAt,
text,
user
};
}
get = callback => {
this.db.on("child_added", snapshot => callback(this.parse(snapshot)));
};
get uid(){
return (firebase.auth().currentUser || {}).uid;
}
}
export default new Fire();
Authenticate Using Google Sign-In
I'm using Firebase to Sign in a user using Advanced: Handle the sign-in flow manually. I have set up Firebase like so:
firebaseConfig.js
// Config file
import * as firebase from "firebase";
const config = {
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",
appId: "app-id",
measurementId: "G-measurement-id",
};
export default !firebase.apps.length ? firebase.initializeApp(config) : firebase.app();
I then import firebase in another file to authenticate and sign in a user.
LoginUser.js
_isUserEqual = (googleUser, firebaseUser) => {
if (firebaseUser) {
var providerData = firebaseUser.providerData;
for (var i = 0; i < providerData.length; i++) {
if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
providerData[i].uid === googleUser.getBasicProfile().getId()) {
// We don't need to reauth the Firebase connection.
return true;
}
}
}
return false;
}
_onSignIn = googleUser => {
console.log('Google Auth Response', googleUser);
// We need to register an Observer on Firebase Auth to make sure auth is initialized.
var unsubscribe = firebase.auth().onAuthStateChanged(firebaseUser => {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
if (!this._isUserEqual(googleUser, firebaseUser)) {
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(
googleUser.idToken,
googleUser.accessToken
);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch(error => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
});
} else {
console.log('User already signed-in Firebase.');
}
});
}
_signInWithGoogleAsync = async () => {
try {
const result = await Google.logInAsync({
androidClientId: "AndroidClientId",
scopes: ['profile', 'email'],
});
if (result.type === 'success') {
this._onSignIn(result)
return result.accessToken;
} else {
return { cancelled: true };
}
} catch (e) {
return { error: true };
}
}
When I execute the authentication, I receive an error:
Possible unhandled Promise Rejection (id: 0):
TypeError: undefined is not an object (evaluating '_firebaseConfig.default.GoogleAuthProvider.credential') showing that firebase.auth.GoogleAuthProvider is undefined.
Screenshot of the error
Are there any reasons as to why this could be the case? Thanks.
I'm trying to do a query to the database, to get all documents of sub-collection "roles" to redirect to different routes.
let userRef1 = db.collection('users').doc(currentUser.uid).collection('roles')
let cont = 0
let rol = ''
let rolStatus = ''
userRef1.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
cont++
rol = doc.data().rol
rolStatus = doc.data().status
});
import { firestore } from "../../firebase";
export const loadCategories = () => {
return (dispatch, getState) => {
firestore
.collection("CATEGORIES")
.get()
.then((querySnapshot) => {
if (!querySnapshot.empty) {
querySnapshot.forEach((doc) => {
console.log(doc.id, "=>", doc.data());
});
}
})
.catch((error) => {
console.log(error);
});
};
};
I have a collection of users including uid just like yours. And for each user, it contains a sub-collection called friends.
Currently, I'm using the following code for my project without having any issues.
module.exports = ({ functions, firestore }) => {
return functions.firestore.document('/users/{uid}').onDelete((event) => {
const userFriendsRef = getFriendsRef(firestore, uid);
userFriendsRef.get().then(snapshot => {
if (snapshot.docs.length === 0) {
console.log(`User has no friend list.`);
return;
} else {
snapshot.forEach(doc => {
// call some func using doc.id
});
}
}
}
};
function getFriendsRef(firestore, uid) {
return firestore.doc(`users/${uid}`).collection('friends');
}
Give it a try to fix your code from
db.collection('users').doc(currentUser.uid).collection('roles')
to
db.doc(`users/${currentUser.uid}`).collection('roles')
It is not clear what you are doing with the rol and status variables. You have declared them as though you are storing a single value, yet you are returning an array of roles and iterating through them.
With regards to getting the results, if your browser supports ES6, then you could do the following:
let userRef1 = db.collection(`users/${currentUser.uid}/roles`)
let cont = 0
let rol;
let rolStatus;
return userRef1.get()
.then(querySnapshot => {
// Check if there is data
if(!querySnapshot.empty) {
// Create an array containing only the document data
querySnapshot = querySnapshot.map(documentSnapshot => documentSnapshot.data());
querySnapshot.forEach(doc => {
let {rol, status} = doc;
console.log(`rol: ${rol} - status: ${status}`);
});
} else {
console.log('No data to show');
}
})
.catch(err => {
console.error(err);
});
Please note: I've only tested this with the Node SDK
// Firebase App (the core Firebase SDK) is always required and must be listed first
import * as firebase from "firebase/app";
// Add the Firebase products that you want to use
import "firebase/auth";
import "firebase/firestore";
const firebaseConfig = {
apiKey: "AIzaSyDNdWutrJ3Axpm-8ngNhzkzcw1g3QvkeFM",
authDomain: "books-7bd8b.firebaseapp.com",
databaseURL: "https://books-7bd8b.firebaseio.com",
projectId: "books-7bd8b",
storageBucket: "books-7bd8b.appspot.com",
messagingSenderId: "385706228283",
appId: "1:385706228283:web:a3c2c9585dd74d54693a1e",
};
firebase.initializeApp(firebaseConfig);
export const firebaseAuth = firebase.auth();
export const firestore = firebase.firestore();
export default firebase;
You should check if it always exists before doing your logic:
userRef1.get().then(function(querySnapshot) {
if(querySnapshot)
{
querySnapshot.forEach(function(doc) {
...you thing
}
})