# Quickstart

Protect an endpoint, see it refuse an agent that has no approval, then approve one yourself.

```python
import os

from flask import Flask, g

from allowedby import route
from allowedby.flask import AllowedBy

app = Flask(__name__)
app.config["ALLOWEDBY"] = {
    "origin": os.environ["ALLOWEDBY_ORIGIN"],  # your app's public URL
    "node": os.environ["ALLOWEDBY_NODE"],  # the node you trust: people approve there
    "org": {"legal_name": "Notes Ltd", "country": "FR"},
    "routes": [route("GET", "/notes", "notes:read", level=1, resource="note:*")],
    "templates": {"notes:read": "Read your notes"},  # what the person approves
}
AllowedBy(app)


@app.get("/notes")
def list_notes():
    return {"notes": [], "person": g.allowedby.human_id}
```

```js
import express from "express";
import { AllowedBy, route } from "@allowedby/sdk";
import { allowedby } from "@allowedby/sdk/express";

const aby = new AllowedBy({
  origin: process.env.ALLOWEDBY_ORIGIN, // your app's public URL
  node: process.env.ALLOWEDBY_NODE, // the node you trust: people approve there
  org: { legal_name: "Notes Ltd", country: "FR" },
  routes: [route("GET", "/notes", "notes:read", { level: 1, resource: "note:*" })],
  templates: { "notes:read": "Read your notes" }, // what the person approves
});

const app = express();
app.use(allowedby(aby));

app.get("/notes", (req, res) => {
  res.json({ notes: [], person: req.allowedby.humanId });
});

app.listen(process.env.PORT, process.env.ALLOWEDBY_BIND || "127.0.0.1"); // ALLOWEDBY_BIND=0.0.0.0 in a container
```

```go
import (
	"encoding/json"
	allowedby "github.com/yannUpTo/allowedby/sdks/go"
	"log"
	"net/http"
	"os"
)

func main() {
	aby, err := allowedby.New(allowedby.Options{
		Origin: os.Getenv("ALLOWEDBY_ORIGIN"), Node: os.Getenv("ALLOWEDBY_NODE"), // your URL; where people approve
		Org:       allowedby.Org{LegalName: "Notes Ltd", Country: "FR"},
		Routes:    []allowedby.Route{{Method: "GET", Path: "/notes", Capability: "notes:read", Class: allowedby.Read, Level: 1, Resource: "note:*"}},
		Templates: map[string]allowedby.Template{"notes:read": allowedby.Text("Read your notes")}, // what they approve
	})
	if err != nil {
		log.Fatal(err)
	}
	http.HandleFunc("GET /notes", func(w http.ResponseWriter, r *http.Request) {
		who, _ := allowedby.ContextFrom(r.Context()) // a level-1 route: never run without a person
		w.Header().Set("Content-Type", "application/json")
		_ = json.NewEncoder(w).Encode(map[string]any{"notes": []string{}, "person": who.HumanID})
	})
	log.Fatal(http.ListenAndServe("localhost:"+os.Getenv("PORT"), aby.Handler(http.DefaultServeMux)))
}
```

```java
import java.util.*;
import org.allowedby.*;
import org.allowedby.spring.*;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;

@SpringBootApplication
@RestController
public class Quickstart {
    @Bean
    AllowedByCustomizer agents() { // origin: your app's public URL; node: the node you trust, people approve there
        return aby -> aby.origin(System.getenv("ALLOWEDBY_ORIGIN")).node(System.getenv("ALLOWEDBY_NODE"))
                .org("Notes Ltd", "FR").route(Route.get("/notes").capability("notes:read").resource("note:*"))
                .template("notes:read", "Read your notes"); // what the person approves
    }
    @GetMapping("/notes")
    Map<String, Object> listNotes(@AllowedByContext Context ctx) {
        return Map.of("notes", List.of(), "person", ctx.getHumanId());
    }
    public static void main(String[] args) {
        SpringApplication.run(Quickstart.class, args);
    }
}
```

```dotnet
using AllowedBy;
using AllowedBy.AspNetCore;
using static AllowedBy.Routes;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAllowedBy(o =>
{
    o.Origin = builder.Configuration["ALLOWEDBY_ORIGIN"]!; // your app's public URL
    o.Node = builder.Configuration["ALLOWEDBY_NODE"]!; // the node you trust: people approve there
    o.Org = new AllowedByOrg { LegalName = "Notes Ltd", Country = "FR" };
    o.Routes = [Route("GET", "/notes", "notes:read", level: 1, resource: "note:*")];
    o.Templates["notes:read"] = "Read your notes"; // what the person approves
});

var app = builder.Build();
app.UseAllowedBy();

app.MapGet("/notes", (AllowedByContext ctx) => new { notes = Array.Empty<string>(), person = ctx.HumanId });

app.Run();
```

```php
require __DIR__.'/vendor/autoload.php';

use AllowedBy\AllowedBy;

use function AllowedBy\route;

$aby = new AllowedBy(
    origin: (string) getenv('ALLOWEDBY_ORIGIN'), // your app's public URL
    node: (string) getenv('ALLOWEDBY_NODE'), // the node you trust: people approve there
    org: ['legal_name' => 'Notes Ltd', 'country' => 'FR'],
    routes: [route('GET', '/notes', 'notes:read', level: 1, resource: 'note:*')],
    templates: ['notes:read' => 'Read your notes'], // what the person approves
    keyFile: getenv('ALLOWEDBY_KEY_FILE') ?: throw new RuntimeException('set ALLOWEDBY_KEY_FILE'), // private
);
$decision = $aby->processGlobals();
if (null !== $decision->response) {
    $decision->response->send(); // discovery documents, refusals and challenges
    exit;
}
if (null === $decision->context) { // not GET /notes: nothing was checked, so nothing is served
    http_response_code(404);
    exit;
}
header('Content-Type: application/json');
echo json_encode(['notes' => [], 'person' => $decision->context->humanId]);
```

```ruby
require "sinatra"
require "allowedby"
require "json"

aby = AllowedBy.new(
  origin: ENV.fetch("ALLOWEDBY_ORIGIN"), # your app's public URL
  node: ENV.fetch("ALLOWEDBY_NODE"),     # the node you trust: people approve there
  org: { legal_name: "Notes Ltd", country: "FR" },
  routes: [AllowedBy.route("GET", "/notes", "notes:read", level: 1, resource: "note:*")],
  templates: { "notes:read" => "Read your notes" } # what the person approves
)
use AllowedBy::Middleware, aby
bind = ENV.fetch("ALLOWEDBY_BIND", "") # ALLOWEDBY_BIND=0.0.0.0 in a container; empty or unset: loopback only
set :bind, bind.empty? ? "127.0.0.1" : bind unless ARGV.any? { |a| a.start_with?("-o") } # an explicit -o wins

get "/notes" do
  content_type :json
  # no person (a level-0 route): refused, never a store keyed by nil
  person = env["allowedby.context"].human_id or halt 403, { error: "no person: this route needs one" }.to_json
  { notes: [], person: person }.to_json
end
```

```rust
use allowedby::{AllowedByContext, Options, Org, Route, Service};
use axum::{routing::get, Json, Router};
use serde_json::{json, Value};
use std::env::var;

async fn list_notes(ctx: AllowedByContext) -> Json<Value> {
    Json(json!({"notes": [], "person": ctx.human_id}))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // your app's public URL, and the node you trust: people approve there
    let aby = Options::new(&var("ALLOWEDBY_ORIGIN")?, &var("ALLOWEDBY_NODE")?)
        .org(Org::new("Notes Ltd", "FR"))
        .route(Route::get("/notes").capability("notes:read").level(1).resource("note:*"))
        .template("notes:read", "Read your notes"); // what the person approves

    let app = Router::new().route("/notes", get(list_notes));
    let app = allowedby::axum::protect(app, Service::new(aby)?);
    let listener = tokio::net::TcpListener::bind(format!("127.0.0.1:{}", var("PORT")?)).await?;
    axum::serve(listener, app).await?;
    Ok(())
}
```


## Install the SDK

The packages are in private preview and not on public registries yet. The "Install" section of your language's guide
has the commands for the preview: [Python](https://docs.allowedby.com/sdk/python#install), [JavaScript](https://docs.allowedby.com/sdk/js#install),
[Go](https://docs.allowedby.com/sdk/go#install), [Java](https://docs.allowedby.com/sdk/java#install), [C#](https://docs.allowedby.com/sdk/dotnet#install), [PHP](https://docs.allowedby.com/sdk/php#install),
[Ruby](https://docs.allowedby.com/sdk/ruby#install), [Rust](https://docs.allowedby.com/sdk/rust#install).

## Describe the endpoint

One line says what the endpoint lets an agent do (`notes:read`), how serious it is, and which resource it touches. One
sentence says what the person will sign. Only your app writes that sentence.

## Run it and call it without approval

```bash
curl -i http://localhost:3000/notes
```

The answer is `401` with a problem document and a challenge that an agent understands:

```http
HTTP/1.1 401 Unauthorized
Content-Type: application/problem+json
WWW-Authenticate: AllowedBy realm="localhost:3000", error="passport_required"
```

## Let an agent call it

An agent shows its passport, is told that an approval is missing, asks the person through its node, and tries again.
You can watch that whole conversation, and take the person's place, on [Try it live](https://docs.allowedby.com/try).

## Next

- [How it works](https://docs.allowedby.com/how-it-works), in five minutes.
- [All recipes](https://docs.allowedby.com/recipes): write, delete, pay, personal data, tests.
- [Before production](https://docs.allowedby.com/guides/accept-agents#14-going-live-checklist).
