Home > database >  What's the right firestore architecture for managing client API keys?
What's the right firestore architecture for managing client API keys?

Time:10-23

Can someone put me in the right direction? I need a Firestore collection to store user-related API keys. This means there are:

  • API key
  • User ID
  • (Created At, maybe other meta fields in the future)

So sometimes I want to retrieve a list of all API keys that belong to a user. But oftentimes, the scenario is that my API is getting a request with an API key attached and then I need to quickly validate whether this API key exists. It’s the first time playing with Firestore for me. And I’m just insecure about how to structure the collection. Should the API key be the ID? And will I be able to efficiently get a list of API keys that have a specific UID too?

CodePudding user response:

Can someone put me in the right direction? I need a Firestore collection to store user-related API keys.

The simplest Firestore structure I can think of might look like this:

Firestore-root
  |
  --- users (collection)
       |
       --- $uid (document)
            |
            --- apiKeys: ["apiKeyOne", "apiKeyTwo", "apiKeyThree"] //Array
            |
            --- uid: "userId" //String
            |
            --- createdAt: October 21, 2021 at 2:46:19 PM UTC 3 //Timestamp

So sometimes I want to retrieve a list of all API keys that belong to a user.

Assuming that you are using Firebase Authentication, to do that, simply use the following lines of code:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    var uidRef = db.collection("users").doc(user.uid);
    //Process the data
  }
});

But oftentimes, the scenario is that my API is getting a request with an API key attached and then I need to quickly validate whether this API key exists.

To solve that, you have to check whether a specific API key already exists using:

var queryByApiKey = db.collection("users").where("apiKeys", "array-contains", "apiKeyToCheck");

Should the API key be the ID?

No, there is no need for that.

And will I be able to efficiently get a list of API keys that have a specific UID too?

Sure, as already explained above.

  • Related