Skip to content

Commit

Permalink
Bedre feilhåndtering av kall mot MS for brukerdata (#1255)
Browse files Browse the repository at this point in the history
  • Loading branch information
charliemidtlyng authored Nov 20, 2023
1 parent 93000d1 commit 788ef3b
Show file tree
Hide file tree
Showing 4 changed files with 51 additions and 36 deletions.
16 changes: 7 additions & 9 deletions packages/familie-backend/src/auth/authenticate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand Down Expand Up @@ -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}`);
}
}
};
};
Expand Down
58 changes: 34 additions & 24 deletions packages/familie-backend/src/auth/bruker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,48 @@ 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 = (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}. Fortsetter uten data fra bruker.`,
`Feilet mot ms graph: ${err.message}. Kan ikke fortsette uten brukerdata.`,
LOG_LEVEL.ERROR,
);
return next();
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));
});
};

/**
* 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',
Expand All @@ -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) {
Expand Down Expand Up @@ -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(next, req, err);
});
});
};
9 changes: 7 additions & 2 deletions packages/familie-backend/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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;
};
4 changes: 3 additions & 1 deletion packages/familie-backend/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`;
};

Expand Down

0 comments on commit 788ef3b

Please sign in to comment.