45 lines
1.3 KiB
TypeScript
45 lines
1.3 KiB
TypeScript
import type { Policy } from '$customType'
|
|
import type { User } from '$lib/models'
|
|
import { BrandPolicy, UserPolicy } from './policies'
|
|
|
|
type PolicyList = Record<string, Policy>
|
|
|
|
class PolicyManager {
|
|
readonly #policies: PolicyList
|
|
|
|
constructor(policiesList: Record<string, PolicyList>) {
|
|
this.#policies = {}
|
|
|
|
Object.entries(policiesList).forEach((policiesListEntry) => {
|
|
const policyFamilyName = policiesListEntry[0],
|
|
policyFamilySuite = policiesListEntry[1]
|
|
Object.entries(policyFamilySuite).forEach((policySuiteEntry) => {
|
|
const policyName = `${policyFamilyName}:${policySuiteEntry[0]}`,
|
|
policy = policySuiteEntry[1]
|
|
this.#policies[policyName] = policy
|
|
})
|
|
})
|
|
}
|
|
|
|
public can(policy: string, user: User): boolean {
|
|
const resolvedPolicy = this.resolvePolicy(policy)
|
|
return resolvedPolicy.call(resolvedPolicy, user)
|
|
}
|
|
|
|
private resolvePolicy(policyName: string): Policy {
|
|
if (!this.#policies[policyName]) {
|
|
throw new Error(`Missing policy ${policyName}`)
|
|
}
|
|
|
|
return this.#policies[policyName]
|
|
}
|
|
}
|
|
|
|
const policies = new PolicyManager({
|
|
user: new UserPolicy().getPolicies(),
|
|
brand: new BrandPolicy().getPolicies(),
|
|
})
|
|
|
|
export default function can(policy: string, user: User): boolean {
|
|
return policies.can(policy, user)
|
|
}
|