| 1 | BEGIN; |
| 2 | |
| 3 | -- One row per refresh token we've issued. A login starts a family, and every |
| 4 | -- refresh adds a token to it and retires the one it replaced. |
| 5 | CREATE TABLE refresh_tokens ( |
| 6 | id uuid PRIMARY KEY DEFAULT gen_random_uuid(), |
| 7 | user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE, |
| 8 | -- SHA-256 of the token. A leaked table holds no working tokens. |
| 9 | token_hash bytea NOT NULL UNIQUE, |
| 10 | -- the login this token descends from, and the token it replaced |
| 11 | family_id uuid NOT NULL, |
| 12 | parent_id uuid REFERENCES refresh_tokens (id) ON DELETE CASCADE, |
| 13 | -- when it was exchanged for a new token: using it again is reuse |
| 14 | rotated_at timestamptz, |
| 15 | revoked_at timestamptz, |
| 16 | expires_at timestamptz NOT NULL, |
| 17 | created_at timestamptz NOT NULL DEFAULT now() |
| 18 | ); |
| 19 | |
| 20 | -- Reuse and logout revoke a whole family at once. |
| 21 | CREATE INDEX refresh_tokens_family_id_idx ON refresh_tokens (family_id); |
| 22 | -- A user's sessions, and the foreign key from users. |
| 23 | CREATE INDEX refresh_tokens_user_id_idx ON refresh_tokens (user_id); |
| 24 | |
| 25 | COMMIT; |