From fec64f2da8d87993e7fc0b7f22309715e479a4a3 Mon Sep 17 00:00:00 2001 From: charliemidtlyng Date: Tue, 14 Nov 2023 10:43:01 +0100 Subject: [PATCH 1/3] =?UTF-8?q?Skal=20pr=C3=B8ve=20=C3=A5=20hente=20ut=20b?= =?UTF-8?q?rukerdata=20to=20ganger=20f=C3=B8r=20vi=20feiler.=20Dersom=20vi?= =?UTF-8?q?=20feiler=20m=C3=A5=20vi=20stanse=20brukeren=20s=C3=A5=20de=20i?= =?UTF-8?q?kke=20sitter=20med=20en=20ugyldig=20brukerdatastate,=20req.sess?= =?UTF-8?q?ion.user,=20som=20i=20praksis=20gj=C3=B8r=20det=20umulig=20?= =?UTF-8?q?=C3=A5=20finne=20ut=20om=20man=20er=20veileder,=20saksbehandler?= =?UTF-8?q?=20eller=20beslutter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/familie-backend/src/auth/bruker.ts | 56 ++++++++++++--------- packages/familie-backend/src/utils.ts | 4 +- 2 files changed, 36 insertions(+), 24 deletions(-) diff --git a/packages/familie-backend/src/auth/bruker.ts b/packages/familie-backend/src/auth/bruker.ts index f28e9a26d..a7d3c7346 100644 --- a/packages/familie-backend/src/auth/bruker.ts +++ b/packages/familie-backend/src/auth/bruker.ts @@ -16,22 +16,42 @@ export const hentBrukerprofil = () => { }; }; -const håndterFeil = (req: Request, err: Error, next: NextFunction) => { - if (!req.session) { - throw new Error('Mangler sesjon på kall'); - } - - req.session.user = { - ...req.session.user, - enhet: '9999', - }; +const håndterGenerellFeil = (req: Request, err: Error) => { + logRequest(req, `Noe gikk galt: ${err.message}.`, LOG_LEVEL.ERROR); + throw new Error('Noe gikk galt ved pålogging i løsningen. Vennligst prøv på nytt.'); +}; +const håndterBrukerdataFeil = (req: Request, err: Error) => { logRequest( req, - `Feilet mot ms graph: ${err.message}. Fortsetter uten data fra bruker.`, + `Feilet mot ms graph: ${err.message}. Kan ikke fortsette uten brukerdata.`, LOG_LEVEL.ERROR, ); - return next(); + if (req.session) { + throw new Error('Noe gikk galt ved pålogging i løsningen. Vennligst prøv på nytt.'); + } else { + throw new Error( + 'Kunne ikke hente dine brukeropplysninger. Vennligst logg ut og inn på nytt.', + ); + } +}; + +const fetchFraMs = (accessToken: string) => { + const query = 'onPremisesSamAccountName,displayName,mail,officeLocation,userPrincipalName,id'; + const graphUrl = `${envVar('GRAPH_API')}?$select=${query}`; + + return fetch(graphUrl, { + headers: { + Authorization: `Bearer ${accessToken}`, + 'Content-Type': 'application/json', + }, + }); +}; +const hentBrukerData = (accessToken: string, req: Request) => { + return fetchFraMs(accessToken).catch((e: Error) => { + logRequest(req, `Kunne ikke hente brukerdata - prøver på nytt: ${e}`, LOG_LEVEL.WARNING); + return fetchFraMs(accessToken).catch((err: Error) => håndterBrukerdataFeil(req, err)); + }); }; /** @@ -48,18 +68,8 @@ export const setBrukerprofilPåSesjon = (authClient: Client, req: Request, next: return next(); } - const query = - 'onPremisesSamAccountName,displayName,mail,officeLocation,userPrincipalName,id'; - const graphUrl = `${envVar('GRAPH_API')}?$select=${query}`; getOnBehalfOfAccessToken(authClient, req, api) - .then(accessToken => - fetch(graphUrl, { - headers: { - Authorization: `Bearer ${accessToken}`, - 'Content-Type': 'application/json', - }, - }), - ) + .then(accessToken => hentBrukerData(accessToken, req)) .then(res => res.json()) .then((data: any) => { if (!req.session) { @@ -90,7 +100,7 @@ export const setBrukerprofilPåSesjon = (authClient: Client, req: Request, next: }); }) .catch((err: Error) => { - return håndterFeil(req, err, next); + return håndterGenerellFeil(req, err); }); }); }; diff --git a/packages/familie-backend/src/utils.ts b/packages/familie-backend/src/utils.ts index ab02fb683..82dc4482a 100644 --- a/packages/familie-backend/src/utils.ts +++ b/packages/familie-backend/src/utils.ts @@ -16,7 +16,9 @@ export const envVar = (navn: string, påkrevd = true, defaultValue?: string): st const prefix = (req: Request) => { return `${ - req.session && req.session.user ? `${req.session.user.displayName} -` : 'ugyldig sesjon -' + req.session && req.session.user + ? `${req.session.user.displayName} -` + : 'ugyldig sesjon eller mangler brukers data -' } ${req.method} - ${req.originalUrl}`; }; From 04b202695125a665346701eb6a16641082fafeb7 Mon Sep 17 00:00:00 2001 From: charliemidtlyng Date: Tue, 14 Nov 2023 13:50:02 +0100 Subject: [PATCH 2/3] =?UTF-8?q?Kan=20ikke=20kaste=20feil=20helt=20ut=20til?= =?UTF-8?q?=20api-et=20-=20da=20krasjer=20hele=20appen=20og=20skrur=20seg?= =?UTF-8?q?=20av.=20Beholder=20eksisterende=20funksjonalitet=20med=20?= =?UTF-8?q?=C3=A5=20kj=C3=B8re=20igjennom=20og=20videre?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- packages/familie-backend/src/auth/bruker.ts | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/packages/familie-backend/src/auth/bruker.ts b/packages/familie-backend/src/auth/bruker.ts index a7d3c7346..b13407a50 100644 --- a/packages/familie-backend/src/auth/bruker.ts +++ b/packages/familie-backend/src/auth/bruker.ts @@ -16,24 +16,18 @@ export const hentBrukerprofil = () => { }; }; -const håndterGenerellFeil = (req: Request, err: Error) => { - logRequest(req, `Noe gikk galt: ${err.message}.`, LOG_LEVEL.ERROR); - - throw new Error('Noe gikk galt ved pålogging i løsningen. Vennligst prøv på nytt.'); +const håndterGenerellFeil = (next: NextFunction, req: Request, err: Error) => { + logRequest(req, `Noe gikk galt: ${err?.message}.`, LOG_LEVEL.ERROR); + next(); }; + const håndterBrukerdataFeil = (req: Request, err: Error) => { logRequest( req, `Feilet mot ms graph: ${err.message}. Kan ikke fortsette uten brukerdata.`, LOG_LEVEL.ERROR, ); - if (req.session) { - throw new Error('Noe gikk galt ved pålogging i løsningen. Vennligst prøv på nytt.'); - } else { - throw new Error( - 'Kunne ikke hente dine brukeropplysninger. Vennligst logg ut og inn på nytt.', - ); - } + throw new Error('Kunne ikke hente dine brukeropplysninger. Vennligst logg ut og inn på nytt'); }; const fetchFraMs = (accessToken: string) => { @@ -100,7 +94,7 @@ export const setBrukerprofilPåSesjon = (authClient: Client, req: Request, next: }); }) .catch((err: Error) => { - return håndterGenerellFeil(req, err); + return håndterGenerellFeil(next, req, err); }); }); }; From 1aff5d05763194aaf7fdab55fa079ed7bac2dff9 Mon Sep 17 00:00:00 2001 From: charliemidtlyng Date: Tue, 14 Nov 2023 14:40:40 +0100 Subject: [PATCH 3/3] =?UTF-8?q?Brukerprofil=20p=C3=A5=20sesjon=20brukes=20?= =?UTF-8?q?kun=20ved=20kall=20p=C3=A5=20profilendepunktet=20-=20og=20f=20v?= =?UTF-8?q?il=20unng=C3=A5=20=C3=A5=20und=C3=B8dvendig=20intern=20kompleks?= =?UTF-8?q?itet=20der=20dette=20ikke=20er=20strengt=20n=C3=B8dvendig=20.?= =?UTF-8?q?=20Trekker=20derfor=20ut=20denne=20delen=20fra=20=5FensureAuthe?= =?UTF-8?q?nticated=5F=20slik=20at=20utviklere=20senere=20forst=C3=A5r=20a?= =?UTF-8?q?t=20dette=20ikke=20trengs=20for=20=C3=A5=20sjekke=20at=20noen?= =?UTF-8?q?=20er=20autentisert?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../familie-backend/src/auth/authenticate.ts | 16 +++++++--------- packages/familie-backend/src/auth/bruker.ts | 8 +++++++- packages/familie-backend/src/router.ts | 9 +++++++-- 3 files changed, 21 insertions(+), 12 deletions(-) diff --git a/packages/familie-backend/src/auth/authenticate.ts b/packages/familie-backend/src/auth/authenticate.ts index 2ddfdb3a7..0570dd329 100644 --- a/packages/familie-backend/src/auth/authenticate.ts +++ b/packages/familie-backend/src/auth/authenticate.ts @@ -4,7 +4,6 @@ import { appConfig } from '../config'; import { LOG_LEVEL } from '@navikt/familie-logging'; import { getTokenSetsFromSession, tokenSetSelfId, hasValidAccessToken } from './tokenUtils'; import { Client, TokenSet } from 'openid-client'; -import { setBrukerprofilPåSesjon } from './bruker'; import { logRequest } from '../utils'; export const authenticateAzure = (req: Request, res: Response, next: NextFunction) => { @@ -86,15 +85,14 @@ export const ensureAuthenticated = (authClient: Client, sendUnauthorized: boolea return; }); } - - return setBrukerprofilPåSesjon(authClient, req, next); - } - - const pathname = req.originalUrl; - if (sendUnauthorized) { - res.status(401).send('Unauthorized'); + return next(); } else { - res.redirect(`/login?redirectUrl=${pathname}`); + const pathname = req.originalUrl; + if (sendUnauthorized) { + res.status(401).send('Unauthorized'); + } else { + res.redirect(`/login?redirectUrl=${pathname}`); + } } }; }; diff --git a/packages/familie-backend/src/auth/bruker.ts b/packages/familie-backend/src/auth/bruker.ts index b13407a50..0fd5d9693 100644 --- a/packages/familie-backend/src/auth/bruker.ts +++ b/packages/familie-backend/src/auth/bruker.ts @@ -51,7 +51,13 @@ const hentBrukerData = (accessToken: string, req: Request) => { /** * Funksjon som henter brukerprofil fra graph. */ -export const setBrukerprofilPåSesjon = (authClient: Client, req: Request, next: NextFunction) => { +export const setBrukerprofilPåSesjonRute = (authClient: Client) => { + return async (req: Request, _: Response, next: NextFunction) => { + return setBrukerprofilPåSesjon(authClient, req, next); + }; +}; + +const setBrukerprofilPåSesjon = (authClient: Client, req: Request, next: NextFunction) => { return new Promise((_, _reject) => { const api = { clientId: 'https://graph.microsoft.com', diff --git a/packages/familie-backend/src/router.ts b/packages/familie-backend/src/router.ts index d39c1b4e3..b3847e799 100644 --- a/packages/familie-backend/src/router.ts +++ b/packages/familie-backend/src/router.ts @@ -7,7 +7,7 @@ import { ensureAuthenticated, logout, } from './auth/authenticate'; -import { hentBrukerprofil } from './auth/bruker'; +import { hentBrukerprofil, setBrukerprofilPåSesjonRute } from './auth/bruker'; const router = express.Router(); @@ -24,7 +24,12 @@ export default (authClient: Client, prometheusTellere?: { [key: string]: Counter router.get('/auth/logout', (req: Request, res: Response) => logout(req, res)); // Bruker - router.get('/user/profile', ensureAuthenticated(authClient, true), hentBrukerprofil()); + router.get( + '/user/profile', + ensureAuthenticated(authClient, true), + setBrukerprofilPåSesjonRute(authClient), + hentBrukerprofil(), + ); return router; };