Skip to content

Commit

Permalink
Sc-9563: improve certificate expiration error (#819)
Browse files Browse the repository at this point in the history
* WIP: Improve Error Message certificate expiration

* refact: set token exp in cookie & check token validity in dash layout

* fix: token expiration from auth0

* remove unused console

* file cleanup
  • Loading branch information
masskoder authored Oct 1, 2022
1 parent c989227 commit 0d7b7f9
Show file tree
Hide file tree
Showing 11 changed files with 108 additions and 42 deletions.
12 changes: 0 additions & 12 deletions node_modules/.yarn-integrity

This file was deleted.

18 changes: 15 additions & 3 deletions web/gds-user-ui/src/components/Header/LandingHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,9 +111,21 @@ const LandingHeader = (props: FlexProps): JSX.Element => {
<MenuItem to={`${TRISA_BASE_URL}/${locale}`} color="white">
<Trans id="Documentation">Documentation</Trans>
</MenuItem>
<MenuItem to="/auth/login" color="white">
<Trans id="Login">Login</Trans>
</MenuItem>
<Stack>
{!isLoggedIn ? (
<NavLink to={'/auth/login'}>
<Button variant="secondary">
<Trans id="Login">Login</Trans>
</Button>
</NavLink>
) : (
<NavLink to={'/dashboard/overview'}>
<Button variant="secondary">
<Trans id="Your dashboard">Your dashboard</Trans>
</Button>
</NavLink>
)}
</Stack>
</DrawerBody>
</DrawerContent>
</Drawer>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Spinner, Flex, Text, VStack } from '@chakra-ui/react';

interface LoaderProps {
title?: string;
opacity?: 'md' | 'full';
}
// This loader is for containers that are loading
const TransparentLoader: React.FC<LoaderProps> = (props) => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,15 @@ exports[`<MembershipGuide /> should match snapshot 1`] = `
<div
class="css-1p293e5"
>
<img
alt="Trisa logo"
src="trisa_logo.svg"
/>
<a
href="/"
>
<img
alt="Trisa logo"
class="css-1czmu1r"
src="trisa_logo.svg"
/>
</a>
</div>
</a>
</a>
Expand Down
21 changes: 16 additions & 5 deletions web/gds-user-ui/src/hooks/useAuth.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useDispatch, useSelector } from 'react-redux';
import { userSelector, login, logout, isLoggedInSelector } from 'modules/auth/login/user.slice';
import { getCookie } from 'utils/cookies';
import { getCookie, clearCookies } from 'utils/cookies';
import useCustomAuth0 from './useCustomAuth0';
const useAuth = () => {
const dispatch = useDispatch();
Expand All @@ -12,6 +12,8 @@ const useAuth = () => {
dispatch(login(u));
};
const getToken = getCookie('access_token') || '';
// get expiry time from cookie
const getExpiryTime: any = getCookie('expires_in') || '';

const logoutUser = () => {
dispatch(logout());
Expand Down Expand Up @@ -42,11 +44,20 @@ const useAuth = () => {
const isUserAuthenticated = !!isLoggedIn;

const isAuthenticated = () => {
if (isLoggedIn && !getToken) {
logoutUser();
return false;
// if token is expired then logout
if (getExpiryTime && isLoggedIn && getToken) {
const currentTime = new Date().getTime() / 1000;

if (currentTime > +getExpiryTime) {
console.log('token expired');
clearCookies();
logoutUser();
return false;
} else {
return isUserAuthenticated;
}
}
return isUserAuthenticated;
return false;
};

return {
Expand Down
21 changes: 20 additions & 1 deletion web/gds-user-ui/src/layouts/DashboardLayout.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import React from 'react';
import React, { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import Sidebar from 'components/Sidebar';
import { Box } from '@chakra-ui/react';
import Loader from 'components/Loader';
import { userSelector } from 'modules/auth/login/user.slice';
import TransparentLoader from '../components/Loader/TransparentLoader';
import { isTokenExpired } from 'utils/utils';
type DashboardLayoutProp = {
children: React.ReactNode;
};
Expand All @@ -21,13 +22,31 @@ const AxiosErrorLoader = () => {

const DashboardLayout: React.FC<DashboardLayoutProp> = (props) => {
const { isFetching } = useSelector(userSelector);
const [isLoading, setIsLoading] = useState(false);

// const deps = window.location.pathname;
useEffect(() => {
// check if token is valid
// if not, redirect to login page
if (isTokenExpired()) {
setIsLoading(true);
setTimeout(() => {
window.location.href = `/auth/login?q=token_expired`;
}, 1000);
}
}, []);

return (
<>
{isFetching ? (
<Loader />
) : (
<>
{isLoading && (
<Box>
<TransparentLoader title="Your session has expired..." />
</Box>
)}
<AxiosErrorLoader />
<Sidebar {...props} />
</>
Expand Down
7 changes: 7 additions & 0 deletions web/gds-user-ui/src/modules/auth/login/user.slice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,11 @@ export const getAuth0User: any = createAsyncThunk(
// then login with auth0
const getUserInfo: any = hasToken && (await auth0Hash());
// console.log('[getUserInfo]', getUserInfo);
const updatedTime = new Date(getUserInfo?.idTokenPayload?.updated_at).getTime() / 1000;
const expiresTime = updatedTime + getUserInfo.expiresIn;
setCookie('access_token', getUserInfo?.accessToken);
setCookie('user_locale', getUserInfo?.idTokenPayload?.locale || 'en');
setCookie('expires_in', expiresTime);
if (getUserInfo && getUserInfo?.idTokenPayload?.email_verified) {
const getUser = await logUserInBff();
// console.log('[getUser]', getUser);
Expand All @@ -72,6 +75,10 @@ export const getAuth0User: any = createAsyncThunk(
// console.log('[newUserPayload]', newUserPayload);
setCookie('access_token', newUserPayload?.accessToken);
setCookie('user_locale', newUserPayload?.idTokenPayload?.locale || 'en');
// set expired time
const updated = new Date(newUserPayload?.idTokenPayload?.updated_at).getTime() / 1000;
const expires = updated + getUserInfo.expiresIn;
setCookie('expires_in', expires);
const userInfo: TUser = {
isLoggedIn: true,
user: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ const Certificate: React.FC = () => {

async function handleNextStepClick() {
if (hasErroredField()) {
console.log('has errored field');
// i think we should not use alert here , but we need to find a way to display the error message
// eslint-disable-next-line no-alert
if (window.confirm('Some elements required for registration are missing; continue anyway?')) {
Expand All @@ -122,14 +123,6 @@ const Certificate: React.FC = () => {
});
}
} else {
nextStep({
isFormCompleted: isFormCompleted(),
formValues: getCurrentFormValue(),
values: methods.getValues(),
registrationValues: registrationData,
isDirty: methods.formState.isDirty,
setRegistrationState: setRegistrationData
});
if (isDirty) {
await postRegistrationValue({
...methods.getValues(),
Expand All @@ -138,6 +131,14 @@ const Certificate: React.FC = () => {
}
});
}
nextStep({
isFormCompleted: isFormCompleted(),
formValues: getCurrentFormValue(),
values: methods.getValues(),
registrationValues: registrationData,
isDirty: methods.formState.isDirty,
setRegistrationState: setRegistrationData
});
}
}
const handlePreviousStep = async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,15 @@ exports[`<VerifyPage /> should match snapshot 1`] = `
<div
class="css-1p293e5"
>
<img
alt="Trisa logo"
src="trisa_logo.svg"
/>
<a
href="/"
>
<img
alt="Trisa logo"
class="css-1czmu1r"
src="trisa_logo.svg"
/>
</a>
</div>
</a>
</a>
Expand Down
23 changes: 22 additions & 1 deletion web/gds-user-ui/src/utils/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import auth0 from 'auth0-js';
import getAuth0Config from 'application/config/auth0';
import * as Sentry from '@sentry/react';
import { getRegistrationDefaultValue } from 'modules/dashboard/registration/utils';

import { getCookie } from 'utils/cookies';
const DEFAULT_REGISTRATION_AUTHORITY = 'RA777777';
export const findStepKey = (steps: any, key: number) =>
steps?.filter((step: any) => step.key === key);
Expand Down Expand Up @@ -145,6 +145,14 @@ export const getRefreshToken = () => {
});
};
export const handleError = (error: any, customMessage?: string) => {
// if error status code is 403 display transparent loader
if (error?.response?.status === 403) {
// get el axiosLoader id and set display to block
const el = document.getElementById('axiosLoader');
if (el) {
el.style.display = 'block';
}
}
if (error) {
Sentry.captureException(error);
}
Expand Down Expand Up @@ -221,3 +229,16 @@ export const splitAndDisplay = (str: string, delimiter?: string, limit?: number)
const limitWords = limit ? words.slice(0, limit) : words;
return limitWords.join(' ');
};

// ceckisTokenExpired function get from cookies
export const isTokenExpired = () => {
// get expires token from cookies
const expiresIn = getCookie('expires_in');
if (expiresIn) {
// get current time
const currentTime = new Date().getTime() / 1000;
// check if token is expired
return currentTime > expiresIn;
}
return false;
};
4 changes: 0 additions & 4 deletions yarn.lock

This file was deleted.

0 comments on commit 0d7b7f9

Please sign in to comment.