> ## Documentation Index
> Fetch the complete documentation index at: https://code.dcycle.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Authentication

> Login, configure hosts, and manage your CLI session

<Note>
  **Early Access** - The Dcycle CLI is currently available for enterprise customers.
  [Contact us](/docs/support) to learn more about access.
</Note>

## Logging In

The CLI uses the same credentials as the Dcycle web application.

### Browser Login (Default)

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth login
```

This opens your default browser to the Dcycle sign-in page. You complete the full authentication flow in the browser (email, password, MFA, SSO) and the CLI receives the session automatically.

Output:

```
Logged in
  User:         john@company.com
  Organization: Acme Corp
  Host:         https://api.dcycle.io (PROD)
```

If you have access to multiple organizations, the CLI prompts you to choose:

```
Available organizations:
  1. Acme Corp
  2. Acme Logistics
Select organization: 1
```

<Tip>
  Browser login handles all authentication methods including SSO and MFA — no extra steps needed in the terminal.
</Tip>

If the browser can't be opened automatically, the CLI prints a URL for you to open manually.

### Terminal Login

Use `--no-browser` to authenticate directly in the terminal:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth login --no-browser
```

This prompts for email and password interactively. If your account has MFA enabled, the CLI also prompts for your TOTP code.

<Info>
  Terminal mode is used automatically when `--email` or `--password` flags are provided, or when stdin is not a TTY (e.g. in CI/CD pipelines).
</Info>

### Non-Interactive Login

For automation and scripting:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth login --email user@example.com --password your_password
```

### Login Flags

| Flag           | Short | Default | Description                                   |
| -------------- | ----- | ------- | --------------------------------------------- |
| `--email`      | `-e`  | —       | Email address                                 |
| `--password`   | `-p`  | —       | Password                                      |
| `--host`       | —     | —       | Host alias or URL (e.g. `prod`, `staging`)    |
| `--no-browser` | —     | `false` | Use terminal prompts instead of browser login |

<Warning>
  Avoid storing passwords in scripts. Consider using environment variables or secure secret management.
</Warning>

## API Key Authentication

For CI/CD pipelines, scripts, and non-interactive environments, use API key authentication instead of browser login.

### Setting Up an API Key

Store an API key in your local config:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth set-api-key <your-api-key>
```

Output:

```
API key saved
  Host:         https://api.dcycle.io (PROD)
  Organization: ff4adcc7-8172-45fe-9cf1-e90a6de53aa9
```

If no organization is set yet, the CLI shows a tip:

```
API key saved
  Host:         https://api.dcycle.io (PROD)
  Tip: set organization with `dcy org set <org-id>` or DCYCLE_ORG_ID env var
```

If no host is configured yet, specify it with `--host`:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth set-api-key <your-api-key> --host prod
```

### Using Environment Variables

You can also authenticate entirely via environment variables — no config file needed:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export DCYCLE_API_KEY=your_api_key
export DCYCLE_HOST=https://api.dcycle.io
export DCYCLE_ORG_ID=your_organization_id

dcy vehicle list
dcy facility list
```

<Tip>
  When `DCYCLE_API_KEY` is set, the CLI uses `x-api-key` header authentication instead of Bearer tokens. This is the recommended approach for CI/CD pipelines.
</Tip>

### CI/CD Example (GitHub Actions)

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
env:
  DCYCLE_API_KEY: ${{ secrets.DCYCLE_API_KEY }}
  DCYCLE_ORG_ID: ${{ secrets.DCYCLE_ORG_ID }}
  DCYCLE_HOST: https://api.dcycle.io

steps:
  - name: Upload vehicle data
    run: dcy vehicle upload --file vehicles.csv --dry-run

  - name: Check facility emissions
    run: dcy facility list --format json
```

### Auth Method Priority

When both an API key and a login token are available, the API key takes precedence:

1. API key (`DCYCLE_API_KEY` env var or `api_key` in config) — uses `x-api-key` header
2. Login token (`dcy auth login`) — uses `Authorization: Bearer` header

### Config File with API Key

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
# ~/.config/dcycle/v2/config.yaml
host: https://api.dcycle.io
api_key: your_api_key_here
organization_id: ff4adcc7-8172-45fe-9cf1-e90a6de53aa9
```

## Checking Session Status

View your current authentication state:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth status
```

Output:

```
Authentication status
  Host:            https://api.dcycle.io (PROD)
  User:            john@company.com
  Name:            John Doe
  Organization:    Acme Corp
  Organization ID: ff4adcc7-8172-45fe-9cf1-e90a6de53aa9
  Auth method:     token
  Authenticated:   yes
```

When using an API key, `Auth method` shows `api_key` instead of `token`.

When not authenticated:

```
Not authenticated
```

### Verifying Credentials

Use `--check` to verify your stored credentials are still valid by calling the API:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth status --check
```

When the session is valid:

```
Authentication status
  Host:            https://api.dcycle.io (PROD)
  User:            john@company.com
  Organization:    Acme Corp
  Organization ID: ff4adcc7-8172-45fe-9cf1-e90a6de53aa9
  Auth method:     token
  Session:         valid
```

When the session has expired (exit code 2):

```
Authentication status
  Host:            https://api.dcycle.io (PROD)
  User:            john@company.com
  Auth method:     token
  Session:         expired
Error: session expired or invalid; run `dcy auth login`
```

<Tip>
  Use `--check` in CI/CD pipelines to validate credentials before running commands:

  ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
  dcy auth status --check || dcy auth login --email "$EMAIL" --password "$PASSWORD"
  ```
</Tip>

| Flag      | Default | Description                        |
| --------- | ------- | ---------------------------------- |
| `--check` | `false` | Verify credentials against the API |

### JSON Response

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth status --format json
```

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "authenticated": true,
  "auth_method": "token",
  "host": "https://api.dcycle.io",
  "environment": "PROD",
  "user": "john@company.com",
  "name": "John Doe",
  "organization": "Acme Corp",
  "organization_id": "ff4adcc7-8172-45fe-9cf1-e90a6de53aa9"
}
```

With `--check`, the JSON response includes `valid` and `check_error` fields:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth status --check --format json
```

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "authenticated": true,
  "auth_method": "token",
  "host": "https://api.dcycle.io",
  "environment": "PROD",
  "user": "john@company.com",
  "name": "John Doe",
  "organization": "Acme Corp",
  "organization_id": "ff4adcc7-8172-45fe-9cf1-e90a6de53aa9",
  "valid": true
}
```

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Extract the current organization for scripts
ORG_ID=$(dcy auth status --format json | jq -r '.organization_id')
```

## Logging Out

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth logout
```

Output:

```
Logged out
```

If not currently logged in:

```
Not currently logged in
```

This removes your stored credentials from the local configuration.

## Configuring Environments

The CLI can connect to different Dcycle environments.

### List Available Hosts

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy config host list
```

Output:

```
production  https://api.dcycle.io           PROD     yes
staging     https://api.stg.dcycle.io       STAGING
dev         https://api.dev.dcycle.io       DEV
local       http://localhost:8000           LOCAL
```

Each row shows: alias, URL, environment, and `yes` if it's the current host.

### JSON Response

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy config host list --format json
```

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
[
  {
    "alias": "production",
    "url": "https://api.dcycle.io",
    "environment": "PROD",
    "active": true
  },
  {
    "alias": "staging",
    "url": "https://api.stg.dcycle.io",
    "environment": "STAGING",
    "active": false
  },
  {
    "alias": "dev",
    "url": "https://api.dev.dcycle.io",
    "environment": "DEV",
    "active": false
  },
  {
    "alias": "local",
    "url": "http://localhost:8000",
    "environment": "LOCAL",
    "active": false
  }
]
```

### Switch Environment

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Production (default)
dcy config host set production

# Staging environment
dcy config host set staging

# Development environment
dcy config host set dev

# Local development
dcy config host set local
```

Output:

```
host set to https://api.dcycle.io (PROD)
```

<Tip>
  Both `prod` and `production` resolve to the same URL. Use whichever you prefer.
</Tip>

<Info>
  Development and staging environments automatically disable SSL verification for self-signed certificates.
</Info>

## Configuration Management

### Show Current Configuration

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Human-readable YAML format (tokens redacted)
dcy config show

# JSON format
dcy config show --format json
```

### List Config Values

Quick summary of host, environment, user, and organization:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy config list
```

Output:

```
Host: https://api.dcycle.io
Environment: PROD
User: john@company.com
Organization: Acme Corp
Organization ID: ff4adcc7-...
Token: ***
```

### JSON Response

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy config list --format json
```

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{
  "host": "https://api.dcycle.io",
  "environment": "PROD",
  "user": "john@company.com",
  "organization": "Acme Corp",
  "organization_id": "ff4adcc7-8172-45fe-9cf1-e90a6de53aa9",
  "has_token": true,
  "has_api_key": false
}
```

### Get / Set Individual Values

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Get a value
dcy config get host
dcy config get organization_id

# Set a value
dcy config set host https://api.dcycle.io
```

### Print Config File Path

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy config path
```

### Reset Configuration

Remove all stored credentials, tokens, and settings:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Interactive confirmation
dcy config reset
```

Confirmation prompt:

```
Reset config at /home/user/.config/dcycle/v2/config.yaml? All credentials will be removed. [y/N]
```

Output:

```
config reset: /home/user/.config/dcycle/v2/config.yaml
```

| Flag    | Short | Default | Description              |
| ------- | ----- | ------- | ------------------------ |
| `--yes` | `-y`  | `false` | Skip confirmation prompt |

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Skip confirmation
dcy config reset --yes
```

### Import from Legacy CLI

If you previously used the Python `dc` CLI, import your configuration:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Import (will error if v2 config already exists)
dcy config import-legacy

# Overwrite existing v2 config
dcy config import-legacy --force
```

## Configuration File

The CLI stores configuration in `~/.config/dcycle/v2/config.yaml`:

```yaml theme={"theme":{"light":"github-light","dark":"github-dark"}}
# ~/.config/dcycle/v2/config.yaml
host: https://api.dcycle.io
token: eyJhbGciOiJIUzI1NiIs...       # set by dcy auth login
api_key: dc_key_abc123...              # set by dcy auth set-api-key (optional)
organization_id: ff4adcc7-8172-45fe-9cf1-e90a6de53aa9
organization_name: Acme Corp
user_email: john@company.com
user_name: John Doe
```

### Configuration Priority

1. Command-line flags (highest priority)
2. Environment variables (`DCYCLE_API_KEY`, `DCYCLE_HOST`)
3. Configuration file (`~/.config/dcycle/v2/config.yaml`)
4. Defaults (lowest priority)

## Environment Variables

For CI/CD and automation:

| Variable         | Description                                       |
| ---------------- | ------------------------------------------------- |
| `DCYCLE_API_KEY` | API key for authentication (alternative to login) |
| `DCYCLE_HOST`    | Override the API host URL                         |
| `DCYCLE_ORG_ID`  | Override the active organization                  |
| `DCYCLE_FORMAT`  | Default output format: `text` or `json`           |
| `DCYCLE_VERBOSE` | Enable verbose HTTP logging (`1` or `true`)       |
| `DCYCLE_TIMEOUT` | HTTP request timeout in seconds (default: `30`)   |
| `NO_COLOR`       | Disable ANSI color output when set                |

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
# Example: Using API key in CI/CD
export DCYCLE_API_KEY=your_api_key
export DCYCLE_ORG_ID=your_org_id
dcy vehicle list

# Example: Debug mode with JSON output
export DCYCLE_VERBOSE=1
export DCYCLE_FORMAT=json
dcy facility list
```

## CLI Health Check

Run `dcy doctor` to verify your CLI setup:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy doctor
```

Output:

```
CLI Health Check

  ✓ Config file — /home/user/.config/dcycle/v2/config.yaml
  ✓ API host — https://api.dcycle.io (PROD)
  ✓ Authentication — Bearer token
  ✓ Organization — Acme Corp (ff4adcc7-...)
  ✓ API connectivity — authenticated as john@company.com
  ✓ Version — v0.0.45 (latest)

All checks passed.
```

When issues are found:

```
CLI Health Check

  ✓ Config file — /home/user/.config/dcycle/v2/config.yaml
  ✓ API host — https://api.dcycle.io (PROD)
  ✗ Authentication — not authenticated; run `dcy auth login` or `dcy auth set-api-key`
  ! Organization — not set; run `dcy org set <org-id>`
  ✓ Version — v0.0.45 (latest)

2 issue(s) found.
```

Icons: `✓` = ok, `!` = warning, `✗` = failure. Use `--format json` for machine-readable output.

## Troubleshooting

### Permission Errors (403/404)

1. Verify your session is valid:
   ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
   dcy auth status --check
   ```

2. Check you're in the correct organization:
   ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
   dcy org list
   dcy org set <correct-org-id>
   ```

3. Run the health check:
   ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
   dcy doctor
   ```

### Token Expired

Check and re-authenticate:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy auth status --check   # verify the session is expired
dcy auth login             # re-authenticate
```

### SSL Certificate Errors

For staging/development environments:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy config host set staging  # Auto-disables SSL verification
```

### Reset Everything

If the config is corrupted, start fresh:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
dcy config reset --yes
dcy auth login
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Organizations" icon="sitemap" href="/cli/organizations">
    Learn how to manage organization context
  </Card>

  <Card title="Configuration" icon="gear" href="/cli/configuration">
    Advanced configuration and environment setup
  </Card>

  <Card title="Examples" icon="code" href="/cli/examples">
    See common workflow examples
  </Card>

  <Card title="Overview" icon="terminal" href="/cli/overview">
    Full command reference
  </Card>
</CardGroup>
