# Ask before deleting

A change that is hard to undo: your app asks the person for that exact request, and the approval works once.

| | |
|---|---|
| Level | 2: A person whose identity is verified 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 approval to write does not delete: 401
- the app asks for this exact request; the person verifies their identity (level 2) and approves: 200
- the approval works once, and for no other note

## Python

```python
routes.append(route("DELETE", "/notes/{id}", "notes:delete", cls="write-hard", level=2, resource="note:{id}",
                    summary="Delete a note"))
templates["notes:delete"] = "Delete {scope}"


@app.delete("/notes/<note_id>")
def delete_note(note_id):
    # The person approved this exact request, and it works once.
    if not notes.delete(g.allowedby.human_id, note_id):
        return {"error": "no such note"}, 404
    return {"deleted": note_id}
```

## JavaScript

```js
routes.push(route("DELETE", "/notes/{id}", "notes:delete", {
  class: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note",
}));
templates["notes:delete"] = "Delete {scope}";

api.delete("/notes/:id", (req, res) => {
  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
  // The person approved this exact request, and it works once.
  if (!notes.delete(person, req.params.id)) {
    return res.status(404).json({ error: "no such note" });
  }
  res.json({ deleted: req.params.id });
});
```

## Go

```go
routes = append(routes, allowedby.Route{Method: "DELETE", Path: "/notes/{id}", Capability: "notes:delete",
	Class: allowedby.WriteHard, Level: 2, Resource: "note:{id}", Summary: "Delete a note"})
templates["notes:delete"] = allowedby.Text("Delete {scope}")

mux.HandleFunc("DELETE /notes/{id}", func(w http.ResponseWriter, r *http.Request) {
	// The person approved this exact request, and it works once.
	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
	}
	if !notes.Delete(me, r.PathValue("id")) {
		writeJSON(w, http.StatusNotFound, map[string]string{"error": "no such note"})
		return
	}
	writeJSON(w, http.StatusOK, map[string]string{"deleted": r.PathValue("id")})
})
```

## Java

```java
@Bean
AllowedByCustomizer delete() {
    return aby -> aby
            .route(Route.delete("/notes/{id}").capability("notes:delete").actionClass(ActionClass.WRITE_HARD)
                    .level(2).resource("note:{id}").summary("Delete a note"))
            .template("notes:delete", "Delete {scope}");
}

@DeleteMapping("/notes/{id}")
ResponseEntity<Map<String, String>> deleteNote(@AllowedByContext Context ctx, @PathVariable String id) {
    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");
    }
    // The person approved this exact request, and it works once.
    if (!notes.delete(person, id)) {
        return ResponseEntity.status(404).body(Map.of("error", "no such note"));
    }
    return ResponseEntity.ok(Map.of("deleted", id));
}
```

## C#

```dotnet
routes.Add(Route("DELETE", "/notes/{id}", "notes:delete", cls: "write-hard", level: 2, resource: "note:{id}",
    summary: "Delete a note"));
templates["notes:delete"] = "Delete {scope}";

app.MapDelete("/notes/{id}", (string id, AllowedByContext ctx) =>
    // The person approved this exact request, and it works once.
    notes.Delete(Person(ctx), id)
        ? Results.Json(new { deleted = id })
        : Results.Json(new { error = "no such note" }, statusCode: 404));
```

## PHP

```php
$routes[] = route('DELETE', '/notes/{id}', 'notes:delete', class: 'write-hard', level: 2, resource: 'note:{id}',
    summary: 'Delete a note');
$templates['notes:delete'] = 'Delete {scope}';

$app->delete('/notes/{id}', function (Request $request, Response $response, array $args) use ($json, $notes) {
    // The person approved this exact request, and it works once.
    $person = $request->getAttribute('allowedby.context')->humanId ?? throw new LogicException('no person at level 0');
    if (!$notes->delete($person, $args['id'])) {
        return $json($response, ['error' => 'no such note'], 404);
    }

    return $json($response, ['deleted' => $args['id']]);
});
```

## Ruby

```ruby
ROUTES << AllowedBy.route(
  "DELETE", "/notes/{id}", "notes:delete",
  class: "write-hard", level: 2, resource: "note:{id}", summary: "Delete a note"
)
TEMPLATES["notes:delete"] = "Delete {scope}"

delete "/notes/:id" do
  # The person approved this exact request, and it works once.
  person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json
  deleted = notes.delete(person, params["id"])
  halt 404, { error: "no such note" }.to_json unless deleted
  { deleted: params["id"] }.to_json
end
```

## Rust

```rust
let aby = aby
    .route(
        Route::delete("/notes/{id}")
            .capability("notes:delete")
            .class(Class::WriteHard)
            .level(2)
            .resource("note:{id}")
            .summary("Delete a note"),
    )
    .template("notes:delete", "Delete {scope}");
let app = app.route("/notes/{id}", delete(delete_note));

async fn delete_note(
    ctx: AllowedByContext,
    State(notes): State<Notes>,
    Path(id): Path<String>,
) -> Result<Json<Value>, Refusal> {
    // The person approved this exact request, and it works once.
    match notes.delete(&ctx.human_id, &id) {
        Some(note) => Ok(Json(json!({"deleted": note.id}))),
        None => Err((StatusCode::NOT_FOUND, Json(json!({"error": "no such note"})))),
    }
}
```
