Skip to content

Commit

Permalink
Add useDashboardToken to app bridge module
Browse files Browse the repository at this point in the history
  • Loading branch information
lkostrowski committed Oct 4, 2022
1 parent 0352356 commit 6a162b7
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/app-bridge/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export * from "./actions";
export * from "./app-bridge-provider";
export * from "./events";
export * from "./types";
export * from "./use-dashboard-token";

/**
* @deprecated use new AppBridge(), createApp will be removed
Expand Down
49 changes: 49 additions & 0 deletions src/app-bridge/use-dashboard-token.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import debugPkg from "debug";
import * as jose from "jose";
import { useMemo } from "react";

import { useAppBridge } from "./app-bridge-provider";

export interface DashboardTokenPayload extends jose.JWTPayload {
app: string;
}

export interface DashboardTokenProps {
isTokenValid: boolean;
hasAppToken: boolean;
tokenClaims: DashboardTokenPayload | null;
}

const debug = debugPkg.debug("app-sdk:AppBridge");

export const useDashboardToken = (): DashboardTokenProps => {
const { appBridgeState } = useAppBridge();

const tokenClaims = useMemo(() => {
try {
if (appBridgeState?.token) {
debug("Trying to decode JWT token drom dashboard");
return jose.decodeJwt(appBridgeState?.token) as DashboardTokenPayload;
}
} catch (e) {
debug("Failed decoding JWT token");
console.error(e);
}
return null;
}, [appBridgeState?.token]);

if (tokenClaims && !tokenClaims.iss) {
console.error(`
"iss" not found in decoded token claims. Ensure Saleor has domain assigned
Check documentation for more details
https://docs.saleor.io/docs/3.x/dashboard/configuration/site#general-information`);
}

const isTokenValid = tokenClaims ? tokenClaims.iss === appBridgeState?.domain : false;

return {
isTokenValid,
tokenClaims,
hasAppToken: Boolean(appBridgeState?.token),
};
};

0 comments on commit 6a162b7

Please sign in to comment.