Day 7: Securing Your App with Firebase Rules and Authentication


Today, you’ll focus on securing your e-commerce app by implementing Firebase Security Rules for Firestore and authentication checks in your React Native app. This ensures that users can only access their data and prevents unauthorized access to sensitive operations.

What You Will Do Today:

  1. Write Firestore Security Rules to restrict access.
  2. Add authentication checks in the app for protected screens.
  3. Test the security setup in Firebase and the app.

Step 1: Writing Firestore Security Rules

  1. Open your Firebase project in the Firebase Console.
  2. Navigate to Firestore Database > Rules.
  3. Update the rules to restrict access based on user authentication:
   rules_version = '2';
   service cloud.firestore {
     match /databases/{database}/documents {
       // Allow users to read and write their own orders
       match /orders/{orderId} {
         allow read, write: if request.auth != null && request.auth.uid == resource.data.userId;
       }

       // Allow users to read products
       match /products/{productId} {
         allow read: if true;
       }
     }
   }

Explanation:

  • Orders: Only authenticated users can access their orders (userId must match the authenticated user’s uid).
  • Products: All users can read product data (no authentication required).
  1. Publish the rules to activate them.

Step 2: Adding Authentication Checks in the App

  1. In App.js, create a function to check authentication status and navigate accordingly:
   import React, { useEffect } from 'react';
   import { NavigationContainer } from '@react-navigation/native';
   import { createStackNavigator } from '@react-navigation/stack';
   import auth from '@react-native-firebase/auth';
   import LoginScreen from './screens/LoginScreen';
   import ProductList from './screens/ProductList';
   import ProductDetail from './screens/ProductDetail';
   import UserProfile from './screens/UserProfile';
   import OrderHistory from './screens/OrderHistory';
   import CartScreen from './screens/CartScreen';
   import CheckoutScreen from './screens/CheckoutScreen';

   const Stack = createStackNavigator();

   export default function App() {
     useEffect(() => {
       const unsubscribe = auth().onAuthStateChanged((user) => {
         if (!user) {
           navigationRef.current?.navigate('LoginScreen');
         }
       });
       return unsubscribe;
     }, []);

     return (
       <NavigationContainer>
         <Stack.Navigator>
           <Stack.Screen name="LoginScreen" component={LoginScreen} options={{ title: 'Login' }} />
           <Stack.Screen name="ProductList" component={ProductList} options={{ title: 'Products' }} />
           <Stack.Screen name="ProductDetail" component={ProductDetail} options={{ title: 'Product Details' }} />
           <Stack.Screen name="CartScreen" component={CartScreen} options={{ title: 'Cart' }} />
           <Stack.Screen name="CheckoutScreen" component={CheckoutScreen} options={{ title: 'Checkout' }} />
           <Stack.Screen name="UserProfile" component={UserProfile} options={{ title: 'Profile' }} />
           <Stack.Screen name="OrderHistory" component={OrderHistory} options={{ title: 'Order History' }} />
         </Stack.Navigator>
       </NavigationContainer>
     );
   }
  1. Protect sensitive screens by redirecting unauthenticated users to the LoginScreen.
See also  Day 5: Implementing Authentication with JWT in React Native

Step 3: Testing Authentication and Security

  1. Test Unauthorized Access:
  • Try accessing Firestore orders without authentication via the Firebase Console or a REST client like Postman. You should get a permission denied error.
  1. Test User-Specific Data:
  • Log in with one user and place an order.
  • Log in with a different user and confirm they cannot access the first user’s order.
  1. Test Authentication Flow in the App:
  • Start the app without logging in. You should be redirected to the LoginScreen.
  • Log in to access the ProductList, CartScreen, and other protected screens.

Optional: Debugging Firebase Security Rules

  1. Use the Firebase Rules Simulator to test security rules.
  2. Simulate read and write operations as different users and check if the rules work as expected.

Summary

Today, you secured your app with Firebase Security Rules and implemented authentication checks in the app. Users can now only access their data, ensuring privacy and security.

Tomorrow, you’ll work on sending order confirmation and status updates via email or push notifications.


Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.