You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Policy is a composable to determine whether the user can perform certain actions. It provides streamlined and consistent authorization mechanism that can be integrated to other components.
Basic usage
// Define policy.functionuseCanCreatePost(post: Post){constuser=getLoggedInUser()returnusePolicy(({ allow, deny })=>{if(post.author===user){returnallow()}returndeny()})}// Use it.constcanCreatePost=useCanCreatePost(post)canCreatePost.value.ok// boolean
Policy can return response code that indicates "why" the user is not allowed to perform action. Using this, we may tell user the reason on UI.
<scriptsetuplang="ts">function useCanCreatePost(post:Post) {const user =getLoggedInUser()// Define code as generics.returnusePolicy<'ok'|'not-author'>(({ allow, deny }) => {// Set code on allow/deny.returnpost.author===user?allow('ok'):deny('not-author') })}const canCreatePost =useCanCreatePost(post)</script>
<template>
<div>
<divv-if="canCreatePost.ok">
<!-- Show post -->
</div>
<divv-else>
<pv-if="canCreatePost.is('not-author')">
You are not the author of this post.
</p>
</div>
</div>
</template>
Pending state
Sometimes, we need to wait for api call to determine the final authorization. In this case, use pending. The ok becomes null in this case.
In the real world, app, we should create a local usePolicy composable that inherits this composable and inject currently logged in user instance for easier access.
interfacePolicyHelpers<Code=any>extendsSefirotPolicyHelpers<Code>{user: User}functionusePolicy<Code=any>(fn: (helpers: PolicyHelpers<Code>)=>PolicyResponse<Code>): Policy<Code>{constuser=getLoggedInUser()returnuseSefirotPolicy((helpers)=>{returnfn({ ...helpers, user })})}functioncanCreatePost(): Policy{// Now the user object is available.returnusePolicy({ user, allow, deny }=>{returnpost.author===user
? allow()
: deny()})})
The text was updated successfully, but these errors were encountered:
Policy
is a composable to determine whether the user can perform certain actions. It provides streamlined and consistent authorization mechanism that can be integrated to other components.Basic usage
API
Using "code"
Policy can return response code that indicates "why" the user is not allowed to perform action. Using this, we may tell user the reason on UI.
Pending state
Sometimes, we need to wait for api call to determine the final authorization. In this case, use
pending
. Theok
becomesnull
in this case.Real world app usage
In the real world, app, we should create a local
usePolicy
composable that inherits this composable and inject currently logged in user instance for easier access.The text was updated successfully, but these errors were encountered: