How to get currentUser on first load in firebase-auth without requesting - firebase

I'm using firebase authentication, and my navbar is depend on if user is logged in or not. When i load the website, if user not logged out before, he should still stay as logged in.But, Firebase onAuthStateChanged listener returns user after 100-300ms, so my navbar can't decide if user is logged in or not.So, navbar shows login and signup button for 300ms, then firebase returns user, and navbar shows dashboard and logout button.
I'm using vue, I've tried saving UID and username on localstorage, but i'm concerning about security. what if someone manually changed localstorage data? Also, user may logged out, but stay logged in my manually setting localStorage.setItem('user', ....)
Navbar.vue
<div v-if="user.uid" class="flex row space-b">
// userpic, photo, logout button
</div>
<div v-else>
// login and signup button
</div>
vuex
state: {
user: {
uid: null,
photoURL: null,
username: null,
},
},
I tried not to mount Vue instance until onAuthStateChanged listener returns something, but this can't be a good solution, hence i'm rendering website nearly 300ms late.

Anyway, i saved it in cookie. when website loads, if cookie is exists i render navbar as if user logged in, and then double check after firebase listener returns

This is caused because beforeEach is getting executed before firebase has fully finished initialization.
You can use onAuthStateChanged observer to make sure the vue app is initialized only after the firebase is fully initialized.
One way to fix it is to wrap the vue initialization code in main.js(new Vue( ... )) with onAuthStateChanged like this:
let app;
const auth = getAuth();
onAuthStateChanged(auth, (user) => {
console.log("user", user);
if (!app) {
new Vue({
router,
vuetify: new Vuetify(options.Vuetify),
render: (h) => h(App),
}).$mount("#app");
}
});
for version 7 firebase you can check this repo file
https://github.com/ErikCH/FirebaseTokenFrontend/blob/master/src/main.js

Related

Prevent React Native remount of component on context value change

In a chat app I am building I want to deduct credits from a user's account, whenever the users sends a message and when a chat is initiated.
The user account is accessible in the app as a context and uses a snapshot listener on a firestore document to update whenever something changes in the user account document. (See code samples 1. and 2. at the bottom)
Now whenever anything in the userAccount object changes, all of the context providers children (NavigationStructure and all its subcomponents) are re-rendered as per React's documentation.
This, however causes huge problems on the chat screen that also uses this context:
The states that are defined there get re-initalized whenever something in the context changes. For example, I have a flag that indicates whether a modal is visible, default value is visible. When I go onto the chat screen, hide the modal, change a value manually in the firestore database (e.g. deduct credits) the chat screen is rerendered and the modal is visible again. (See code sample 3.)
I am very lost what the best way to solve this issue is, any ideas?
Solutions that I have thought about:
Move the credits counter to a different firestore document and deduct the credits once per day, but that feels like a weird workaround.
From Googling it seems to be possible to do something with useCallback or React.memo, but I am very unsure how.
Give up and become a wood worker...seems like running away from the problem though.
Maybe it has something to the nested react-navigation stack and tab navigators I'm using within NavigationStructure?
Desperate things I have tried:
Wrap all sub-components of NavigationStructrue in "React.memo(..)"
Make sure I don't define a component within another component's body.
Look at loads of stack overflow posts and try to fix things, none have worked.
Code Samples
App setup with context
function App() {
const userData = useUserData();
...
return (
<>
<UserContext.Provider value={{ ...userData }}>
<NavigationStructure />
</UserContext.Provider>
</>
}
useUserData Hook with firestore snapshot listener
export const useUserData = () => {
const [user, loading] = useAuthState(authFB);
const [userAccount, setUserAccount] = useState<userAccount | null>();
const [userLoading, setUserLoading] = useState(true);
useEffect(() => {
...
unsubscribe = onSnapshot(
doc(getFirestore(), firebaseCollection.userAccount, user.uid),
(doc) => {
if (doc.exists()) {
const data = doc.data() as userAccount & firebaseRequirement;
//STACK OVERFLOW COMMENT: data CONTAINES 'credits' FIELD
...
setUserAccount(data);
}
...
}
);
}, [user, loading]);
...
return {
user,
userAccount,
userLoading: userLoading || loading,
};
};
Code Sample: Chat screen with modal
export const Chat = ({ route, navigation }: ChatScreenProps): JSX.Element => {
const ctx = useContext(UserContext);
const userAccount = ctx.userAccount as userAccount;
...
//modal visibility
const [modalVisible, setModalVisible] = useState(true);
// STACK OVERFLOW COMMENT: ISSUE IS HERE.
// FOR SOME REASON THIS STATE GET'S RE-INITALIZED (AS true) WHENEVER
// SOMETHING IN THE userAccount CHANGES.
...
return (
<>
...
<Modal
title={t(tPrefix, 'tasklistModal.title')}
visible={ModalVisible}
onClose={() => setModalVisible(false)}
footer={
...
}
>
....
</Modal>
...
</>)
}
Any change to the context does indeed rerender all consumer components whether they use the changed property or not.
But it will not unmount and mount the component which is the reason why your local state gets initialized to the default value.
So the problem is not the in the rerenders (rarely the case) but rather <Chat ... /> or one of it's parent component unmounting due to changes in the context.
It is hard to tell from the partial code examples given but I would suggest looking at how you use loading. Something like loading ? <div>loading..</div> : <Chat ... /> would cause this behaviour.
As an example here is a codesandbox which illustrates the points made.
This is a characteristic of React Context - any change in value to a context results in a re-render in all of the context's consumers. This is briefly touched on in the Caveats section in their docs, but is expanded on in third-party blogs like this one: How to destroy your app's performance with React Context.
You've already tried the author's suggestion of memoization. Memoizing your components won't prevent re-initialization, since the values in the component do change when you change your user object.
The solution is to use a third-party state management solution that relies not on Context but on its own diffing. Redux, Zustand, and other popular libraries do their own comparison so that only affected components re-render.
Context is really only recommended for values that change infrequently and would require full-app re-renders anyway, like theme changes or language selection. Try replacing it with a "real" state management solution instead.

Firebase Persisting Auth with Stack Navigator

Attempting to let Firebase persist authentication within the app.js of React Native by doing the following:
There is a sign in page that envokes auth() sign in via Firebase, which works fine, and redirects to the home page via navigation.replace("Home"); however, once the app is closed and relaunched on the emulator, it redirects back to sign in.
This is seemingly what the App.js looks like, I assume that the AuthStateChanged would be prevalent as depicted below, however, user is not accessed in App.js as it is established in SignIn.js, when the Firebase credentials are sent, but I assume it would be similar to this layout?
const App = () => {
var initialRoute = null
React.useEffect(() => {
const unsubscribe = auth().onAuthStateChanged(user => {
if(user) {
initialRoute = "Home"
}
else {
initialRoute = "SignIn"
}
})
return unsubscribe
}, []);
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false,
}}
initialRouteName={initialRoute}
>
The reason it needs to affect the initial route, and not just redirect anyone who reopens to the home page, is because after registration, there are extra steps included that adjust the database, such as location mapping and etc., therefore, the redirection has to occur within the initial route.
Thanks for your assistance.
This is not how you build a navigation flow with react-navigation. But that's no problem since theres a guide here on the official react-navigation side on how to do that: https://reactnavigation.org/docs/auth-flow/
Fixed by setting two different returns within App.js, one for if the user is authenticated with Firebase that sets the initialRoute to "Home", and one for else that sets it to "SignUp", seems to work fine.

How to know if firebase.messaging().requestPermission has been previously called using react-native-firebase

I have a React Native app that uses Firebase Cloud Messaging with the react-native-firebase package.
I am doing this on the first screen of a React Native app, so after 5 seconds, the user will be sent to a new screen which explains why push notifications are useful, and gives them a button to launch the dialog where they can accept or decline the permission.
setTimeout(() => {
firebase.messaging().hasPermission()
.then(enabled => {
if (enabled) {
// user has permissions
} else {
// user doesn't have permission
this.props.navigation.navigate('EnableNotificationPermissionScreen')
}
});
},
5000);
In the EnableNotificationPermissionScreen screen, there is a button like this:
<Button onPress={this.onSetNotificationPref.bind(this)} title="Set Notification Preference" color="#4ab2fc"/>
Which is handled by an event like this:
onSetNotificationPref() {
firebase.messaging().requestPermission()
.then(() => {
// User has authorized
firebase.analytics().logEvent('messaging_permission_accepted');
this.props.navigation.navigate('App');
})
.catch(error => {
// User has rejected permissions
firebase.analytics().logEvent('messaging_permission_rejected');
this.props.navigation.navigate('App');
});
}
If the user accepts, everything works as I would hope, and the user will have the permission, and will not navigate to that screen again.
However, if the user rejects the permission, I do not want to navigate them to that screen again. As-is, they will be navigated there again because hasPermission will be false. Also, clicking the button to execute requestPermission on that screen will do nothing, as the OS will block requestPermission().
In the examples I have seen, requestPermission is called whenever the permission is not enabled (with no custom screen like this); and so either the dialog pops up, or it doesn't. However, in the flow that I am trying to achieve, I want to navigate to this custom screen only if the user does not have permission because they have not been asked. If they have been asked and declined, they should not be navigated to that screen.
Is there any way to achieve that using the functions in firebase.messaging(), or do I have to use persistent storage like async-storage to track on my own whether the dialog has been shown?

How do I login a user with Meteor

I've added accounts-password and useraccounts:unstyled
I've included the signin template in my footer.html -
{{#if showSignIn}}
{{> atForm state="signIn"}}
{{/if}}
I'm hard coding the creation of users as the app starts up -
import { Accounts } from 'meteor/accounts-base'
if (!Acounts.findUserByEmail('aidan#gmail.com')) {
Accounts.createUser({
username: 'Aidan',
email: 'aidan#gmail.com',
password: 'securePassword'
});
}
It's just that I can't work out how to actually log my user in. I've tried simply entering the password and email address into the form. That doesn't work (the form error says 'Login Forbidden').
I've tried adding the following line (to the same file as my account creation code) -
accountsServer.validateLoginAttempt(()=>{return true;});
Unsurprisingly that doesn't do anything.
I've tried add a submit event into my footer.js file -
Template.footer.events({
'submit form'(event) {
console.log('submitted');
const email = document.getElementById('at-field-email').value;
const password = document.getElementById('at-field-password').value;
Meteor.loginWithPassword(email, password);
},
});
I can see that the event is firing, but when I try Meteor.user() in the console I still get null.
There's typo in if (!Acounts.findUserByEmail('aidan#gmail.com')) (it should have been Accounts). The user isn't being created.
To get a super simple functional login with a single hard coded user -
Add the accounts-password package and the ui user accounts package.
> meteor add accounts-password
> meteor add useraccouts:unstyled
The accounts-password package handles the actual logging in. The user accounts:unstyled packages provides a set of templates for accounts management.
Then add the login form to a template.
<template name="templateWithLogin">
{{> atForm state="signIn"}}
</template>
Lastly create a user (e.g. in /server/main.js).
import { Accounts } from 'meteor/accounts-base';
if (!Accounts.findUserByEmail('user#gmail.com')) {
Accounts.createUser({
username: 'User',
email: 'user#gmail.com',
password: 'securePassword'
});
}
This should be everything needed to get a functional login form. There's loads of tutorials online for creating additional functionality. The main documentation is here.
you can use {{>loginButtons}} to get the ui and {{#if currentUser }} for the functionality.

After login user list is not showing in meteor?

After login user details is not showing.But if I use
Meteor.userId();
its showing the userid
But if I use
Meteor.user();
Its showing undefined.Why it so?
Meteor.userId() would've been set already, Meteor.user() would not have its subscription fullfilled on page load. What you would need is to wrap it in
Tracker.autorun(() => {
const currentUser = Meteor.user()
... code that needs the current user.
})

Resources