/ src / utils / auth.js
auth.js
 1  const { VITE_CLIENT_NAME: CLIENT_NAME, VITE_WEBSITE: WEBSITE } = import.meta
 2    .env;
 3  
 4  const SCOPES = 'read write follow push';
 5  
 6  export async function registerApplication({ instanceURL }) {
 7    const registrationParams = new URLSearchParams({
 8      client_name: CLIENT_NAME,
 9      redirect_uris: location.origin + location.pathname,
10      scopes: SCOPES,
11      website: WEBSITE,
12    });
13    const registrationResponse = await fetch(
14      `https://${instanceURL}/api/v1/apps`,
15      {
16        method: 'POST',
17        headers: {
18          'Content-Type': 'application/x-www-form-urlencoded',
19        },
20        body: registrationParams.toString(),
21      },
22    );
23    const registrationJSON = await registrationResponse.json();
24    console.log({ registrationJSON });
25    return registrationJSON;
26  }
27  
28  export async function getAuthorizationURL({ instanceURL, client_id }) {
29    const authorizationParams = new URLSearchParams({
30      client_id,
31      scope: SCOPES,
32      redirect_uri: location.origin + location.pathname,
33      // redirect_uri: 'urn:ietf:wg:oauth:2.0:oob',
34      response_type: 'code',
35    });
36    const authorizationURL = `https://${instanceURL}/oauth/authorize?${authorizationParams.toString()}`;
37    return authorizationURL;
38  }
39  
40  export async function getAccessToken({
41    instanceURL,
42    client_id,
43    client_secret,
44    code,
45  }) {
46    const params = new URLSearchParams({
47      client_id,
48      client_secret,
49      redirect_uri: location.origin + location.pathname,
50      grant_type: 'authorization_code',
51      code,
52      scope: SCOPES,
53    });
54    const tokenResponse = await fetch(`https://${instanceURL}/oauth/token`, {
55      method: 'POST',
56      headers: {
57        'Content-Type': 'application/x-www-form-urlencoded',
58      },
59      body: params.toString(),
60    });
61    const tokenJSON = await tokenResponse.json();
62    console.log({ tokenJSON });
63    return tokenJSON;
64  }