Securing data
Manage access to data using client authentication and backend functionality
Now that we have set up authentication, we can use our Squid backend project to start securing our data. Both read and write operations be can be secured using the @secureCollection
and @secureDatabase
decorators from the Squid Backend SDK.
To begin
Navigate to the generated example-service.ts
file and add the following function:
type User = { id: string; email: string; age: number };
export class ExampleService extends SquidService {
@secureCollection('users', 'read')
secureUsersRead(context: QueryContext<User>): boolean {
/** Checks whether the user is authenticated */
return this.isAuthenticated();
}
}
Deploy the changes to your backend project using the Squid CLI:
squid deploy --apiKey YOUR_API_KEY --environmentId TARGET_ENVIRONMENT_ID
A client that will try reading data from the users
collection will have to be authenticated in order to access the
data.
// This function will throw an error if the user is not authenticated
async function readUsers(squid: Squid): Promise<User[]> {
return await squid.collection<Users>('users').query().snapshot();
}
If the client is not authenticated, any attempt to read data from the users
collection will result in an Error
with
these details:
{
"statusCode": 401,
"message": "UNAUTHORIZED"
}
What's going on here?
This is where Squid as a "middle tier" comes into play. Now that we've deployed our security function, whenever a client
makes a query using squid.collection('users').query
, the secureUsersRead
function will be called before any data is
returned.
If the function returns true, the user is able to access the data, but if the function returns false, the user
will be considered unauthorized, and the request will fail. The isAuthenticated
call is a built-in Squid Backend SDK
utility function that checks for the presence of a valid auth ID token (which we set in the previous step). If the
token is not present, the request will fail.
The above is just one example of how you can secure your data by writing backend functions in Squid. By following these steps, you'll be able to create a secure backend that authorizes user actions.