Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | 4x 4x | /*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
import type { EC3ConfigPropsWithRedirectUri } from "./EC3Config";
import { getDefaultEC3Uri } from "./EC3Config";
import type { EC3Token } from "./EC3Token";
/* This function must be called in EC3 authentication redirect path.
*
* Example:
* } else if (window.location.pathname === "/callback") {
* handleEC3AuthCallback({
* clientId: "...",
* redirectUri: "http://localhost:8887/callback",
* });
* } else {
*/
/**
* EC3 Auth Callback Config Props
* @beta
*/
export type EC3AuthCallbackConfigProps = Pick<EC3ConfigPropsWithRedirectUri, "clientId" | "redirectUri" | "ec3Uri">;
/**
* Simple implementation to handle EC3 OAuth2 callback and exchange token
* @beta
*/
export function handleEC3AuthCallback(ec3Config: EC3AuthCallbackConfigProps, source: string = "ec3-auth") {
const MILLI_SECONDS = 1000;
const ec3Uri = getDefaultEC3Uri(ec3Config.ec3Uri);
async function exchangeToken() {
const code = new URL(window.location.href).searchParams.get("code");
const prop = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: `client_id=${ec3Config.clientId}&grant_type=authorization_code&code=${code}&redirect_uri=${ec3Config.redirectUri}`,
};
const response = await fetch(`${ec3Uri}api/oauth2/token`, prop);
const tokenResponse = await response.json();
const token: EC3Token = {
token: tokenResponse.access_token,
exp: Date.now() + tokenResponse.expires_in * MILLI_SECONDS,
source,
};
const parentWindow = window.opener as Window;
parentWindow.postMessage(token, window.location.origin);
}
void exchangeToken();
}
|