Authentication

Grids uses Discord OAuth for user authentication, with JWT tokens for API access and a device-code flow for linking the game client to a web account.

Discord OAuth Flow

1. Initiate Login

GET /auth/discord

Redirects the user to Discord's authorization page. After approval, Discord redirects back to:

GET /auth/discord/callback?code=...

2. Callback

The callback exchanges the authorization code for a Discord access token, fetches the user profile, and creates or updates the user in the D1 database.

Response: Returns a JWT token and redirects to the web app.

3. JWT Token

Tokens use HS256 signing with a 24-hour expiry. The payload contains:

{
  "sub": "user_id",
  "discord_id": "123456789",
  "display_name": "PlayerName",
  "iat": 1712000000,
  "exp": 1712086400
}

Device Linking

The device-code flow lets the game client authenticate without a browser embedded in the game.

Step 1: Generate Code

From the game client:

POST /auth/device/code

Response:

{
  "device_code": "ABCD-1234",
  "verification_url": "https://a-new-world.com/auth/link",
  "expires_in": 300
}

Step 2: User Links

The player visits a-new-world.com/auth/link in their browser, logs in via Discord, and enters the device code.

Step 3: Game Polls

The game client polls the API with the device code until the link is confirmed:

POST /auth/device/link
Content-Type: application/json

{
  "device_code": "ABCD-1234"
}

Response (success):

{
  "status": "linked",
  "token": "<jwt_token>",
  "user": {
    "id": "user_id",
    "display_name": "PlayerName",
    "avatar": "https://cdn.discordapp.com/..."
  }
}

Response (pending):

{
  "status": "pending"
}