Advanced

Jul 11, 2024

Opening your backend to business partners

Introduction

Let's say you have an app that's fully functional and live, but now a large company contacts you wanting to form a partnership. They want to integrate your app into their existing system. For example, imagine you have an accounting app and you are being approached by a large restaurant chain. They want to use your app's functionality within their platform to manage their finances more efficiently. Instead of having their 500 employees learn a new tool, they prefer integrating your app into their sophisticated management software.

This raises a few key questions… How do you securely open your backend to them? Once you secure your backend, how do you give them access? This guide will walk you through the steps using Firebase, but similar steps need to be taken for other backends like Supabase as well.


Setting up security

The first and most critical step is setting up security rules. An introductory guide to Firebase Security Rules can be found here. Begin by understanding what your partner needs access to. Once you know which collections they need to interact with, you can proceed to create a secure setup.


1.   Create a partner account:
  • Create an account for your partner using email authentication or another verification method.

  • Assign a Firebase role to this account - give them a role so that you know exactly what they can manage and that you have 100% control over it.


2.   Assign a role:

Use Python to assign a custom role. If you need help with setting up Python to interact with your Firebase, check out our Python for Firebase guide. Here's a snippet to set the role to "partner":

# Give role of "partner"
def set_custom_user_claims(uid):
    try:
        # Set custom user claims
        auth.set_custom_user_claims(uid, {'role': 'partner'})
        print(f'Custom claims set for user {uid}')
    except Exception as error:
        print(f'Error setting custom claims: {error}')

3.   Define security rules:

Use the assigned role within Firebase Security Rules to control access:

function isPartner() {
    return (exists(request.auth.token.role) && request.auth.token.role == 'partner');
}

match /your_collection/{document} {
    allow create: if isPartner();
    allow read: if isPartner();
    allow update: if false;
    allow delete: if false;
}


Inside this collection, only your partner can create & read the collection.

Now that your database is secure, we can start giving the partner access. So how do we do that? 


Creating API endpoints

With security in place, you can now create API endpoints usingFirebase Cloud Functions. These endpoints will allow your partners to interact with your database.  


1. Set up Cloud Functions:

Create a Cloud Function to serve as an API endpoint. Here's an example of a function that fetches data:

const functions = require('firebase-functions');
const admin = require('firebase-admin');

exports.fetchData = functions.https.onRequest(async (req, res) => {
    try {
        const demo = await admin.firestore().collection('demo').get();
        const results = demo.docs.map(doc => ({
            name: doc.data().name
        }));
        res.status(200).json(results);
    } catch (error) {
        if (error.message === 'Unauthorized') {
            return res.status(401).send('Unauthorized');
        } else if (error.message === 'Forbidden') {
            return res.status(403).send('Forbidden');
        }
        console.error('Error:', error);
        res.status(500).json({ error: 'Internal Server Error' });
    }
});

2. Deploy and share:
  • Deploy the CloudFunction from inside FlutterFlow.

  • Share the function URL with your partners, who can then call it with a POST request. 


Use case

Imagine you've set up the necessary Cloud Functions. Your restaurant chain partner can now fetch financial data directly into their system, add new entries, or even update existing ones - all without leaving their platform. This seamless integration not only enhances their workflow but also strengthens your partnership by providing them with a tailored solutions.


Best practices

  • Limit access in a way that you only grant the minimum required permissions to your partners.

  • Perform regular audits periodically. Review access logs to monitor for any unusual activity. These can be viewed inside your Firebase Cloud Function logs.

  • Update security rules whenever new collections or endpoints are created. Don't forget to update rules when requirements change, more partners are added or your backend structure gets more complex.


Conclusion

By following these steps, you can securely open your backend to business partners, allowing them to integrate your app's functionality into their systems. This not only adds to their operations but also opens up new opportunities for collaboration and growth for your own business.