Skip to main content

Security rules

Squid Cloud provides powerful authorization features to help you control access to your different entities, such as databases, backend functions, APIs, and more. This allows you to protect your data and ensure that only authorized users can perform certain actions.

Using the Squid Backend SDK, you can apply various decorators to your functions to enable authorization checks. These decorators act as guards to restrict access to your entities, based on various criteria such as user roles, permissions, and more.

If a client attempts to access a secured entity but the authorization function returns false, indicating that the user is not authorized, the client will receive an Error with the following details

{
"statusCode": 401,
"message": "UNAUTHORIZED"
}

For example, let's say you have a users collection and want to ensure that users can only read their own user record. You can write a backend function annotated with @secureCollection like this

Backend code
import { secureCollection, SquidService } from '@squidcloud/backend';
import { QueryContext } from '@squidcloud/client';

type User = { id: string; email: string; age: number };

export class ExampleService extends SquidService {
@secureCollection('users', 'read')
secureUsersRead(context: QueryContext<User>): boolean {
const userAuth = this.getUserAuth();
if (!userAuth) {
return false;
}
const userId = userAuth.userId;
return context.isSubqueryOf('id', '==', userId);
}
}

If a user tries to read users other than themselves, the secureUsersRead function will return false, causing the client function to throw an error:

Client code
// This function will throw an error
async function readAllUsers(squid: Squid): Promise<User[]> {
return await squid.collection<User>('users').query().snapshot();
}

In summary, Squid provides powerful authorization and security features that allow you to easily control access to your data and resources.

Explore