TUTORIAL

Get Access Token for Weavy user in Jira

The following tutorial shows what a typical implementation of the tokenFactory and corresponding server-side code in your application could look like. As the example shows, we recommend that your server store and reuse access tokens to avoid unnecessary roundtrips.

Requesting a new access token from Weavy should always be done from your server side. Forge uses a bridge that allows you to define backend functions that can be called from the frontend.

Modify index.js

Update the index.js file located in the src folder in your forge project with the following code.
Modify index.js
import Resolver from '@forge/resolver';
import api, { fetch, route } from '@forge/api';

let _tokens = [];
const apiKey = "********************";
const backend = "WEAVY_URL";

resolver.define("token", async (req, res) => {
    // get jira user's account id
    const accountId = req.context.accountId;

    // check if we already have a token stored for the user or if we need to refresh the token
    if ((!req.payload.refresh || req.payload.refresh === "false") && _tokens.find((t) => t.accountId === accountId)) {
        res.json({ access_token: _tokens.find((t) => t.accountId === accountId).access_token });
    } else {
        // get an access token from weavy backend
        let response = await fetch(`${backend}/api/users/${accountId}/tokens`, {
            method: 'POST',
            headers: {
                'content-type': 'application/json',
                'Authorization': `Bearer ${apiKey}`
            },
            body: JSON.stringify({ expires_in: 3600 })
        });

        if (response.ok) {
            let data = await response.json();
            // store the access token so we don't need to call the api every time (unless we need to refresh the token)
            _tokens = [..._tokens.filter((t) => t.accountId !== accountId), { accountId: accountId, access_token: data.access_token }];
            return data.access_token;
        } else {
            return ({ message: "Could not get access token from server!", accountId: accountId, error: response })
        }
    }
});

export const handler = resolver.getDefinitions();

Modify App.js

Update the app.js file and change the tokenFactory to call the /token endpoint whenever the Weavy building block requires a token.
Update tokenFactoy in App.js
weavy.tokenFactory = async (refresh) => {
    return await invoke('token', { refresh: refresh });
};
Unlock the tutorial with your Weavy API key.