From 89a221f19dbba6728288f838b898f0db9d1b6356 Mon Sep 17 00:00:00 2001 From: Cameron Zuziak <93697431+cameronzuziak@users.noreply.github.com> Date: Fri, 16 Aug 2024 15:21:50 -0700 Subject: [PATCH] Update AppContext.tsx Fixed issue related to authentication. getProfilePhoto on line 106 was returning 404 in cases where users don't have an avatar, which cause caught by the catch statement, meaning the remainder of the code in the try statement after line 106 was never executed. Also setAuthenticated was never being called in that same try catch stement, so I added that. Also accessToken and sessionId were never set on initial login, so I set added that, and wrapped in a try catch statement just incase. --- app/frontend/src/context/AppContext.tsx | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/app/frontend/src/context/AppContext.tsx b/app/frontend/src/context/AppContext.tsx index 9b8a342b..3cbbf5ff 100644 --- a/app/frontend/src/context/AppContext.tsx +++ b/app/frontend/src/context/AppContext.tsx @@ -3,7 +3,7 @@ import React, { useContext, createContext, useState, MouseEventHandler, useEffect } from "react"; import { AuthCodeMSALBrowserAuthenticationProvider } from "@microsoft/microsoft-graph-client/authProviders/authCodeMsalBrowser"; -import { InteractionType, PublicClientApplication } from "@azure/msal-browser"; +import { InteractionType, PublicClientApplication, AuthenticationResult } from "@azure/msal-browser"; import { useMsal } from "@azure/msal-react"; import { getUser, getProfilePhoto } from "../GraphService"; import { v4 as uuidv4 } from "uuid"; @@ -103,7 +103,7 @@ function useProvideAppContext() { // Get the user from Microsoft Graph const user = await getUser(authProvider); console.log("user", user); - const avatar = await getProfilePhoto(authProvider); + const avatar = await getProfilePhoto(authProvider).catch(() => undefined); setUser({ displayName: user.displayName || "", email: user.mail || "", @@ -126,6 +126,7 @@ function useProvideAppContext() { setSessionId({ sessionId: uuidv4() }); + setIsAuthenticated(true); } } catch (err: any) { displayError(err.message); @@ -136,10 +137,18 @@ function useProvideAppContext() { }); const signIn = async () => { - await msal.instance.loginPopup({ - scopes: ["user.read"], - prompt: "select_account" - }); + try { + // signin then set access token and session id after successful signin + await msal.instance.loginPopup({ + scopes: ["user.read"], + prompt: "select_account" + }).then((response: AuthenticationResult) => { + setAccessToken({ accessToken: response.accessToken }); + setSessionId({ sessionId: uuidv4() }); + }, (error: any) => { console.log(error) }); + } catch (err: any) { + displayError(err.message); + } // Get the user from Microsoft Graph const user = await getUser(authProvider);