Guides
Create a policy
A policy defines whether a use case can be accessed/executed or not.
Intro
A policy is a class that implements the UCPolicy
interface.
libmodulor
provides policies that are commonly used.
But some apps need specific policies.
Example
As an example, you can define a policy to allow some use cases only to "Pro" users.
@injectable()
export class ProUCPolicy<
I extends UCInput | undefined = undefined,
OPI0 extends UCOPIBase | undefined = undefined,
OPI1 extends UCOPIBase | undefined = undefined,
> implements UCPolicy<I, OPI0, OPI1>
{
constructor(
@inject('UserDataStore') private userDataStore: UserDataStore,
) {}
public async canBeExecutedPreAuth(): Promise<boolean> {
return false;
}
public async exec({
uc,
}: UCPolicyInput<I, OPI0, OPI1>): Promise<UCPolicyOutput> {
const out = defaultUCPolicyOutput();
const user = await this.userDataStore.get(uc.auth.user.id);
if (!user) {
return out;
}
out.allowed = user.plan === 'Pro';
return out;
}
}
In this example, we get the information from a hypothetical UserDataStore
but you are free to inject anything you need in here.