Package Exports
- pundit-ts
- pundit-ts/dist/index.js
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (pundit-ts) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
Pundit-TS - Plain Typescript Authorization Library
Pundit-TS is an authorization library highly-inspired by the pundit gem.
Usage
Install the package first:
npm i -S pundit-ts
Declare your models.
// models.ts
class User {}
class Post {}
Declare your actions for each model.
// actions.ts
export type UserActions = "create" | "delete" | "update";
export type PostActions = "create" | "delete" | "update";
Declare your policies
// policies.ts
import { PunditPolicy } from "pundit-ts";
import { Post, User } from "./models";
import { PostActions, UserActions } from "./actions";
export class PolicyContext {
// your orm related properties might go here
}
export class PostPolicy
implements PunditPolicy<PolicyContext, Post, PostActions>
{
async canCreate() {
return false;
}
async canDelete() {
return false;
}
async canUpdate() {
return false;
}
handlesAction(action) {
return action === "create" || action === "delete" || action === "update";
}
handlesModel(object) {
return object instanceof User;
}
filter(ctx) {
// modify context
}
}
export class UserPolicy
implements PunditPolicy<PolicyContext, User, UserActions>
{
async canCreate() {
return false;
}
async canDelete() {
return false;
}
async canUpdate() {
return false;
}
handlesAction(action) {
return action === "create" || action === "delete" || action === "update";
}
handlesModel(object) {
return object instanceof User;
}
filter(ctx) {
// modify context
}
}
Create your Pundit instance:
// pundit.ts
import { Pundit } from "pundit-ts";
import { PostPolicy, UserPolicy } from "./policies";
export const pundit = new Pundit<PolicyContext>()
.register(new UserPolicy())
.register(new PostPolicy());
Authorize your actions in a fully type-safe way.
// index.ts
import { PolicyContext } from "./policies";
import { Post } from "./models";
import { pundit } from "./pundit";
const ctx = new PolicyContext();
const post = new Post();
await pundit.authorize(ctx, post, "create");