polizy-setup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Polizy Setup

Polizy 安装设置

Guide for installing and configuring polizy in your project.
为你的项目安装和配置polizy的指南。

When to Apply

适用场景

  • User says "add authorization to my project"
  • User says "install polizy" or "set up polizy"
  • User has no existing polizy configuration
  • User asks about initial setup or storage selection
  • User is starting a new project with authorization needs
  • 当用户说“为我的项目添加授权功能”
  • 当用户说“安装polizy”或“配置polizy”
  • 用户尚未配置过polizy
  • 用户询问初始设置或存储选择相关问题
  • 用户启动一个需要授权功能的新项目

Priority Table

优先级表

PriorityTaskNotes
CriticalInstall package
npm install polizy
CriticalDefine schemaRelations, actions, mappings
CriticalChoose storageInMemory (dev) or Prisma (prod)
ImportantTest setupVerify with a permission check
OptionalConfigure optionsDepth limits, logging
优先级任务说明
关键安装包
npm install polizy
关键定义Schema关系、操作、映射
关键选择存储InMemory(开发环境)或Prisma(生产环境)
重要测试配置通过权限检查验证
可选配置选项深度限制、日志

Step-by-Step Setup

分步设置指南

Step 1: Install

步骤1:安装

bash
npm install polizy
bash
npm install polizy

or

or

pnpm add polizy
pnpm add polizy

or

or

yarn add polizy
undefined
yarn add polizy
undefined

Step 2: Define Schema

步骤2:定义Schema

Create your authorization model:
typescript
import { defineSchema } from "polizy";

const schema = defineSchema({
  // Define relationship types
  relations: {
    owner: { type: "direct" },    // Direct user → resource
    editor: { type: "direct" },
    viewer: { type: "direct" },
    member: { type: "group" },    // Group membership
    parent: { type: "hierarchy" } // Folder → file
  },

  // Map actions to relations that grant them
  actionToRelations: {
    delete: ["owner"],
    edit: ["owner", "editor"],
    view: ["owner", "editor", "viewer"]
  },

  // Optional: How permissions propagate through hierarchies
  hierarchyPropagation: {
    view: ["view"],  // view on parent → view on children
    edit: ["edit"]
  }
});
创建你的授权模型:
typescript
import { defineSchema } from "polizy";

const schema = defineSchema({
  // 定义关系类型
  relations: {
    owner: { type: "direct" },    // 直接用户 → 资源
    editor: { type: "direct" },
    viewer: { type: "direct" },
    member: { type: "group" },    // 群组成员
    parent: { type: "hierarchy" } // 文件夹 → 文件
  },

  // 将操作映射到对应的授权关系
  actionToRelations: {
    delete: ["owner"],
    edit: ["owner", "editor"],
    view: ["owner", "editor", "viewer"]
  },

  // 可选:权限在层级结构中的传播规则
  hierarchyPropagation: {
    view: ["view"],  // 父资源的view权限 → 子资源的view权限
    edit: ["edit"]
  }
});

Step 3: Choose Storage Adapter

步骤3:选择存储适配器

For development/testing:
typescript
import { InMemoryStorageAdapter } from "polizy";

const storage = new InMemoryStorageAdapter();
For production (Prisma):
typescript
import { PrismaAdapter } from "polizy/prisma-storage";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
const storage = PrismaAdapter(prisma);
See PRISMA-SETUP.md for Prisma model requirements.
开发/测试环境:
typescript
import { InMemoryStorageAdapter } from "polizy";

const storage = new InMemoryStorageAdapter();
生产环境(Prisma):
typescript
import { PrismaAdapter } from "polizy/prisma-storage";
import { PrismaClient } from "@prisma/client";

const prisma = new PrismaClient();
const storage = PrismaAdapter(prisma);
查看 PRISMA-SETUP.md 了解Prisma模型的要求。

Step 4: Create AuthSystem

步骤4:创建AuthSystem

typescript
import { AuthSystem } from "polizy";

const authz = new AuthSystem({
  storage,
  schema,
});
typescript
import { AuthSystem } from "polizy";

const authz = new AuthSystem({
  storage,
  schema,
});

Step 5: Verify Setup

步骤5:验证配置

typescript
// Grant a permission
await authz.allow({
  who: { type: "user", id: "alice" },
  toBe: "owner",
  onWhat: { type: "document", id: "doc1" }
});

// Check it works
const canEdit = await authz.check({
  who: { type: "user", id: "alice" },
  canThey: "edit",
  onWhat: { type: "document", id: "doc1" }
});

console.log("Setup working:", canEdit); // true
typescript
// 授予权限
await authz.allow({
  who: { type: "user", id: "alice" },
  toBe: "owner",
  onWhat: { type: "document", id: "doc1" }
});

// 检查权限是否生效
const canEdit = await authz.check({
  who: { type: "user", id: "alice" },
  canThey: "edit",
  onWhat: { type: "document", id: "doc1" }
});

console.log("配置生效:", canEdit); // true

Storage Decision Matrix

存储方案决策矩阵

FactorInMemoryStorageAdapterPrismaAdapter
PersistenceNo (lost on restart)Yes
Multi-instanceNoYes
SetupZero configRequires Prisma model
PerformanceFastestDatabase-dependent
Use caseTesting, devProduction
考量因素InMemoryStorageAdapterPrismaAdapter
持久化否(重启后丢失)
多实例支持
配置难度零配置需要Prisma模型
性能最快取决于数据库
适用场景测试、开发生产环境

Complete Minimal Setup

完整极简配置示例

typescript
// auth.ts
import {
  defineSchema,
  AuthSystem,
  InMemoryStorageAdapter
} from "polizy";

const schema = defineSchema({
  relations: {
    owner: { type: "direct" },
    viewer: { type: "direct" },
  },
  actionToRelations: {
    edit: ["owner"],
    view: ["owner", "viewer"],
  },
});

const storage = new InMemoryStorageAdapter();

export const authz = new AuthSystem({ storage, schema });
typescript
// auth.ts
import {
  defineSchema,
  AuthSystem,
  InMemoryStorageAdapter
} from "polizy";

const schema = defineSchema({
  relations: {
    owner: { type: "direct" },
    viewer: { type: "direct" },
  },
  actionToRelations: {
    edit: ["owner"],
    view: ["owner", "viewer"],
  },
});

const storage = new InMemoryStorageAdapter();

export const authz = new AuthSystem({ storage, schema });

Configuration Options

配置选项

typescript
const authz = new AuthSystem({
  storage,
  schema,

  // Optional: Max depth for group/hierarchy traversal (default: 10)
  defaultCheckDepth: 10,

  // Optional: Throw error instead of returning false on max depth
  throwOnMaxDepth: false,

  // Optional: Field separator for field-level permissions (default: "#")
  fieldSeparator: "#",

  // Optional: Custom logger
  logger: {
    warn: (msg) => console.warn("[Polizy]", msg)
  }
});
typescript
const authz = new AuthSystem({
  storage,
  schema,

  // 可选:群组/层级遍历的最大深度(默认值:10)
  defaultCheckDepth: 10,

  // 可选:达到最大深度时抛出错误而非返回false
  throwOnMaxDepth: false,

  // 可选:字段级权限的分隔符(默认值:"#")
  fieldSeparator: "#",

  // 可选:自定义日志器
  logger: {
    warn: (msg) => console.warn("[Polizy]", msg)
  }
});

Common Issues

常见问题

IssueSolution
"Cannot find module 'polizy'"Run
npm install polizy
TypeScript errors in schemaEnsure
defineSchema
is imported from "polizy"
Prisma model not foundSee PRISMA-SETUP.md
Permission check returns falseVerify relation is in
actionToRelations
for that action
问题解决方案
"找不到模块 'polizy'"执行
npm install polizy
Schema相关TypeScript错误确保从"polizy"导入
defineSchema
Prisma模型未找到查看 PRISMA-SETUP.md
权限检查返回false验证该操作对应的关系是否在
actionToRelations
中配置

Next Steps

后续步骤

After setup, use these skills:
  • polizy-schema - Design your authorization model
  • polizy-patterns - Implement authorization scenarios
  • polizy-storage - Production storage setup
完成设置后,可使用以下技能:
  • polizy-schema - 设计你的授权模型
  • polizy-patterns - 实现授权场景
  • polizy-storage - 生产环境存储配置

References

参考资料

  • PRISMA-SETUP.md - Full Prisma configuration
  • FRAMEWORK-INTEGRATIONS.md - Next.js, Express examples
  • PRISMA-SETUP.md - 完整Prisma配置
  • FRAMEWORK-INTEGRATIONS.md - Next.js、Express集成示例