firebase authentication persistence in electron - javascript

I'm trying to sign in a user with signInWithEmailAndPassword() but after signing the user and moving to another BrowserWindow object and initializing the auth object again with the same firebase app .. the auth.currentUser property shows as null.
I tried using the onAuthStateChanged observer as following :
onAuthStateChanged(auth,(user) => {
console.log(user)
})
and I also tried setting the persistence using setPersistence :
onAuthStateChanged(auth,(user) => {
setPersistence(auth,browserLocalPersistence).then(console.log(user))
})
both ended up giving me a null user

Related

Vue 3 Firebase Auth get *any* user data by id? [duplicate]

This question already has an answer here:
How to get FirebaseUser from a uid?
(1 answer)
Closed 8 months ago.
New to vue/firebase. I was able to lookup how to pull up “current user” data from auth no problem but trying to write a js composable that I can pass in any user id (not necessarily current user) and it will return the user object or at least displayName.
All the docs/vids I can find on the topic reference getting info on *current user *only not another user. From the Google Docs it says I should be able to do this in the "Retrieve user data" section. Closest model to Vue code-wise seems to be “Node.Js” but it isn't working.
Here's what I've got in getUserById
import { getAuth } from 'firebase/auth'
const getUserById = (u) => { // u = user id
const userData = null
getAuth()
.getUser(u)
.then((userRecord) => {
// See the UserRecord reference doc for the contents of userRecord.
console.log(`Successfully fetched user data: ${userRecord.toJSON()}`);
userData = userRecord
})
.catch((error) => {
console.log('Error fetching user data:', error);
});
return { userData }
}
export default getUserById
The error I get is getUser is not a function. I tried adding getUser to the import but same error.
There is no way to look up information about just any user by their UID in the client-side APIs of Firebase as that would be a security risk. There is an API to look up a user by their UID in the Admin SDK, but that can only be used on a trusted environment (such as your development machine, a server you control, or Cloud Functions/Cloud Run), and not in client-side code.
If you need such functionality in your app, you can either wrap the functionality from the Admin SDK in a custom endpoint that you then secure, or have each user write information to a cloud database (such as Realtime Database or Firestore) and read it from there.
Also see:
How to get FirebaseUser from a uid?
Firebase get user by ID
Is there any way to get Firebase Auth User UID?

firebase - if statement not executed after query

I have integrated firebase in a vue app. I have a navbar that can show some user informations like name and status, and I need to query firebase realtime database after the login to set the needed informations inside my store that will manage application state.
I'm using this code when the navbar component is mounted but the if() statement will be not executed. The strange thing is that I'm able to log each user during the loop. Is there something wrong or another solution to achive this?
onValue(query(ref(db, 'Users'), orderByKey('uid')), users => {
users.forEach( (user) => {
let userData = user.val()
// the console will log each user correctly
console.log(userData)
if( userData.uid == store.currentUser.uid ) {
console.log('called')
console.log(userData)
}
})
})

Issues With Persistent React Native Login

I am trying to make a persistent login system with React Native and expo but am running into several issues. I read online that AsyncStorage is the way to do this. I wrote three functions for dealing with login, all seen below.
// use asyncstorage to log in the user
logInUser = async (uid) => await AsyncStorage.setItem('loggedin', uid)
// set loggedin to null in asyncstorage
logOutUser = async() => await AsyncStorage.setItem('loggedin', null)
// returns userid if user is logged in
getUserState = async() => await AsyncStorage.getItem('loggedin')
On my login screen, I use the following onPress event to log in the user.
onPress={() => {
db.logInUser(this.user[1]).then(() => {
//this.removekey(this.user[1]) // delete the user's one-time-login key
this.props.navigation.navigate('Home') // navigate to home
})
}}
Also on the login screen, I use the following componentDidMount function to send the user to the homescreen if they are already logged in.
async componentDidMount() {
db.getUserState().then(loggedin => {
if (loggedin != null) { // log the user in if they have a uid in asyncstorage
this.props.navigation.navigate('Home')
}
})
}
The app will not have a "logout" feature, and users should stay logged in until either buying a new phone or reinstalling the app. Unfortunately this code does not work, and actually automatically logs the user in. I was thinking that it could maybe relate to the user with id=0, but removing this user from the database had no effect. The code of the actual application is here.

Create accounts in Firebase Auth from custom admin website while I'm logged in

I'm doing a web application using Angular 8 and AngularFire.
On my custom website, a user with the admin privilege, can create accounts for other people.
To do this, I have read that I need to:
Create a second auth reference and use that to create users.
Reason: if we use our default auth reference, when the createUserWithEmailAndPassword() method creates the new user, the
user is signed in automatically, overriding our current session (the
logged in user on our custom website).
I have tried:
async createUserWithEmailAndPassword(email: string, password: string): Promise<string> {
// 1. A new auth session
let secondaryApp = firebase.initializeApp(environment.firebaseConfig, 'Secondary');
// 2. Create the account
const user = await secondaryApp.auth().createUserWithEmailAndPassword(email, password);
// 3. Sign out the user created
await secondaryApp.auth().signOut();
// 4. Make the auth session null to ensure that it's deleted
secondaryApp = null;
if (user.user.uid) {
// User created
return Promise.resolve(user.user.uid);
} else {
// Error
return Promise.reject();
}
}
Error received (happens when I call the method a second time):
FirebaseError: Firebase: Firebase App named 'Secondary' already exists
(app/duplicate-app).
My thoughts/steps were:
Create a new auth session.
Create the user.
Sign out the user created.
Delete the auth session created.
All clear and ready to create a new account in any moment.
What I'm doing wrong?
My goal is to be able to create accounts while I'm logged in on my custom website.
An educated guess is that you get that error message the second time you call your own createUserWithEmailAndPassword method. The reason for that is that you've already created an app named Secondary on the previous call, and didn't remove that app.
The easiest solution is to check if the Secondary app already exists before creating it.
let secondaryApp = firebase.app("Secondary");
if (!secondaryApp) {
secondaryApp = firebase.initializeApp(environment.firebaseConfig, 'Secondary');
}

Interacting with the current user object in firebase requires me the type user.user, why must I type user twice?

I am trying to add a registration page for users to register on a firebase database in a web page(it's wordpress).
For example when I create the user and then try a simple console log to check the created user's uid like so:
auth.createUserWithEmailAndPassword(email, password)
.then(function(user){
console.log(user.uid);
});
I get an "undefined". But when I attempt to do the same thing by typing
auth.createUserWithEmailAndPassword(email, password)
.then(function(user){
console.log(user.user.uid);
});
It works correctly.
Why is this?
I followed the documentation for initialising firebase and then set the reference to the auth as
var auth = firebase.auth();
Thanks for any help. I am new to both Javascript and Firebase.
From the documentation
createUserWithEmailAndPassword(email, password) returns firebase.Promise containing non-null firebase.auth.UserCredential
Clicking firebase.auth.UserCredential shows you it has the structure
{
user: nullable firebase.User,
credential: nullable firebase.auth.AuthCredential,
operationType: (nullable string or undefined),
additionalUserInfo: (nullable firebase.auth.AdditionalUserInfo or undefined)
}
So you are accessing the user property of the returned UserCredential object which you have named user.
If you wanted to, you could change user to userCredential to help clarify what it is and avoid future confusion.
auth.createUserWithEmailAndPassword(email, password)
.then(function(userCredential){
console.log(userCredential.user.uid);
});

Categories