I am working on a web application (beginner level) and I use firebase for authentification and database. I can create a new account and register it on my firebase authentification dashboard without issue, but nothing inside .then((userCredential) => { } is working (alerts don't show up, I can't register the account on firebase database etc....
I checked on chrome console and no errors show up, and I have no error messages from .catch as well.
How can I fix this so what's inside .then is working?
Thank you!
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js'
import { getAuth, createUserWithEmailAndPassword } from 'https://www.gstatic.com/firebasejs/9.15.0/firebase-auth.js'
import { getFirestore, doc, getDoc, getDocs, collection } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-firestore.js";
import { getDatabase, ref, set } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-database.js";
const firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
const app = initializeApp(firebaseConfig);
const db = getFirestore();
const auth = getAuth();
const database = getDatabase()
submitData.addEventListener('click', (e) => {
var name = document.getElementById('full_name').value
var email = document.getElementById('email').value;
var password = document.getElementById('psw').value;
alert(email)
// do verification
// Move on with Auth
createUserWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
const user = userCredential.user
alert("user created")
})
.catch(function(error) {
// Firebase will use this to alert of its errors
var error_code = error.code
var error_message = error.message
alert(error_message)
alert('not working')
})
})
If you're using form element then just use e.preventDefault() to stop page from reloading, place it before the variables.
Related
I am trying to add Google sign-in to my web application. I am able to open the redirect window for the popup, but am unable to know when the sign in is complete and get the user info. This is my code:
import {initializeApp} from "https://www.gstatic.com/firebasejs/9.9.2/firebase-app.js";
import { getAuth,GoogleAuthProvider,signInWithRedirect,getRedirectResult } from "https://www.gstatic.com/firebasejs/9.9.2/firebase-auth.js";
const firebaseConfig = {
apiKey: "...",
authDomain: "...",
projectId: "...",
storageBucket: "...",
messagingSenderId: "...",
appId: "...",
};
const app = initializeApp(firebaseConfig)
const auth = getAuth(app);
const provider = new GoogleAuthProvider(app);
document.getElementById("sign-in").onclick = function() {
getAuth().useDeviceLanguage()
signInWithRedirect(auth, provider)
getRedirectResult(auth)
.then((result) => {
// This gives you a Google Access Token. You can use it to access Google APIs.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.user;
console.log(user)
})
.catch((error) => {
// Handle Errors here.
const errorCode = error.code;
const errorMessage = error.message;
// The email of the user's account used.
const email = error.customData.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});
}
I am now able to implement push notifications with Firebase Cloud Messaging, and the push notifications themselves are delivered, but I am having trouble changing their content.
The default title is "This site has been updated in the background", but I changed it to any text.
Environment
Vue CLI
TypeScript
main.ts
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import './registerServiceWorker'
import firebase from 'firebase/compat/app';
import { getMessaging, getToken } from "firebase/messaging";
const firebaseConfig = {
apiKey: "xxx",
authDomain: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const app = createApp(App)
installElementPlus(app)
app
.use(store)
.use(router)
.component('MqResponsive', Vue3Mq.MqResponsive)
.mount('#app')
const messaging = getMessaging(firebaseApp);
const vapidKey = {
vapidKey:
"xxx",
};
// Messaging
getToken(messaging, { vapidKey: 'xxx' }).then((currentToken) => {
if (currentToken) {
// Send the token to your server and update the UI if necessary
console.log("currentToken : ", currentToken);
// ...
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
firebase-messaging-sw.js
import firebase from 'firebase/compat/app';
import { onBackgroundMessage } from "firebase/messaging/sw";
import { getMessaging, getToken, onMessage } from "firebase/messaging";
const firebaseConfig = {
apiKey: "xxx",
authDomain: "xxx",
projectId: "xxx",
storageBucket: "xxx",
messagingSenderId: "xxx",
appId: "xxx",
measurementId: "xxx"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
const messaging = getMessaging(firebaseApp);
const vapidKey = {
vapidKey:
"xxx",
};
// Messaging
getToken(messaging, { vapidKey: 'xxx' }).then((currentToken) => {
if (currentToken) {
// Send the token to your server and update the UI if necessary
console.log("currentToken : ", currentToken);
// ...
} else {
// Show permission request UI
console.log('No registration token available. Request permission to generate one.');
// ...
}
}).catch((err) => {
console.log('An error occurred while retrieving token. ', err);
// ...
});
onMessage(messaging, (payload) => {
console.log('Message received. ', payload);
// ...
});
onBackgroundMessage(messaging, (payload) => {
console.log('[firebase-messaging-sw.js] Received background message ', payload);
self.addEventListener('push', async function (event) {
event.waitUntil(
self.registration.showNotification('title', {
body: 'body'
})
);
});
});
The image is localhost, but deploying to the web did not change the result.
I also tested on Firebase Messaging and downloaded as a PWA and again the results did not change.
What is the problem??
Thank you in advance!
I have a VueJS application and a firebase project, I'm trying to access the realtime database to add data to it but it's not working and it's not logging anything.
I have a firebase.js file :
import firebase from 'firebase/compat/app'
const firebaseConfig = {
apiKey: "myapp",
authDomain: "myapp.firebaseapp.com",
projectId: "myapp",
storageBucket: "myapp",
messagingSenderId: "myapp",
appId: "myapp"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
export default firebaseApp;
And i have this create user method in a file called DataService.js :
import firebase from "../firebase";
import 'firebase/compat/database';
const db = firebase.database();
create(user) {
db.ref('users' + user.login).set({
username: user.login,
email: user.password,
profile_picture : false
},(error)=>{
if(error){
console.log(error)
}else{
console.log('all good');
}
});
}
In my component, I have a method called SaveUser that i'm calling in the submit
saveuser(){
var data = {
login: this.login,
password: this.password,
isvalid: false
};
DataService.create(data);
},
What am I doing wrong ? I'm new to firebase and I don't really know what's not working
Your firebaseConfig variable is missing a databaseURL property, which is pretty much the only key that is required for your code to be able to find the Realtime Database on the server. So add that key/value, and try again.
Here is the code signInWithEmailAndPassword works perfectly but when I try to acquire a token the error is always thrown TypeError: user.getToken is not a function.
import app from "./base.js";
app.auth()
.signInWithEmailAndPassword(email, password)
.then(function (user) {
user.getToken().then(function (token) {
localForage.setItem("token", token); // store the token
console.log("pusing forward");
history.push("/");
});
}).catch((error) => {
console.log("err: " + error);
});
base.js
import firebase from "firebase/app";
import "firebase/auth";
const app = firebase.initializeApp({
apiKey: process.env.REACT_APP_FIREBASE_KEY,
authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
});
export default app;
Comments welcome thanks.
According to the API documentation for signInWithEmailAndPassword() user is a UserCredential object. It doesn't have a getToken method. Perhaps you want to use its user property to get a User object, which has a getIdToken() method.
user.user.getIdToken().then(token => { ... })
Here is a peak at the object user1 returned after calling signInWithEmailAndPassword(email, password)
I am using firebase authentication using social media accounts. After signing up, I am unable to log out.
The following is my Javascript code:
<script src="https://www.gstatic.com/firebasejs/4.1.3/firebase.js"></script>
<script>
// Initialize Firebase
var config = {
apiKey: "*******",
authDomain: "******",
databaseURL: "******",
projectId: "*******",
storageBucket: "******",
messagingSenderId: "*******"
};
firebase.initializeApp(config);
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// User is signed in.
var displayName = user.displayName;
var email = user.email;
var photoURL = user.photoURL;
user.getToken().then(function(accessToken) {
console.debug('user', user);
document.getElementById('sign-in-status').textContent = 'Signed in';
document.getElementById('name').textContent = JSON.stringify( displayName )
document.getElementById('email').textContent = JSON.stringify(email)
document.getElementById('account-details').textContent = JSON.stringify({
displayName: displayName,
email: email,
photoURL: photoURL
});
});
} else {
console.log('not logged in');
/*document.getElementById('sign-in-status').textContent = 'Signed out';
document.getElementById('sign-in').textContent = 'Sign in';
document.getElementById('account-details').textContent = 'null';
*/
}
});
// User is signed out.
firebase.auth().signOut().then(function() {
// Sign-out successful.
signOutSuccessUrl: 'https://url.html'
}).catch(function(error) {
// An error happened.
});
</script>
And in the html I am calling it by:
<button class="btn btn-primary" onclick="signOut()"><i class="fa fa-sign-out">/i> Log out</button>
But on clicking the button nothing happens.
I even tried putting the signout segment in a function, but that didn't help.
Any kind of help would be greatly appreciated. Thanks.
if your click event handler calls a signOut method, then you have to define it somewhere. like:
window.signOut = function signOut(_e) {
firebase.auth().signOut().then(function() {
// Sign-out successful.
}).catch(function(error) {
// An error happened.
});
}