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.
Before creating your own, check the policies reference to see if libmodulor
does not already provide it.
If you don't find your "bonheur" there, check out the example below.
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.