Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 40 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,43 @@ An **optional** [Open API specification](https://swagger.io/specification/) obje
#### **defaultErrorHandler** `(error:OrderCloudError) => void`
An **optional** callback function for globally handling OrderCloud errors in your application. Useful for wiring up toast-like feedback.

#### **openIdConnect** `object`
An **optional** object containing configuration for single-sign-on via [OpenID Connect](https://ordercloud.io/knowledge-base/sso-via-openid-connect).

### **openIdConnect** `boolean`
Set to `true` to activate single-sign-on via OpenIDConnect in your application. If `false`, all OIDC logic (such as login redirects and token handling) will be disabled, even if configs are defined.

#### **openIdConnect.configs** `{id: string, roles?: string[], clientId: string}[]`
An array of OpenID Connect configuration objects. Each defines the settings required to authenticate against a specific identity provider. At least one configuration must be provided.

#### **openIdConnect.configs.[i].id** `string`
The ID of the [OpenID connect configuration](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create) that should be targeted for authentication

#### **openIdConnect.configs.[i].roles** `string`
An **optional** array of roles that will be requested when authenticating. If excluded, the token generated will contain any roles assigned to the user. Unless you have a specific reason for limiting roles, we recommend omitting this option.

#### **openIdConnect.configs.[i].clientId** `string`
An **optional** OrderCloud clientId to authenticate against. By default, will use `clientId` at the root of the provider settings.

#### **openIdConnect.configs.[i].appStartPath** `string`
An **optional** path to redirect the user to after returning from the identity provider. See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect#deep-linking) for more information

#### **openIdConnect.configs.[i].customParams** `string`
**optional** query parameters passed along to the `AuthorizationEndpoint`. See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect) for more information

#### **openIdConnect.autoRedirect** `boolean`
True will automatically redirect the user to the first openIdConnect config stored if the token is expired, or invalid. This is a simplified use case. For more control, or when you need to handle multiple identity providers set this to false and handle redirect on your own by calling `loginWithOpenIdConnect`

### **openIdConnect.accessTokenQueryParamName** `string`
Query parameter name where the OrderCloud access token is stored after login. For example, if [AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create) is `https://my-application.com/login?token={0}`, use `token`

### **openIdConnect.refreshTokenQueryParamName**
The **optional** query parameter name for the refresh token after login. Example: if [AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create) is `https://my-application.com/login?token={0}&refresh={3}`, use `refresh`


### **openIdConnect.idpAccessTokenQueryParamName**
The **optional** query parameter name for the identity provider access token after login. Example: if [AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create) is `https://my-application.com/login?token={0}&idptoken={1}`, use `idptoken`

## `useOrderCloudContext()` hook
This hook returns the OrderCloud context that the OrderCloudProvider sets up based on your provided options. If anonymous authentication is allowed the OrderCloud context will automatically be in an authenticated state on first page load (shortly after the first React lifecycle).

Expand All @@ -53,6 +90,9 @@ When true, the currently active OrderCloud access token is a _registered_ user (
#### **login**: `(username:string, password:string, rememberMe:boolean) => Promise<AccessToken>`
An asyncrhonous callback method for building a login form for your application. When **rememberMe** is set to `true`, the `OrderCloudProvider` will attempt to store and use the `refresh_token` as long as it is valid. It is not necessary to do anything with the `AccessToken` response as this method will take care of managing the active token and authentication state for you.

### **loginWithOpenIdConnect**: `(openIdConnectId: string, options?: { appStartPath?: string; customParams?: string; }) => void
A method for manually redirecting a user to the identity provider login page defined by the openIdConnectId. To use this method you must define the relevent `openIdConnect` properties

#### **logout**: `() => void`
A callback for logging out a registered user from your application. This will also clear the Tanstack query client cache for OrderCloud API calls, forcing any actively used queries to refetch once anonymous auth takes over again or the user logs back in.

Expand Down
9 changes: 5 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@
"@hookform/resolvers": "^3.3.4",
"@tanstack/react-query": "^5.62.2",
"@tanstack/react-table": "^8.20.5",
"ordercloud-javascript-sdk": "^10.0.0",
"axios": "^1.1.3",
"ordercloud-javascript-sdk": "^11.1.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.2"
Expand Down
7 changes: 7 additions & 0 deletions src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,13 @@ const INITIAL_ORDERCLOUD_CONTEXT: IOrderCloudContext = {
login: async (username: string, password: string, rememberMe?: boolean) => {
return Promise.reject({username, password, rememberMe})
},
loginWithOpenIdConnect: (
openIdConnectId: string
) => {
throw new Error(
`loginWithOpenIdConnect is not implemented. ${openIdConnectId}`
);
},
setToken: async (accessToken: string ) => {
return Promise.reject({accessToken})
},
Expand Down
42 changes: 42 additions & 0 deletions src/hooks/useOnceAtATime.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { useRef, useCallback } from 'react';

/**
* useOnceAtATime
*
* A React hook that ensures an async function is only executed once at a time.
* While the function is in-flight, all subsequent calls return the same Promise.
* Once the function resolves or rejects, it can be called again.
*
* Useful for deduplicating concurrent requests (e.g. token validation, lazy loading).
*
* @template TArgs - Argument types of the async function
* @template TResult - Return type of the async function
*
* @param fn - The async function to guard
* @returns An object with:
* - run: the deduplicated function
* - isRunning: boolean indicating whether the function is currently executing
*/
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I had to use this with verifyToken to solve a race condition I was facing where a second invocation thought I wasn't logged in even though I was.

export function useOnceAtATime<TArgs extends any[], TResult>(
fn: (...args: TArgs) => Promise<TResult>
) {
const inFlightRef = useRef<Promise<TResult> | null>(null);

const run = useCallback((...args: TArgs): Promise<TResult> => {
if (inFlightRef.current) return inFlightRef.current;

inFlightRef.current = (async () => {
try {
return await fn(...args);
} finally {
inFlightRef.current = null; // allow future calls
}
})();

return inFlightRef.current;
}, [fn]);

const isRunning = !!inFlightRef.current;

return { run, isRunning };
}
89 changes: 89 additions & 0 deletions src/models/IOpenIdConnectSettings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
export interface IOpenIdConnectSettings
{
/**
* Enables or disables OpenID Connect authentication.
*
* Set to `true` to activate OIDC support in your application. If `false`, all OIDC logic
* (such as login redirects and token handling) will be disabled, even if configs are defined.
*/
enabled: boolean
/**
* An array of OpenID Connect configuration objects.
* Each defines the settings required to authenticate against a specific identity provider.
* At least one configuration must be provided.
*/
configs: IOpenIdConnectConfig[]
/**
* True will automatically redirect the user to the
* first openIdConnect config stored if the token is expired, or invalid.
* This is a simplified use case. For more control, or when you need to
* handle multiple identity providers set this to false and handle redirect on your
* own by calling `loginWithOpenIdConnect`
*/
autoRedirect?: boolean
/**
* The name of the query parameter under which the ordercloud access token will be stored under after successful login.
* This will vary based on your [OpenIdConnect.AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create).
* For example if your `AppStartUrl` is `https://my-buyer-application.com/login?token={0}` then the value should be `token`
*/
accessTokenQueryParamName: string
/**
* The **optional** name of the query parameter under which the ordercloud refresh token will be stored
* under after successful login. This will vary based on your [OpenIdConnect.AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create).
* For example if your `AppStartUrl` is `https://my-buyer-application.com/login?token={0}&refresh={3}` then the value should be `refresh`
*/
refreshTokenQueryParamName?: string
/**
* The **optional** name of the query parameter under which the idp access token will be stored
* under after successful login. This will vary based on your [OpenIdConnect.AppStartUrl](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create).
* For example if your `AppStartUrl` is `https://my-buyer-application.com/login?token={0}&idptoken={1}` then the value should be `idptoken`
*/
idpAccessTokenQueryParamName?: string
/**
* An **optional** path to redirect the user to after returning from the identity provider.
* See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect#deep-linking) for more information
* This global setting will be used if not overridden by the `appStartPath` in the individual OpenID Connect configurations.
* Call `setAppStartPath()` to change this value at runtime.
*/
appStartPath?: string
/**
* **optional** query parameters passed along to the `AuthorizationEndpoint`.
* See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect) for more information
* This global setting will be used if not overridden by the `customParams` in the individual OpenID Connect configurations.
* Call `setCustomParams()` to change this value at runtime.
*/
customParams?: string
}

export interface IOpenIdConnectConfig
{
/**
* The ID of the [OpenID connect configuration](https://ordercloud.io/api-reference/authentication-and-authorization/open-id-connects/create)
* that should be targeted for authentication
*/
id: string
/**
* An **optional** array of roles that will be requested when authenticating.
* If excluded, the token generated will contain any roles assigned to the user.
* Unless you have a specific reason for limiting roles, we recommend omitting this option.
*/
roles?: string[]
/**
* An **optional** OrderCloud clientId to authenticate against.
* By default, will use `clientId` at the root of the provider settings.
*/
clientId?: string
/**
* An **optional** path to redirect the user to after returning from the identity provider.
* See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect#deep-linking) for more information
* call `setAppStartPath(openIdConnectConfigId)` to change this value at runtime.
*/
appStartPath?: string

/**
* **optional** query parameters passed along to the `AuthorizationEndpoint`.
* See [here](https://ordercloud.io/knowledge-base/sso-via-openid-connect) for more information
* call `setCustomParams(openIdConnectConfigId)` to change this value at runtime.
*/
customParams?: string
}
36 changes: 29 additions & 7 deletions src/models/IOrderCloudContext.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import { AccessToken, ApiRole, OrderCloudError } from "ordercloud-javascript-sdk";
import {
AccessToken,
ApiRole,
OrderCloudError,
} from "ordercloud-javascript-sdk";
import { IOrderCloudErrorContext } from "./IOrderCloudErrorContext";
import { OpenAPIV3 } from "openapi-types";

Expand All @@ -21,15 +25,29 @@ export interface IOrderCloudContext {
/**
* authenticates using the configured client ID and username / password
*/
login: (username:string, password:string, rememberMe?:boolean) => Promise<AccessToken>;
login: (
username: string,
password: string,
rememberMe?: boolean
) => Promise<AccessToken>;
/**
* authenticates using the configured OpenID Connect settings
*/
loginWithOpenIdConnect: (
openIdConnectId: string,
options?: {
appStartPath?: string;
customParams?: string;
}
) => void;
/**
* authenticates using the provided OrderCloud access token
*/
setToken: (accessToken: string ) => void;
setToken: (accessToken: string) => void;
/**
* Signifies when authorization is in a loading state
*/
authLoading: boolean
authLoading: boolean;

/**
* If anonymous, this will retrieve a new anon token, useful for anonymous
Expand All @@ -43,9 +61,13 @@ export interface IOrderCloudContext {
scope?: ApiRole[];
customScope?: string[];
allowAnonymous: boolean;
defaultErrorHandler?: (error:OrderCloudError, context:IOrderCloudErrorContext) => void;
defaultErrorHandler?: (
error: OrderCloudError,
context: IOrderCloudErrorContext
) => void;
token?: string;
idpToken?: string;
xpSchemas?: OpenAPIV3.SchemaObject;
autoApplyPromotions?: boolean;
currencyDefaults: { currencyCode: string, language: string }
}
currencyDefaults: { currencyCode: string; language: string };
}
2 changes: 2 additions & 0 deletions src/models/IOrderCloudProvider.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { ApiRole, OrderCloudError, SdkConfiguration } from "ordercloud-javascript-sdk";
import { IOrderCloudContext } from "./IOrderCloudContext";
import { OpenAPIV3 } from "openapi-types";
import { IOpenIdConnectSettings } from "./IOpenIdConnectSettings";

export interface IOrderCloudProvider {
baseApiUrl: string;
clientId: string;
scope?: ApiRole[];
customScope?: string[];
allowAnonymous: boolean;
openIdConnect?: IOpenIdConnectSettings;
xpSchemas?: OpenAPIV3.SchemaObject;
autoApplyPromotions?: boolean,
configurationOverrides?: Omit<SdkConfiguration, 'baseApiUrl' | 'clientID'>
Expand Down
5 changes: 4 additions & 1 deletion src/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ import { IOrderCloudOperationObject } from "./IOrderCloudOperationObject";
import { IOrderCloudContext } from "./IOrderCloudContext";
import { IOrderCloudErrorContext } from "./IOrderCloudErrorContext";
import { IOrderCloudProvider } from "./IOrderCloudProvider";
import { IOpenIdConnectSettings, IOpenIdConnectConfig } from "./IOpenIdConnectSettings";

export type {
IOrderCloudContext,
IOrderCloudErrorContext,
IOrderCloudProvider,
IOrderCloudOperationObject
IOrderCloudOperationObject,
IOpenIdConnectSettings,
IOpenIdConnectConfig
}
Loading