-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add useDashboardToken to app bridge module
- Loading branch information
1 parent
0352356
commit 6a162b7
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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), | ||
}; | ||
}; |