# Custom token validation

If your app uses its own sign-in (provider `custom`), StickyHealth cannot check your tokens itself. Instead, your server hosts a validation endpoint: we send it the token, and it tells us who the user is. This page is the contract that endpoint must follow.

### Overview

- You build the endpoint and send us its URL. We register it for your organization.
- The app never sends the URL. In the SDK, the custom provider's `config` has no URL field: `auth={{ token, provider: 'custom', config: {} }}`.
- On every sign-in from your app, StickyHealth calls the endpoint with the member's token, plus an authorization request when the app sent one (see **Authorization requests**).

### Endpoint requirements

- **Protocol**: HTTPS
- **Method**: `POST`, JSON body
- **Timeout**: respond within 10 seconds, or the sign-in fails

### Request

#### Token validation

```json
{
  "token": "string"
}
```

#### Token validation with an authorization request

```json
{
  "token": "string",
  "authorization_request": {
    "entries": [
      { "external_uid": "string" }
    ]
  }
}
```

The entries contain only `external_uid` values. StickyHealth sets the permissions and the one-hour expiry itself. Your endpoint decides only whether the signed-in user may access each listed member.

### Response

#### Basic response

```json
{
  "sub": "string"
}
```

#### Response to an authorization request

When the request contains `authorization_request`, your response **must** contain `authorization_request` too, listing the entries you approve:

```json
{
  "sub": "string",
  "authorization_request": {
    "entries": [
      { "external_uid": "string" }
    ]
  }
}
```

### Response requirements

1. Return HTTP `200` with a JSON body for a valid token.
1. `sub` is required: the user's id in your system. It becomes the member's `external_uid`, which webhooks and authorization requests use to refer to them.
1. If the request contained `authorization_request`, always echo `authorization_request` back with only the entries you approve. Leave out any entry the user may not access. Return `"entries": []` to approve none.
1. Other fields are allowed. `email`, `name` and `picture`, if present, fill in the member's profile.

### Validating authorization requests

When the request contains an authorization request:

1. **Check permissions**: make sure the authenticated user may access each requested member.
1. **Check the ids**: make sure each `external_uid` is a real user in your system.
1. **Log it**: record every authorization request for audit.

Never trust the requested list on its own: it comes from the app. Only your endpoint can confirm that the user may access those members.

### Errors

For an invalid token or a failed check, return an error status. Any status outside 2xx fails the sign-in. We suggest:

- `400`: invalid request format
- `401`: invalid or expired token
- `403`: the user may not grant the requested access
- `500`: internal error

```json
{
  "error": "Invalid token",
  "message": "Token has expired"
}
```

### Examples

A valid token:

```json
{
  "sub": "user123",
  "email": "user@example.com",
  "name": "Jane Doe"
}
```

A valid token with an approved authorization request:

```json
{
  "sub": "careteam456",
  "email": "careteam@example.com",
  "name": "Care Team User",
  "authorization_request": {
    "entries": [
      { "external_uid": "user123" }
    ]
  }
}
```

### Implementation example (Python, Flask)

`is_valid_token`, `extract_user_from_token` and `can_access_member` stand in for your own logic.

```python
from flask import Flask, jsonify, request

app = Flask(__name__)


@app.route("/validate", methods=["POST"])
def validate_token():
    data = request.get_json(silent=True) or {}
    token = data.get("token")
    if not token or not is_valid_token(token):
        return jsonify({"error": "Invalid token"}), 401

    user = extract_user_from_token(token)
    response = {"sub": user["id"], "email": user["email"], "name": user["name"]}

    auth_request = data.get("authorization_request")
    if auth_request is not None:
        # Always echo it back, with only the members this user may access.
        response["authorization_request"] = {
            "entries": [
                {"external_uid": entry["external_uid"]}
                for entry in auth_request.get("entries", [])
                if can_access_member(user, entry.get("external_uid"))
            ]
        }

    return jsonify(response)
```

### Security requirements

1. Serve the endpoint over HTTPS only.
1. Rate-limit it.
1. Validate the request body.
1. Approve only members the authenticated user is allowed to manage.
1. Log every authorization request for audit.
