# Creating a token for a script

A script logs in once and keeps an **offline token**: a refresh token that keeps working
without you, from which it gets its access tokens. To run requests from these pages, log in
here instead: [Logging in](/docs/login.md).

## Creating one

Run the first sample on the right once, in Python, in a shell or in Node:

1. It prints a link, for which it asked the login server with the scope `offline_access`.
2. Open the link, in a browser on any device, log in with your reconnectchina.org account and
   confirm.
3. The sample notices by itself and saves the offline token in `reconnectchina-token`, a file
   only you can read.

No password passes through the script: you enter it on account.reconnectchina.org only.

## Using a saved token

The second sample is how every later run starts: a client that reads the token from
`reconnectchina-token`, without logging in. It exchanges the token for access tokens as it goes,
and saves the one the login server sends in its place. The operation pages' Python and Node
samples run on that client ([Client libraries](/docs/clients.md)). In the shell, the sample puts
an access token in `$TOKEN`, which the operation pages' curl commands read, for the five minutes
it lasts ([Access tokens](/docs/login/access-token.md)).

## How long it lasts

An offline token that is not used for 30 days ends, and one ends after a year however much it
is used. A script that runs regularly therefore keeps it for the year. Revoke one you no longer
need under *Applications* in the reconnectchina.org account console, or with a request ([Logging
out](/docs/login/logout.md)): a copy of a revoked token is worthless.

## Samples

Console programs that do what this page is about, logging in at the API's own /oauth. The Shell ones need curl and jq.

Every API host serves these pages for its own API. The samples are written for production, https://api.reconnectchina.org, as the pages are before they know their host. On another host, such as the sandbox, use that host instead: in curl's URL and the Shell samples' `login=` line, and as `server` for the Python and Node clients, which log in there too.

### Python

Creating it

```python
from reconnectchina import Client, ConsolePrompt, OfflineTokenFile

client = Client(
    tokens=OfflineTokenFile("reconnectchina-token"),
    prompt=ConsolePrompt(),
    offline=True,
)
client.login()
```

Using a saved token

```python
from reconnectchina import Client, OfflineTokenFile

client = Client(
    tokens=OfflineTokenFile("reconnectchina-token"),
)
```

### Shell

Creating it

```sh
login=https://api.reconnectchina.org/oauth
device=$(curl -s "$login/device" -d client_id=reconnectchina-api -d scope=offline_access)
echo "$device" | jq -r '"Open \(.verification_uri_complete) to log in."'
interval=$(echo "$device" | jq -r '.interval // 5')
while sleep "$interval"; do
  answer=$(echo "$device" | jq -r '"device_code=\(.device_code)"' |
    curl -s "$login/token" -d client_id=reconnectchina-api -d grant_type=urn:ietf:params:oauth:grant-type:device_code -d @-)
  case $(echo "$answer" | jq -r '.error // empty') in
    '') (umask 077 && echo "$answer" | jq -r .refresh_token > reconnectchina-token); break ;;
    authorization_pending) ;;
    slow_down) interval=$((interval + 5)) ;;
    *) echo "$answer" >&2; break ;;
  esac
done
```

Using a saved token

```sh
login=https://api.reconnectchina.org/oauth
answer=$(printf 'refresh_token=%s' "$(cat reconnectchina-token)" |
  curl -s "$login/token" -d client_id=reconnectchina-api -d grant_type=refresh_token -d @-)
new=$(echo "$answer" | jq -r '.refresh_token // empty')
if [ -n "$new" ]; then (umask 077 && echo "$new" > reconnectchina-token); fi
TOKEN=$(echo "$answer" | jq -r '.access_token // error(.error_description // .error)')
```

### Node

Creating it

```js
import { writeFile } from "node:fs/promises";
import { Client } from "@reconnectchina/client";

const client = new Client({
  tokens: {
    load: () => undefined,
    save: (tokens) =>
      tokens && writeFile("reconnectchina-token", tokens.refreshToken, { mode: 0o600 }),
  },
});
await client.login({
  offline: true,
  prompt: ({ link }) => console.log(`Open ${link} to log in.`),
});
```

Using a saved token

```js
import { readFile, writeFile } from "node:fs/promises";
import { Client } from "@reconnectchina/client";

const file = "reconnectchina-token";
const client = new Client({
  tokens: {
    load: async () => ({
      refreshToken: (await readFile(file, "utf8")).trim(),
      offline: true,
    }),
    save: (tokens) => tokens && writeFile(file, tokens.refreshToken),
  },
});
```
