Skip to main content

Security and access control

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

Squid's access control is managed in the Squid backend using TypeScript functions. To mark a function as pertaining to access control, you apply one or more decorators, which are labels that start with an @. For example, the following function uses the @secureDatabase decorator to ensure only authenticated users have access to the build-in database:

Backend code
  @secureDatabase('all', 'built_in_db') // Decorator marks function as securing a database
allowAccessToBuiltInDb(): boolean {
return this.isAuthenticated();
}

Using Squid decorators and the Squid Backend SDK, you can restrict access to your entities based on various criteria such as user roles and permissions.

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, the following code ensures only the specified user can read their record in a collection called users:

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

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);
}
}

Based on this security functionality, a client who attempts to run the following query will return an error because this function attempts to access multiple user records not belonging to the user:

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

Explore

To learn more about access controls for individual features, check out the following documentation: