In this article we learn the basics about integration of React Redux and Firebase and we end up with working To-Do application. In this article we’re gonna take it and add authentication to it. In order to do so, we’re gonna need to do these steps:
- Add Sign In component
- Add listener for auth state, sign in and sign out
- Track auth state in Redux
- Make sure user can access app only if signed in
- Change database rules in firebase console
Adding Sign In Component
This component will handle two things:
- It will have one button and when the user clicks on it he’ll sign in using google OAuth.
- It will redirect user to the application if the user is already signed in
render takes care of the point 1 and componentWillUpdate takes care of point 2.
Adding Listener For Auth State
We need 3 function here. One to listen if the user sign in or sign out. One to actually sign in user and one to sign him or her out. We’ll need to create new reference in Firebase config and then use it to add these functions.
signOut just change the state of user. When the state changes fetchUser will get notified and it will update redux store. If the user signed in it will update it with the user object. And if the user signed out it will update it with
null. Now we need to actually keep track of the auth state in the store
Adding Protected Routes
We need to make sure of one thing. When the user is not authenticated. And tries to access private route. Then he or she should be redirected to sign in. We can achieve this with higher order component. This component will simply take another component and renders it when user is authenticated. If not, it will redirect to sign in page.
Tracking Auth State in Redux
We just need to add new reducer to take care of auth state and then add it to
Changing Database Rules In Firebase
Now when we added authentication to our application it would be good thing to change the rules for database. The rule will say, only signed in users can access it. To change it go to your Firebase console and set it as on this picture.
That’s it. It didn’t take a long time. And we got Google OAuth working in matter of couple minutes. Now our application is authenticated and protected. Now the user can sign in, create new tasks and complete them. The source code is available at GitHub. Feel free to clone it extend it and play with it. If you have any questions don’t hesitate and ask. If you liked the story feel free to clap for it. Thanks for your time and see you at the next one.