快速开始

签发 user_token

给产品侧 client 一个可以调用 City 的用户凭证。

user_token 需要由可信环境签发。开发者后端使用 Admin City,基于 town_id + user_id 向 City 申请 token。

import { City } from "@downcity/city";

const client = new City({
  role: "admin",
  city_url: "https://base.example.com",
  admin_secret_key: process.env.DOWNCITY_CITY_ADMIN_SECRET_KEY,
});

const town = await client.towns.create({
  name: "Web App",
});

const user = await client.towns.tokens.apply({
  town_id: town.town_id,
  user_id: "user_123",
  metadata: {
    plan: "pro",
  },
  ttl: "7d",
});

user.user_tokentown.town_id 返回给产品 client。

metadata 的作用

metadata 可以把套餐、组织 ID 等业务信息带进 hook。

const action = service.action("generate", async (ctx) => {
  return generateSomething(ctx.input);
});

action.before(async (ctx) => {
  await quotaService.check({
    town_id: ctx.town?.town_id,
    user_id: ctx.user?.user_id,
    plan: ctx.user?.metadata?.plan,
  });
});

这样多个 client 可以共享一套鉴权和限额判断。