"Cannot read properties of undefined (reading 'params')" - javascript

I'm trying after successful login, to redirect the user on another page.
I'm on Svelte JS, and i use Routify, Firebase for Auth and datas
my imports :
import { Router, redirect, routes, goto } from "#roxi/routify";
my function to verify form and redirect when user is ok
// submit form
let params = {};
function handleSubmission({params}) {
hasBeenClicked = true;
if (isValidEmail && isValidPassword) {
// Trim email and password
let trimEmail = email.trim();
let trimPassword = password.trim();
// Initialize Firebase
const auth = getAuth();
const db = getFirestore();
// Test connection
signInWithEmailAndPassword(auth, trimEmail, trimPassword)
.then((userCredential) => {
// Signed in
const user = userCredential.user;
console.log('user',user.uid);
// Try to redirect to the page with the params
// doc : src/pages/admin/[business].svelte corresponds to /admin/:business, where :business // is a parameter.
$goto(`/adminUser/userPage:params?user=${user.uid}`, params);
})
.catch((error) => {
const errorCode = error.code;
const errorMessage = error.message;
console.log(errorCode, errorMessage);
});
}
}
when i submit i got this :
Cannot read properties of undefined (reading 'params')
I've been read the doc, but I can't figure out what to do and how to put the user in the params.

Related

Google signin with signInWithRedirect always takes me back to the login page

I'm having a hard time getting the Firebase signInWithRedirect with google to work. Below is the doc I've been looking at: https://firebase.google.com/docs/auth/web/google-signin.
I have a login page which contains a button. When the button is clicked it take you to google sign in page. However every time I sign in with google it redirects me back to the login page of my app. Part of the code is shown below:
login() {
const auth = getAuth();
signInWithRedirect(auth, provider);
console.log("AAA")
auth.onAuthStateChanged((user) => {
console.log("BBB")
if (user) {
this.$router.push('home')
} else {
getRedirectResult(auth)
.then((result) => {
console.log("WIN0")
// 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(token)
console.log(user)
console.log("WIN")
}).catch((error) => {
console.log("ERROR0")
// 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);
console.log(errorCode)
console.log(errorMessage)
console.log(email)
console.log(credential)
console.log("ERROR")
// ...
});
}
})
From the console, I only ever see the log AAA, but I don't see any other logs at all. What am I missing? Thank you.
I should also mention that I'm doing this in vue js but I don't think it matters.
So the problem was that I have onAuthStateChanged within the login function. Since the SignInWithRedirect takes to a different page and then redirects back to the page where it was called, in vue I basically moved the onAuthStateChanged to the mounted lifecycle hook.
mounted() {
auth.onAuthStateChanged((user) => {
console.log("BBB")
if (user) {
this.$router.push('home')
} else {
getRedirectResult(auth)
.then((result) => {
console.log("WIN0")
// 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(token)
console.log(user)
console.log("WIN")
}).catch((error) => {
console.log("ERROR0")
// 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);
console.log(errorCode)
console.log(errorMessage)
console.log(email)
console.log(credential)
console.log("ERROR")
// ...
});
}
})
}

Cannot POST Sign In Result from Firebase

Hey all so I'll keep it short. I've used firebase to log users in and recently implemented 'Sign In with Apple'. The following code is able to open the pop up and let users sign in with their Apple ID but the moment they hit sign in my web app remains unaffected and the console shows the following error:
The script that I'm using is following:
import { initializeApp } from "https://www.gstatic.com/firebasejs/9.4.1/firebase-app.js";
import { getAuth ,OAuthProvider, signInWithRedirect, getRedirectResult, signInWithPopup, signOut } from "https://www.gstatic.com/firebasejs/9.4.1/firebase-auth.js";
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);
const provider = new OAuthProvider('apple.com');
provider.addScope('email');
provider.addScope('name');
signInWithPopup(auth, provider)
.then((result) => {
// The signed-in user info.
const user = result.user;
// Apple credential
const credential = OAuthProvider.credentialFromResult(result);
const accessToken = credential.accessToken;
const idToken = credential.idToken;
// ...
})
.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 credential that was used.
const credential = OAuthProvider.credentialFromError(error);
// ...
});
getRedirectResult(auth)
.then((result) => {
const credential = OAuthProvider.credentialFromResult(result);
if (credential) {
// You can also get the Apple OAuth Access and ID Tokens.
const accessToken = credential.accessToken;
const idToken = credential.idToken;
}
// The signed-in user info.
const user = result.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.email;
// The credential that was used.
const credential = OAuthProvider.credentialFromError(error);
// ...
});
When I click the 'index.ts:116' link I get the error at the following line:
Any input shall be appreciated. Please let me know if I can provide more information. Thanks!

Firebase - email is not defined

I am trying to build a function that allows user to change their password. The problem is when I am getting the current user's data it shows that the email is null.
Everything works on Firebase, users are creating in Firebase auth system.
Here is a part of my code
reauthenticate = (currentPassword) => {
var user = firebase.auth().currentuser;
var cred = firebase.auth.EmailAuthProvider.credential(user.email, currentPassword);
user.reauthenticateWithCredential(cred);
}
reauthenticate(currentPassword).then(() => {
var user = firebase.auth().currentuser;
user.updatePassword(newPassword).then(() => {
alert("Password changed");
window.location.replace("./index.html");
}).catch((error) => {
console.log(error);
})
});
What console shows is Uncaught TypeError: Cannot read properties of undefined (reading 'email') at reauthenticate (password.js:15:64) at changePassword (password.js:27:9)
its currentUser not currentuser. Capital U.
const user = firebase.auth().currentUser;

How to export async var from a login

I am trying to export user info from login to other modules.
export function login(){
console.log("entrando A LOGIN")
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth()
.signInWithPopup(provider)
.then((result) => {
/** #type {firebase.auth.OAuthCredential} */
var credential = result.credential;
var token = credential.accessToken;
// The signed-in user info.
let user = result.user;
module.exports.user=user /// it says it does not provide user variable when in this ine I am
doing it
}etc....
/// it says it does not provide user variable but I do it.Thanks I am new
You don't need to use module.exports at all as far as I know. And you really don't want to mix them with es6 modules.
// google-auth.js
export function login() {
const provider = new firebase.auth.GoogleAuthProvider();
return firebase.auth()
.signInWithPopup(provider)
.then((result) => {
const credential = result.credential;
const token = credential.accessToken;
const user = result.user;
return user;
})
.catch(error => {
// you deal with errors that happen here
})
}
You get the user object by returning it from the function. The function returns a promise though so, if you try and do something like const user = login() it's not going to work To import the function into another file and use it in a way that you can access the user object, you'd do something like this:
// login.js
import { login } from './path/to/google-auth.js'
const authInstance = login();
From the official docs:
import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";
const auth = getAuth();
signInWithPopup(auth, provider)
.then((result) => {
// This gives you a Google Access Token. You can use it to access the Google API.
const credential = GoogleAuthProvider.credentialFromResult(result);
const token = credential.accessToken;
// The signed-in user info.
const user = result.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.email;
// The AuthCredential type that was used.
const credential = GoogleAuthProvider.credentialFromError(error);
// ...
});

Firebase .getIdToken() returns invalid token

I'm trying to make just a simple authentication app with electron and firebase redirect, but if the user is already logged in and I use the firebase.auth().currentUser.getIdToken() to get the IdToken of that user, but when i try that token in
firebase.auth().signInWithCredential(credential) I get the error that says ERROR: auth/invalid-credential
Here is my code front-end
firebase.auth().onAuthStateChanged( async function (user) {
if (user) {
// User is signed in.
var user = await firebase.auth().currentUser;
if (user != null) {
await firebase.auth().currentUser.getIdToken().then(function(idToken) {
window.location.href = "electron://"+idToken;
}).catch(function(error) {
console.log(error)
});
}
} else {
// No user is signed in.
document.getElementById("user_div").style.display = "none";
document.getElementById("login_div").style.display = "block";
}
});
Here is my code back-end
app.on('second-instance', (event, commandLine, workingDirectory) => {
if (commandLine[2]) {
var url = commandLine[2].split('/')
var id_token = url[2]
console.log('id: ', id_token)
// Build Firebase credential with the Google ID token.
var credential = firebase.auth.GoogleAuthProvider.credential(id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential)
.then((success)=>{
myWindow.loadFile('./scr/welcome.html')
console.log('RESULT: ',success)
})
.catch((error) => {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
console.log('ERROR:', errorMessage)
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
console.log('ERROR:', credential)
// ...
})
}
I'm missing something or doing something wrong?
That's not how ID tokens work. The purpose of an ID token is to pass to your backend, so that it can validate the identity of the signed in user, and perform some action on their behalf. It's not valid for signing in on the client again. You might want to review the documentation on use of ID tokens to learn how this works.
signInWithCredential only works with Google Auth when you correctly construct a GoogleAuthProvider credential. There is plenty of sample code in the API documentation for that.

Categories