Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor OIDC calls and added Callback component #77

Merged
merged 4 commits into from
Nov 18, 2024
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
1,806 changes: 858 additions & 948 deletions package-lock.json

Large diffs are not rendered by default.

15 changes: 12 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,15 @@
"access": "public"
},
"dependencies": {
"@deriv-com/utils": "^0.0.37",
"oidc-client-ts": "^3.1.0"
},
"peerDependencies": {
"@deriv-com/utils": "^0.0.37",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@deriv-com/utils": "^0.0.37",
"@eslint/js": "^9.9.0",
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/github": "^10.0.2",
Expand All @@ -42,10 +47,14 @@
"prettier": "3.3.3",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"sass": "^1.80.6",
Copy link
Collaborator

Choose a reason for hiding this comment

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

this is beyond the context of the PR 😅 , let's be more specific when adding changes next time

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

Got it, I've added sass just for styling the Callback component for now

"sass-embedded": "^1.80.6",
"semantic-release": "^23.0.6",
"typescript": "^5.6.3",
"typescript-eslint": "^8.0.1",
"vite": "^5.4.10",
"vite-plugin-dts": "^4.2.1"
"vite": "^5.4.1",
"vite-plugin-dts": "^4.2.1",
"vite-plugin-lib-inject-css": "^2.1.1",
"vite-plugin-svgr": "^4.3.0"
}
}
241 changes: 241 additions & 0 deletions src/assets/404.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
6 changes: 6 additions & 0 deletions src/assets/deriv_logo.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
71 changes: 71 additions & 0 deletions src/components/Callback/Callback.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
@import url('https://fonts.googleapis.com/css2?family=Ubuntu:ital,wght@0,300;0,400;0,500;0,700;1,300;1,400;1,500;1,700&display=swap');

.callback {
font-family: 'Ubuntu', sans-serif;
height: 100vh;
width: 100vw;
background-repeat: no-repeat;
background-position: center;
position: relative;
align-items: center;

&__header {
border-bottom: 1px solid #00000014;
Copy link
Collaborator

Choose a reason for hiding this comment

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

[Q] do we not have any vars css from quill or deriv ui?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

We do, but I don't think we should set this up here for now because the design is not final yet, this is just a placeholder

width: 100%;
display: flex;
align-items: center;
justify-content: center;
gap: 1.4rem;
position: absolute;

& > svg {
width: 72px;
height: 24px;
display: flex;
align-items: center;
justify-content: center;
padding: auto 5%;
min-height: 5rem;
color: #ff444f;
}
}

&__content {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 100%;
gap: 1rem;

h3 {
color: #000000;
font-size: 34px;
text-align: center;
font-weight: bold;
margin: 0;
}

p {
font-weight: normal;
font-size: 16px;
}

button {
width: fit-content;
}
}

&__loading {
div.barspinner {
& > div.barspinner__rect {
background: #ff444f !important;
}
}
}

& > svg {
width: 20rem;
height: 10rem;
}
}
148 changes: 148 additions & 0 deletions src/components/Callback/Callback.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import { useCallback, useState, useEffect } from 'react';
import { LegacyTokens, requestLegacyToken, requestOidcToken, OIDCError, OIDCErrorType } from '../../oidc';
import ErrorIcon from '../../assets/404.svg?react';
import DerivLogoIcon from '../../assets/deriv_logo.svg?react';

import './Callback.scss';
thisyahlen-deriv marked this conversation as resolved.
Show resolved Hide resolved

const Loading = () => (
<div className={`barspinner barspinner--dark dark`}>
{Array.from(new Array(5)).map((_, inx) => (
<div key={inx} className={`barspinner__rect barspinner__rect--${inx + 1} rect${inx + 1}`} />
))}
</div>
);

type CallbackProps = {
/** callback function triggerred when `requestOidcToken` is successful. Use this only when you want to request the legacy tokens yourself, otherwise pass your callback to `onSignInSuccess` prop instead */
onRequestOidcTokenSuccess?: (accessToken: string) => void;
/** callback function triggered when the OIDC authentication flow is successful */
onSignInSuccess?: (tokens: LegacyTokens) => void;
/** callback function triggered when sign-in encounters an error */
onSignInError?: (error: Error) => void;
/** URI to redirect to the callback page. This is where you should pass the callback page URL in your app .e.g. https://app.deriv.com/callback or https://smarttrader.deriv.com/en/callback */
redirectCallbackUri?: string;
/** URI to redirect after authentication is completed or failed */
postLoginRedirectUri?: string;
/** URI to redirect after logout */
postLogoutRedirectUri?: string;
/** callback function triggered when return button is clicked in error state */
onClickReturn?: (error: OIDCError) => void;
/** custom error message to display */
errorMessage?: string;
};

/**
* Callback component handles the OAuth callback process and token management
*
* @component
* @param {Object} props - Component props
* @param {Function} [props.onSignInSuccess] - Callback for successful sign-in
* @param {Function} [props.onSignInError] - Callback for sign-in errors
* @param {string} props.callbackRedirectUri - The URI for the callback page
* @param {string} [props.postLogoutRedirectUri] - Post-logout redirect URI
* @param {Function} [props.onClickReturn] - Callback for return button click
* @param {string} [props.errorMessage] - Custom error message
*
* @returns {JSX.Element} Rendered component
*
* @example
* ```jsx
* <Callback
* callbackRedirectUri="https://app.deriv.com/callback"
* onSignInSuccess={(tokens) => handleSuccess(tokens)}
* onSignInError={(error) => handleError(error)}
* />
**/

export const Callback = ({
onClickReturn: onClickReturnCallback,
onSignInSuccess,
onSignInError,
onRequestOidcTokenSuccess,
redirectCallbackUri,
postLoginRedirectUri,
postLogoutRedirectUri,
errorMessage,
}: CallbackProps) => {
const [error, setError] = useState<Error | null>(null);

const fetchTokens = useCallback(async () => {
try {
const { accessToken } = await requestOidcToken({
redirectCallbackUri,
postLogoutRedirectUri,
});

if (accessToken) {
onRequestOidcTokenSuccess?.(accessToken);

const legacyTokens = await requestLegacyToken(accessToken);

onSignInSuccess?.(legacyTokens);
}
} catch (err) {
if (err instanceof Error) {
setError(err);
onSignInError?.(err);
}
}
}, [redirectCallbackUri, postLogoutRedirectUri]);

const onClickReturn = () => {
if (onClickReturnCallback && error !== null) {
onClickReturnCallback(error);
} else {
// Redirect the user back to the page they started from
// If there's no record from where they came from, default to redirect back to their main home page (window.location.origin)
// window.location.origin returns => https://app.deriv.com if the URL is https://app.deriv.com/callback
const _postLoginRedirectUri =
postLoginRedirectUri ||
localStorage.getItem('config.post_login_redirect_uri') ||
window.location.origin;
window.location.href = _postLoginRedirectUri;
}
};

useEffect(() => {
const params = new URLSearchParams(window.location.search);
const oneTimeCode = params.get('code');

if (oneTimeCode) {
fetchTokens();
} else {
setError(
new OIDCError(
OIDCErrorType.OneTimeCodeMissing,
'the one time code was not returned by the authorization server'
)
);
}
}, []);

return (
<div className='callback'>
<div className='callback__header'>
<DerivLogoIcon />
</div>
<div className='callback__content'>
{!error && (
<>
<div className='callback__loading'>
<Loading />
</div>
<h3>We are logging you in...</h3>
</>
)}
{error && (
<>
<ErrorIcon height={454} />
<h3>There was an issue logging you in</h3>
<p>{errorMessage || error.message}</p>
<button onClick={onClickReturn}>Return to Home</button>
</>
)}
</div>
</div>
);
};
1 change: 1 addition & 0 deletions src/components/Callback/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { Callback } from './Callback';
1 change: 1 addition & 0 deletions src/components/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './Callback';
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './hooks/';
export * from './oidc/';
export * from './components/';
9 changes: 9 additions & 0 deletions src/oidc/config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export const getConfigurations = () => {
const postLoginRedirectUri = localStorage.getItem('config.post_login_redirect_uri') || window.location.origin;
const postLogoutRedirectUri = localStorage.getItem('config.post_logout_redirect_uri') || window.location.origin;

return {
postLoginRedirectUri,
postLogoutRedirectUri,
};
};
38 changes: 11 additions & 27 deletions src/oidc/error.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,18 @@
export enum OIDCErrorType {
FailedToFetchOIDCConfiguration = "FailedToFetchOIDCConfiguration",
AuthenticationRequestFailed = "AuthenticationRequestFailed",
AccessTokenRequestFailed = "AccessTokenRequestFailed",
LegacyTokenRequestFailed = "LegacyTokenRequestFailed",
UserManagerCreationFailed = "UserManagerCreationFailed"
FailedToFetchOIDCConfiguration = 'FailedToFetchOIDCConfiguration',
AuthenticationRequestFailed = 'AuthenticationRequestFailed',
AccessTokenRequestFailed = 'AccessTokenRequestFailed',
LegacyTokenRequestFailed = 'LegacyTokenRequestFailed',
UserManagerCreationFailed = 'UserManagerCreationFailed',
OneTimeCodeMissing = 'OneTimeCodeMissing',
}

export class OIDCError extends Error {
constructor(type: OIDCErrorType) {
let message = '';
switch (type) {
case OIDCErrorType.FailedToFetchOIDCConfiguration:
message = 'Failed to fetch OIDC configuration'
break
case OIDCErrorType.AuthenticationRequestFailed:
message = 'Authentication request failed'
break
case OIDCErrorType.AccessTokenRequestFailed:
message = 'Unable to request access tokens'
break
case OIDCErrorType.LegacyTokenRequestFailed:
message = 'Unable to request legacy tokens'
break
case OIDCErrorType.UserManagerCreationFailed:
message = 'Unable to create user manager for OIDC'
break
default:
message = 'There was an issue in authenticating the user'
}
type?: OIDCErrorType;

constructor(type: OIDCErrorType, message: string) {
super(message);
this.name = type;
this.type = type;
}
}
}
Loading
Loading