# Sign in with OpenDunes

Give your app an API key on its user's balance, with the user's approval.

1. [Send the user to OpenDunes](#1-send-the-user-to-opendunes).
2. [Read the code on your callback](#2-the-user-approves-your-app).
3. [Exchange the code for a key](#3-exchange-the-code-for-a-key).
4. [Call models with the key](#4-call-models-with-the-key).

Your app never asks for a password or a card. The user signs in on OpenDunes, approves your app, and your app gets an API key of its own. Every request sent with that key is charged to the user's balance, never to yours. The flow is OAuth PKCE, with the S256 method.

## 1. Send the user to OpenDunes

Make a secret, the code verifier, and keep it in your app. Send the user to `https://opendunes.com/auth` with its SHA-256 hash, the code challenge, and the page of your app they come back to.

| You send | Holds |
|---|---|
| `callback_url` | the page of your app the user comes back to |
| `code_challenge` | the SHA-256 hash of your code verifier, in base64url |
| `code_challenge_method` | `S256` |
| `key_label` | the key's name, shown to the user before they approve |

The samples make a verifier, print it as an `export` line, and print the address to open. The callback here is `http://localhost:3000/callback`: put your app's page in its place.

```python
import base64
import hashlib
import secrets
import urllib.parse

AUTH_URL = "https://opendunes.com/auth"
CALLBACK_URL = "http://localhost:3000/callback"
KEY_LABEL = "Souk Bot"

verifier = secrets.token_urlsafe(48)
digest = hashlib.sha256(verifier.encode()).digest()
challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode()

query = urllib.parse.urlencode(
    {
        "callback_url": CALLBACK_URL,
        "code_challenge": challenge,
        "code_challenge_method": "S256",
        "key_label": KEY_LABEL,
    }
)

print(f'export OPENDUNES_CODE_VERIFIER="{verifier}"')
print(AUTH_URL + "?" + query)
```

```javascript
import { createHash, randomBytes } from "node:crypto";

const authURL = "https://opendunes.com/auth";
const callbackURL = "http://localhost:3000/callback";
const keyLabel = "Souk Bot";

const verifier = randomBytes(48).toString("base64url");
const challenge = createHash("sha256").update(verifier).digest("base64url");

const query = new URLSearchParams({
  callback_url: callbackURL,
  code_challenge: challenge,
  code_challenge_method: "S256",
  key_label: keyLabel,
});

console.log(`export OPENDUNES_CODE_VERIFIER="${verifier}"`);
console.log(`${authURL}?${query}`);
```

```go
package main

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"net/url"
)

const (
	authURL     = "https://opendunes.com/auth"
	callbackURL = "http://localhost:3000/callback"
	keyLabel    = "Souk Bot"
)

func main() {
	secret := make([]byte, 48)
	if _, err := rand.Read(secret); err != nil {
		panic(err)
	}
	verifier := base64.RawURLEncoding.EncodeToString(secret)
	hash := sha256.Sum256([]byte(verifier))
	challenge := base64.RawURLEncoding.EncodeToString(hash[:])

	query := url.Values{}
	query.Set("callback_url", callbackURL)
	query.Set("code_challenge", challenge)
	query.Set("code_challenge_method", "S256")
	query.Set("key_label", keyLabel)

	fmt.Printf("export OPENDUNES_CODE_VERIFIER=%q\n", verifier)
	fmt.Println(authURL + "?" + query.Encode())
}
```

```bash cURL
AUTH_URL="https://opendunes.com/auth"
CALLBACK_URL="http%3A%2F%2Flocalhost%3A3000%2Fcallback"
KEY_LABEL="Souk%20Bot"

export OPENDUNES_CODE_VERIFIER=$(openssl rand -base64 48 \
  | tr '+/' '-_' | tr -d '=\n')
CODE_CHALLENGE=$(printf '%s' "$OPENDUNES_CODE_VERIFIER" \
  | openssl dgst -sha256 -binary | openssl base64 | tr '+/' '-_' | tr -d '=\n')

echo "$AUTH_URL?callback_url=$CALLBACK_URL&code_challenge=$CODE_CHALLENGE\
&code_challenge_method=S256&key_label=$KEY_LABEL"
```

<div class="dont">
<p>Don't put the code verifier in the address. Only its hash, the code challenge, travels to OpenDunes in this step.</p>
</div>

<div class="do">
<p>Do keep the code verifier with the user's session in your app, until step 3 sends it.</p>
</div>

## 2. Read the code on your callback {#2-the-user-approves-your-app}

On OpenDunes, the user signs in and sees your app's key, under the name `key_label` gave it. When they approve, OpenDunes sends them back to your `callback_url` with a `code` in the address:

```
http://localhost:3000/callback?code=‹code›
```

Your app reads `code` from the address. To try the samples by hand, copy it from the browser's address bar into your terminal:

```bash
export OPENDUNES_AUTH_CODE="‹code›"
```

## 3. Exchange the code for a key

Send the code and the verifier to `POST /v1/auth/keys`. This call carries no key: the code and the verifier prove it is your app. The answer holds the user's new key in `key`.

| You send | Holds |
|---|---|
| `code` | the code from the callback address |
| `code_verifier` | the secret you made in step 1 |
| `code_challenge_method` | `S256`, as in step 1 |

The samples exchange the code, then read the new key back with [This key](/docs/reference/key), a route that charges nothing. The cURL tab reads the answer with `jq`.

```python
import json
import os
import urllib.request

BASE_URL = "https://opendunes.com/v1"

body = json.dumps(
    {
        "code": os.environ["OPENDUNES_AUTH_CODE"],
        "code_verifier": os.environ["OPENDUNES_CODE_VERIFIER"],
        "code_challenge_method": "S256",
    }
).encode()
request = urllib.request.Request(
    BASE_URL + "/auth/keys",
    data=body,
    headers={"Content-Type": "application/json"},
)
with urllib.request.urlopen(request) as response:
    user_key = json.load(response)["key"]

check = urllib.request.Request(
    BASE_URL + "/key",
    headers={"Authorization": "Bearer " + user_key},
)
with urllib.request.urlopen(check) as response:
    print(json.load(response)["data"])
```

```javascript
const baseURL = "https://opendunes.com/v1";

const exchange = await fetch(`${baseURL}/auth/keys`, {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    code: process.env.OPENDUNES_AUTH_CODE,
    code_verifier: process.env.OPENDUNES_CODE_VERIFIER,
    code_challenge_method: "S256",
  }),
});
const { key: userKey } = await exchange.json();

const check = await fetch(`${baseURL}/key`, {
  headers: { Authorization: `Bearer ${userKey}` },
});
console.log((await check.json()).data);
```

```go
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
)

const baseURL = "https://opendunes.com/v1"

func main() {
	body, err := json.Marshal(map[string]string{
		"code":                  os.Getenv("OPENDUNES_AUTH_CODE"),
		"code_verifier":         os.Getenv("OPENDUNES_CODE_VERIFIER"),
		"code_challenge_method": "S256",
	})
	if err != nil {
		panic(err)
	}

	res, err := http.Post(
		baseURL+"/auth/keys", "application/json", bytes.NewReader(body),
	)
	if err != nil {
		panic(err)
	}
	defer res.Body.Close()

	var exchange struct {
		Key string `json:"key"`
	}
	if err := json.NewDecoder(res.Body).Decode(&exchange); err != nil {
		panic(err)
	}

	req, err := http.NewRequest("GET", baseURL+"/key", nil)
	if err != nil {
		panic(err)
	}
	req.Header.Set("Authorization", "Bearer "+exchange.Key)

	check, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	defer check.Body.Close()

	var answer struct {
		Data map[string]any `json:"data"`
	}
	if err := json.NewDecoder(check.Body).Decode(&answer); err != nil {
		panic(err)
	}
	fmt.Println(answer.Data)
}
```

```bash cURL
BASE_URL="https://opendunes.com/v1"

USER_KEY=$(curl -s "$BASE_URL/auth/keys" \
  -H "Content-Type: application/json" \
  -d '{
    "code": "'"$OPENDUNES_AUTH_CODE"'",
    "code_verifier": "'"$OPENDUNES_CODE_VERIFIER"'",
    "code_challenge_method": "S256"
  }' | jq -r .key)

curl "$BASE_URL/key" \
  -H "Authorization: Bearer $USER_KEY"
```

<div class="do">
<p>Do keep the user's key on your server, next to the user's account in your app. It is an API key like any other: whoever holds it spends the user's balance.</p>
</div>

## 4. Call models with the key

The user's key calls every route your own API key calls. Send it as `Authorization: Bearer <key>`, the way [Quickstart](/docs/quickstart) sends yours. Each request is charged in DA to the user's balance, the moment it ends, and `usage.cost` in the answer carries the charge ([Balance and charges](/docs/balance-and-charges)).

<div class="watch-out">
<p>When the user's balance is at zero or below, or cannot pay the request's hold, their key gets a 402, whatever is left on yours. Show the user the 402 and ask them to make a deposit on OpenDunes: <a href="/docs/errors-and-retries">Errors and retries</a>.</p>
</div>
