Sign-in¶
This page shows how a tool on SweatStack Tools calls the SweatStack API, with a token that SweatStack Tools gets for it.
Beta
SweatStack Tools is in beta and is subject to breaking changes. If you plan to use it in production, email [email protected] before you integrate, so we can tell you about changes in advance and help you migrate.
SweatStack Tools signs a person in before it serves a page of your tool. Your tool contains no OAuth code. It reads an access token from a cookie and sends it to the API.
How it works¶
- A person opens your tool. If they are not signed in to it, SweatStack Tools sends them to SweatStack, which asks them to share the data your tool declared.
- SweatStack sends them back. SweatStack Tools keeps two cookies on your tool's address: an access token, which your code can read, and a refresh token, which it can't.
- Your code reads the access token from the cookie for each API request.
- When the access token is missing or refused, your code asks SweatStack Tools for a new one.
The next time the person opens your tool, they are signed in already. A person who shared their data with your tool is not asked to share it again, unless they revoked it.
A tool that declares no data scopes has no sign-in. Nobody signs in to it.
Call the API¶
Copy this file into your tool as vendor/sweatstack.js. Don't change it. sweatstack tool create adds it to a new tool.
const COOKIE = /(?:^|; )__Host-sweatstack_access_token=([^;]*)/;
// Each Tools app pairs with one SweatStack app: staging tools with staging, the rest with production.
const API = location.hostname.endsWith(".sweatstack-tools-staging.dev")
? "https://staging.sweatstack.no"
: "https://app.sweatstack.no";
let pending = null;
function cookieToken() {
const match = document.cookie.match(COOKIE);
return match ? match[1] : null;
}
function signIn() {
const back = location.pathname + location.search;
location.assign(`/_sweatstack/sign-in?return=${encodeURIComponent(back)}`);
}
function freshToken() {
pending ??= fetch("/_sweatstack/token", { method: "POST" })
.then(async (response) => {
if (response.status === 401) {
signIn();
return new Promise(() => {}); // The page is going away.
}
if (!response.ok) throw new Error(`SweatStack sign-in failed: ${response.status}`);
return (await response.json()).access_token;
})
.finally(() => { pending = null; });
return pending;
}
export async function sweatstack(path, init = {}) {
for (const retry of [false, true]) {
const token = (!retry && cookieToken()) || (await freshToken());
const headers = new Headers(init.headers);
headers.set("Authorization", `Bearer ${token}`);
const response = await fetch(`${API}${path}`, { ...init, headers });
if (response.status !== 401 || retry) return response;
}
}
export async function signOut() {
await fetch("/_sweatstack/sign-out", { method: "POST" });
}
Call the API through sweatstack(). It takes a path and the same options as fetch, and returns the Response:
import { sweatstack } from "./vendor/sweatstack.js";
const response = await sweatstack("/api/v1/activities/latest");
if (!response.ok) throw new Error(`The API answered ${response.status}`);
const activity = await response.json();
- A request body must be a string,
Blob,FormData,ArrayBufferorURLSearchParams. Not a stream:sweatstack()sends a request again after a refused token. - Don't keep the token. Not in a variable,
localStorageor a closure.sweatstack()reads the cookie for each request. - Don't write your own sign-in. Don't go to
/oauth/authorize, and don't open a popup.
Use a web worker¶
A web worker has no document.cookie. Ask SweatStack Tools for a token:
const response = await fetch("/_sweatstack/token", { method: "POST" });
if (response.status === 401) {
postMessage({ type: "sweatstack-signed-out" });
} else {
const { access_token } = await response.json();
}
When the page receives sweatstack-signed-out, send the person to sign in again:
location.assign(`/_sweatstack/sign-in?return=${encodeURIComponent(location.pathname + location.search)}`);
Sign out¶
import { signOut } from "./vendor/sweatstack.js";
await signOut();
signOut() ends the sign-in on SweatStack and clears both cookies. Then show your tool's own signed-out state, with a link to /_sweatstack/sign-in?return=%2F. Don't reload the page: a reload signs the person in again.
A person ends a tool's access to their data for good by revoking it in their SweatStack account.
Test sign-in on your computer¶
sweatstack tool serve signs in as SweatStack Tools does. It reads your tool's slug, folder and scopes from sweatstack.toml, and serves the tool at http://{slug}.localhost:{port}.
- Use Chrome or Firefox. Safari keeps no sign-in cookie on
http://, so sign-in undertool servedoesn't work there. On SweatStack Tools, Safari works. - Your tool calls the production API under
tool serve.
What SweatStack Tools reserves¶
| Address on your tool | What it does |
|---|---|
POST /_sweatstack/token |
Returns {"access_token": "…", "expires_in": 840}, 401 when the person must sign in again, or 503 when SweatStack can't be reached |
GET /_sweatstack/sign-in?return={path} |
Signs the person in, and returns to {path} on your tool |
POST /_sweatstack/sign-out |
Ends the sign-in and clears both cookies |
GET /_sweatstack/callback |
Where SweatStack sends the person back |
A file in your tool whose path starts with _sweatstack or _gate is never served.