Skip to content

Commit

Permalink
Fix authentication flow (#1749)
Browse files Browse the repository at this point in the history
  • Loading branch information
danypellerin authored Oct 26, 2024
1 parent d02cac7 commit 0ab5b7d
Showing 1 changed file with 74 additions and 74 deletions.
148 changes: 74 additions & 74 deletions TrashMob/client-app/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { initializeIcons } from '@uifabric/icons';
import { MsalAuthenticationResult, MsalAuthenticationTemplate, MsalProvider } from '@azure/msal-react';
import { InteractionType } from '@azure/msal-browser';
import * as msal from '@azure/msal-browser';
import { Guid } from 'guid-typescript';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import Home from './components/Pages/Home';
Expand All @@ -26,7 +25,7 @@ import { PrivacyPolicy } from './components/PrivacyPolicy';
import { TermsOfService } from './components/Pages/TermsOfService';
import { Board } from './components/Board';
import { VolunteerOpportunities } from './components/VolunteerOpportunities';
import { msalClient } from './store/AuthStore';
import { getApiConfig, msalClient } from './store/AuthStore';
import EventDetails, { DetailsMatchParams } from './components/Pages/EventDetails';
import { NoMatch } from './components/NoMatch';
import UserData from './components/Models/UserData';
Expand Down Expand Up @@ -64,37 +63,83 @@ interface DeleteMyDataProps extends RouteComponentProps {}

const queryClient = new QueryClient();

export const App: FC = () => {
const [isUserLoaded, setIsUserLoaded] = useState(false);
const useInitializeApp = () => {
const [isInitialized, setIsInitialized] = useState(false);
useEffect(() => {
if (isInitialized) {
return;
}
setIsInitialized(true);
initializeIcons();
}, [isInitialized]);
};

const useLogin = () => {
const [callbackId, setCallbackId] = useState('');
const [currentUser, setCurrentUser] = useState<UserData>(new UserData());
const isUserLoaded = !!currentUser.email;

useEffect(() => {
if (callbackId) {
return;
}
const id = msalClient.addEventCallback((message: msal.EventMessage) => {
if (message.eventType === msal.EventType.LOGIN_SUCCESS) {
verifyAccount(message.payload as msal.AuthenticationResult);
}
if (message.eventType === msal.EventType.LOGOUT_SUCCESS) {
clearUser();
}
});
setCallbackId(id ?? '');
initialLogin();
return () => msalClient.removeEventCallback(callbackId);
}, [callbackId]);

useEffect(
() => {
initializeIcons();
async function initialLogin() {
const accounts = msalClient.getAllAccounts();
if (accounts === null || accounts.length <= 0) {
return;
}
const tokenResponse = await msalClient.acquireTokenSilent({
scopes: getApiConfig().b2cScopes,
account: accounts[0],
});
verifyAccount(tokenResponse);
}

msalClient.addEventCallback((message: msal.EventMessage) => {
if (message.eventType === msal.EventType.LOGIN_SUCCESS) {
verifyAccount(message.payload as msal.AuthenticationResult);
}
if (message.eventType === msal.EventType.LOGOUT_SUCCESS) {
clearUser();
}
});
function clearUser() {
setCurrentUser(new UserData());
}

const userStr = sessionStorage.getItem('user');
if (userStr) {
const user = JSON.parse(userStr);
setCurrentUser(user);
if (user.id === Guid.EMPTY) {
setIsUserLoaded(false);
} else {
setIsUserLoaded(true);
}
}
},
// eslint-disable-next-line
[],
);
async function handleUserUpdated() {
const { data: user } = await GetUserById({ userId: currentUser?.id }).service();
setCurrentUser(user || new UserData());
}

async function verifyAccount(result: msal.AuthenticationResult) {
const { userDeleted } = result.idTokenClaims as Record<string, any>;
if (userDeleted && userDeleted === true) {
clearUser();
return;
}
const { email } = result.idTokenClaims as Record<string, any>;
const { data: user } = await GetUserByEmail({ email }).service();
if (!user) {
return;
}
setCurrentUser(user);
}
return {
isUserLoaded,
currentUser,
handleUserUpdated,
};
};

export const App: FC = () => {
useInitializeApp();
const { currentUser, isUserLoaded, handleUserUpdated } = useLogin();

function ErrorComponent(error: MsalAuthenticationResult) {
return (
Expand Down Expand Up @@ -177,51 +222,6 @@ export const App: FC = () => {
);
}

function clearUser() {
const user = new UserData();
setCurrentUser(user);
sessionStorage.setItem('user', JSON.stringify(user));
setIsUserLoaded(false);
}

function handleUserUpdated() {
setIsUserLoaded(false);
GetUserById({ userId: currentUser.id })
.service()
.then((res) => {
setCurrentUser(res.data || new UserData());
setIsUserLoaded(true);
sessionStorage.setItem('user', JSON.stringify(res.data));
});
}

function verifyAccount(result: msal.AuthenticationResult) {
const { userDeleted } = result.idTokenClaims as Record<string, any>;
if (userDeleted && userDeleted === true) {
clearUser();
return;
}

const { email } = result.idTokenClaims as Record<string, any>;
GetUserByEmail({ email })
.service()
.then((res) => {
const user = new UserData();
if (res.data) {
user.id = res.data.id;
user.userName = res.data.userName;
user.dateAgreedToTrashMobWaiver = res.data.dateAgreedToTrashMobWaiver;
user.memberSince = res.data.memberSince;
user.trashMobWaiverVersion = res.data.trashMobWaiverVersion;
user.isSiteAdmin = res.data.isSiteAdmin;
user.email = res.data.email;
}
setCurrentUser(user);
setIsUserLoaded(true);
sessionStorage.setItem('user', JSON.stringify(user));
});
}

return (
<QueryClientProvider client={queryClient}>
<MsalProvider instance={msalClient}>
Expand Down

0 comments on commit 0ab5b7d

Please sign in to comment.