# Start and cancel a subscription

The person approves the plan and its monthly price once; you charge it until they cancel.

| | |
|---|---|
| Level | 1: A person approves with a passkey. |
| Class | `write-hard`: Hard to undo. The app creates the approval for that exact request, and it works once. |

## What the test proves

- the person approves the plan and its monthly price, once: 201, charged
- another price needs another approval
- a month later it is charged again, and nobody is asked
- the person approves the cancellation: it is never charged again

## Python

```python
routes.append(route("POST", "/plans/{plan}/subscription", "plans:subscribe", cls="write-hard", level=1,
                    resource="plan:{plan}", amount_field="/monthly", summary="Subscribe to a plan",
                    body={"monthly": "the price per month, e.g. 12.00", "currency": "EUR"}))
routes.append(route("GET", "/subscription", "plans:read", level=1, resource="plan:*", summary="Your subscription"))
routes.append(route("DELETE", "/subscription", "plans:cancel", cls="write-hard", level=1, resource="plan:mine",
                    summary="Cancel your subscription"))
templates["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel"
templates["plans:read"] = "See your subscription"
templates["plans:cancel"] = "Cancel your subscription"


@app.post("/plans/<plan>/subscription")
def subscribe(plan):
    # Approved once, with the price: your billing charges it every month (subscriptions.py) until it is cancelled.
    return subscriptions.start(g.allowedby.human_id, plan, request.json["monthly"]), 201


@app.get("/subscription")
def subscription():
    return subscriptions.get(g.allowedby.human_id) or ({"error": "no subscription"}, 404)


@app.delete("/subscription")
def cancel():
    return subscriptions.cancel(g.allowedby.human_id) or ({"error": "no subscription"}, 404)
```

## JavaScript

```js
routes.push(
  route("POST", "/plans/{plan}/subscription", "plans:subscribe", {
    class: "write-hard", level: 1, resource: "plan:{plan}", amountField: "/monthly", summary: "Subscribe to a plan",
    body: { monthly: "the price per month, e.g. 12.00", currency: "EUR" },
  }),
  route("GET", "/subscription", "plans:read", { level: 1, resource: "plan:*", summary: "Your subscription" }),
  route("DELETE", "/subscription", "plans:cancel", {
    class: "write-hard", level: 1, resource: "plan:mine", summary: "Cancel your subscription",
  }),
);
templates["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel";
templates["plans:read"] = "See your subscription";
templates["plans:cancel"] = "Cancel your subscription";

api.post("/plans/:plan/subscription", (req, res) => {
  // Approved once, with the price: your billing charges it every month (subscriptions.mjs) until it is cancelled.
  const person = req.allowedby.humanId;
  if (person === null) return res.status(403).json({ error: "no person at level 0" }); // level 0: no person to key by
  res.status(201).json(subscriptions.start(person, req.params.plan, req.body.monthly));
});

api.get("/subscription", (req, res) => {
  const person = req.allowedby.humanId;
  if (person === null) return res.status(403).json({ error: "no person at level 0" });
  const subscription = subscriptions.get(person);
  if (!subscription) return res.status(404).json({ error: "no subscription" });
  res.json(subscription);
});

api.delete("/subscription", (req, res) => {
  const person = req.allowedby.humanId;
  if (person === null) return res.status(403).json({ error: "no person at level 0" });
  const subscription = subscriptions.cancel(person);
  if (!subscription) return res.status(404).json({ error: "no subscription" });
  res.json(subscription);
});
```

## Go

```go
routes = append(routes,
	allowedby.Route{Method: "POST", Path: "/plans/{plan}/subscription", Capability: "plans:subscribe",
		Class: allowedby.WriteHard, Level: 1, Resource: "plan:{plan}", AmountField: "/monthly",
		Summary: "Subscribe to a plan",
		Body:    map[string]string{"monthly": "the price per month, e.g. 12.00", "currency": "EUR"}},
	allowedby.Route{Method: "GET", Path: "/subscription", Capability: "plans:read",
		Class: allowedby.Read, Level: 1, Resource: "plan:*", Summary: "Your subscription"},
	allowedby.Route{Method: "DELETE", Path: "/subscription", Capability: "plans:cancel",
		Class: allowedby.WriteHard, Level: 1, Resource: "plan:mine", Summary: "Cancel your subscription"})
templates["plans:subscribe"] = allowedby.Text(
	"Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel")
templates["plans:read"] = allowedby.Text("See your subscription")
templates["plans:cancel"] = allowedby.Text("Cancel your subscription")

mux.HandleFunc("POST /plans/{plan}/subscription", func(w http.ResponseWriter, r *http.Request) {
	// Approved once, with the price: your billing charges it every month (subscriptions.go) until it is cancelled.
	who, _ := allowedby.ContextFrom(r.Context())
	me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for
	if !ok {
		writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"})
		return
	}
	var input struct{ Monthly string }
	if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
		writeJSON(w, http.StatusBadRequest, map[string]string{"error": "monthly: a string"})
		return
	}
	writeJSON(w, http.StatusCreated, subscriptions.Start(me, r.PathValue("plan"), input.Monthly))
})

mux.HandleFunc("GET /subscription", func(w http.ResponseWriter, r *http.Request) {
	who, _ := allowedby.ContextFrom(r.Context())
	me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for
	if !ok {
		writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"})
		return
	}
	subscription, found := subscriptions.Get(me)
	if !found {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "no subscription"})
		return
	}
	writeJSON(w, http.StatusOK, subscription)
})

mux.HandleFunc("DELETE /subscription", func(w http.ResponseWriter, r *http.Request) {
	who, _ := allowedby.ContextFrom(r.Context())
	me, ok := who.Human() // false at level 0: an agent calls, with no person to keep data for
	if !ok {
		writeJSON(w, http.StatusForbidden, map[string]string{"error": "no person at level 0"})
		return
	}
	subscription, found := subscriptions.Cancel(me)
	if !found {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "no subscription"})
		return
	}
	writeJSON(w, http.StatusOK, subscription)
})
```

## Java

```java
@Bean
AllowedByCustomizer subscribe() {
    return aby -> aby
            .route(Route.post("/plans/{plan}/subscription").capability("plans:subscribe")
                    .actionClass(ActionClass.WRITE_HARD).level(1).resource("plan:{plan}")
                    .amountField("/monthly").summary("Subscribe to a plan")
                    .body(Map.of("monthly", "the price per month, e.g. 12.00", "currency", "EUR")))
            .route(Route.get("/subscription").capability("plans:read").level(1).resource("plan:*")
                    .summary("Your subscription"))
            .route(Route.delete("/subscription").capability("plans:cancel").actionClass(ActionClass.WRITE_HARD)
                    .level(1).resource("plan:mine").summary("Cancel your subscription"))
            .template("plans:subscribe",
                    "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel")
            .template("plans:read", "See your subscription")
            .template("plans:cancel", "Cancel your subscription");
}

@PostMapping("/plans/{plan}/subscription")
@ResponseStatus(HttpStatus.CREATED)
Subscription subscribe(@AllowedByContext Context ctx, @PathVariable String plan, @RequestBody Price price) {
    String person = ctx.getHumanId();
    if (person == null) { // level 0: no person, and never a key
        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0");
    }
    // Approved once, with the price: your billing charges it every month (Subscriptions) until it is cancelled.
    return subscriptions.start(person, plan, price.monthly());
}

@GetMapping("/subscription")
ResponseEntity<Object> subscription(@AllowedByContext Context ctx) {
    String person = ctx.getHumanId();
    if (person == null) { // level 0: no person, and never a key
        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0");
    }
    return subscriptions.get(person).<ResponseEntity<Object>>map(ResponseEntity::ok)
            .orElse(ResponseEntity.status(404).body(Map.of("error", "no subscription")));
}

@DeleteMapping("/subscription")
ResponseEntity<Object> cancel(@AllowedByContext Context ctx) {
    String person = ctx.getHumanId();
    if (person == null) { // level 0: no person, and never a key
        throw new ResponseStatusException(HttpStatus.FORBIDDEN, "no person at level 0");
    }
    return subscriptions.cancel(person).<ResponseEntity<Object>>map(ResponseEntity::ok)
            .orElse(ResponseEntity.status(404).body(Map.of("error", "no subscription")));
}
```

## C#

```dotnet
routes.Add(Route("POST", "/plans/{plan}/subscription", "plans:subscribe", cls: "write-hard", level: 1,
    resource: "plan:{plan}", amountField: "/monthly", summary: "Subscribe to a plan",
    body: new Dictionary<string, string> { ["monthly"] = "the price per month, e.g. 12.00", ["currency"] = "EUR" }));
routes.Add(Route("GET", "/subscription", "plans:read", level: 1, resource: "plan:*", summary: "Your subscription"));
routes.Add(Route("DELETE", "/subscription", "plans:cancel", cls: "write-hard", level: 1, resource: "plan:mine",
    summary: "Cancel your subscription"));
templates["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel";
templates["plans:read"] = "See your subscription";
templates["plans:cancel"] = "Cancel your subscription";

app.MapPost("/plans/{plan}/subscription", (string plan, Price price, AllowedByContext ctx) =>
    // Approved once, with the price: your billing charges it every month (Subscriptions.cs) until it is cancelled.
    Results.Json(subscriptions.Start(Person(ctx), plan, price.Monthly), statusCode: 201));

app.MapGet("/subscription", (AllowedByContext ctx) =>
    subscriptions.Get(Person(ctx)) is { } subscription
        ? Results.Json(subscription)
        : Results.Json(new { error = "no subscription" }, statusCode: 404));

app.MapDelete("/subscription", (AllowedByContext ctx) =>
    subscriptions.Cancel(Person(ctx)) is { } subscription
        ? Results.Json(subscription)
        : Results.Json(new { error = "no subscription" }, statusCode: 404));
```

## PHP

```php
$routes[] = route('POST', '/plans/{plan}/subscription', 'plans:subscribe', class: 'write-hard', level: 1,
    resource: 'plan:{plan}', amountField: '/monthly', summary: 'Subscribe to a plan',
    body: ['monthly' => 'the price per month, e.g. 12.00', 'currency' => 'EUR']);
$routes[] = route('GET', '/subscription', 'plans:read', level: 1, resource: 'plan:*', summary: 'Your subscription');
$routes[] = route('DELETE', '/subscription', 'plans:cancel', class: 'write-hard', level: 1, resource: 'plan:mine',
    summary: 'Cancel your subscription');
$templates['plans:subscribe'] = 'Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel';
$templates['plans:read'] = 'See your subscription';
$templates['plans:cancel'] = 'Cancel your subscription';

$app->post('/plans/{plan}/subscription', function (Request $request, Response $response, array $args) use (
    $json,
    $subscriptions
) {
    // Approved once, with the price: your billing charges it every month (Subscriptions.php) until it is cancelled.
    $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0');
    $input = json_decode((string) $request->getBody(), true);

    return $json($response, $subscriptions->start($person, $args['plan'], $input['monthly']), 201);
});

$app->get('/subscription', function (Request $request, Response $response) use ($json, $subscriptions) {
    $subscription = $subscriptions->get($request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'));

    return $subscription ? $json($response, $subscription) : $json($response, ['error' => 'no subscription'], 404);
});

$app->delete('/subscription', function (Request $request, Response $response) use ($json, $subscriptions) {
    $subscription = $subscriptions->cancel($request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0'));

    return $subscription ? $json($response, $subscription) : $json($response, ['error' => 'no subscription'], 404);
});
```

## Ruby

```ruby
ROUTES << AllowedBy.route(
  "POST", "/plans/{plan}/subscription", "plans:subscribe",
  class: "write-hard", level: 1, resource: "plan:{plan}", amount_field: "/monthly", summary: "Subscribe to a plan",
  body: { monthly: "the price per month, e.g. 12.00", currency: "EUR" }
)
ROUTES << AllowedBy.route(
  "GET", "/subscription", "plans:read",
  level: 1, resource: "plan:*", summary: "Your subscription"
)
ROUTES << AllowedBy.route(
  "DELETE", "/subscription", "plans:cancel",
  class: "write-hard", level: 1, resource: "plan:mine", summary: "Cancel your subscription"
)
TEMPLATES["plans:subscribe"] = "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel"
TEMPLATES["plans:read"] = "See your subscription"
TEMPLATES["plans:cancel"] = "Cancel your subscription"

post "/plans/:plan/subscription" do
  # Approved once, with the price: your billing charges it every month (subscriptions.rb) until it is cancelled.
  person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json
  monthly = JSON.parse(request.body.read)["monthly"]
  [201, subscriptions.start(person, params["plan"], monthly).to_json]
end

get "/subscription" do
  person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json
  subscription = subscriptions.get(person)
  halt 404, { error: "no subscription" }.to_json unless subscription
  subscription.to_json
end

delete "/subscription" do
  person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json
  subscription = subscriptions.cancel(person)
  halt 404, { error: "no subscription" }.to_json unless subscription
  subscription.to_json
end
```

## Rust

```rust
let aby = aby
    .route(
        Route::post("/plans/{plan}/subscription")
            .capability("plans:subscribe")
            .class(Class::WriteHard)
            .level(1)
            .resource("plan:{plan}")
            .amount_field("/monthly")
            .summary("Subscribe to a plan")
            .body_field("monthly", "the price per month, e.g. 12.00")
            .body_field("currency", "EUR"),
    )
    .route(
        Route::get("/subscription")
            .capability("plans:read")
            .level(1)
            .resource("plan:*")
            .summary("Your subscription"),
    )
    .route(
        Route::delete("/subscription")
            .capability("plans:cancel")
            .class(Class::WriteHard)
            .level(1)
            .resource("plan:mine")
            .summary("Cancel your subscription"),
    )
    .template(
        "plans:subscribe",
        "Subscribe to {scope} for {amount.max} {amount.currency} per month, until you cancel",
    )
    .template("plans:read", "See your subscription")
    .template("plans:cancel", "Cancel your subscription");
let app = app
    .route("/plans/{plan}/subscription", post(subscribe))
    .route("/subscription", get(subscription).delete(cancel));

async fn subscribe(
    ctx: AllowedByContext,
    State(subscriptions): State<Subscriptions>,
    Path(plan): Path<String>,
    Json(price): Json<Price>,
) -> (StatusCode, Json<Subscription>) {
    // Approved once, with the price: your billing charges it every month (subscriptions.rs) until it is cancelled.
    (StatusCode::CREATED, Json(subscriptions.start(&ctx.human_id, plan, price.monthly)))
}

async fn subscription(
    ctx: AllowedByContext,
    State(subscriptions): State<Subscriptions>,
) -> Result<Json<Subscription>, Refusal> {
    let found = subscriptions.get(&ctx.human_id);
    found.map(Json).ok_or((StatusCode::NOT_FOUND, Json(json!({"error": "no subscription"}))))
}

async fn cancel(
    ctx: AllowedByContext,
    State(subscriptions): State<Subscriptions>,
) -> Result<Json<Subscription>, Refusal> {
    let found = subscriptions.cancel(&ctx.human_id);
    found.map(Json).ok_or((StatusCode::NOT_FOUND, Json(json!({"error": "no subscription"}))))
}
```
