Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Filter agent on Annuaire side rather than ProConnect side #1260

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion clients/authentication/agent-connect/strategy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { BaseClient, Issuer, generators } from 'openid-client';
import { HttpForbiddenError } from '#clients/exceptions';
import { IReqWithSession } from '#utils/session/with-session';
import { BaseClient, Issuer, generators } from 'openid-client';

let _client = undefined as BaseClient | undefined;

Expand Down
4 changes: 3 additions & 1 deletion models/user/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export type IAgentInfo = {
userType: string;
isPrestataire: boolean;
isMCP: boolean;
belongToATeam: boolean;
};

const extractDomain = (email: string) => {
Expand All @@ -65,7 +66,7 @@ const extractDomain = (email: string) => {
export const getAgent = async (
userInfo: IAgentConnectUserInfo
): Promise<IAgentInfo> => {
const { scopes, userType } = await getAgentScopes(userInfo?.email);
const { scopes, userType, team } = await getAgentScopes(userInfo?.email);

const domain = extractDomain(userInfo?.email || '');
const isPrestataire = isLikelyPrestataire(domain);
Expand All @@ -90,5 +91,6 @@ export const getAgent = async (
userType,
isPrestataire,
isMCP,
belongToATeam: team,
};
};
4 changes: 3 additions & 1 deletion models/user/scopes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const agentScope = [
*/
export const getAgentScopes = async (
userEmail: string
): Promise<{ scopes: IAgentScope[]; userType: string }> => {
): Promise<{ scopes: IAgentScope[]; userType: string; team: boolean }> => {
const isTestAccount =
userEmail === '[email protected]' &&
(process.env.NODE_ENV !== 'production' ||
Expand All @@ -49,6 +49,7 @@ export const getAgentScopes = async (
return {
scopes: [...agentScope, 'conformite', 'beneficiaires'],
userType: 'Super-agent connecté',
team: false,
};
}

Expand All @@ -58,5 +59,6 @@ export const getAgentScopes = async (
scopes: [...agentScope, ...additionnalScopes],
userType:
additionnalScopes.length > 0 ? 'Super-agent connecté' : 'Agent connecté',
team: additionnalScopes.length > 0,
};
};
58 changes: 56 additions & 2 deletions pages/api/auth/agent-connect/callback.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { agentConnectAuthenticate } from '#clients/authentication/agent-connect/strategy';
import { HttpForbiddenError } from '#clients/exceptions';
import { clientUniteLegaleRechercheEntreprise } from '#clients/recherche-entreprise/siren';
import { isServicePublic } from '#models/core/types';
import { Exception } from '#models/exceptions';
import { getAgent } from '#models/user/agent';
import { IAgentInfo, getAgent } from '#models/user/agent';
import { extractSirenFromSiret } from '#utils/helpers';
import { logFatalErrorInSentry } from '#utils/sentry';
import { cleanPathFrom, getPathFrom, setAgentSession } from '#utils/session';
import withSession from '#utils/session/with-session';
Expand All @@ -10,6 +13,9 @@ export default withSession(async function callbackRoute(req, res) {
try {
const userInfo = await agentConnectAuthenticate(req);
const agent = await getAgent(userInfo);

await verifyAgentHabilitation(agent);

const session = req.session;
await setAgentSession(agent, session);

Expand All @@ -23,14 +29,62 @@ export default withSession(async function callbackRoute(req, res) {
}
} catch (e: any) {
logFatalErrorInSentry(new AgentConnectionFailedException({ cause: e }));
if (e instanceof CouldAServicePublicException) {
return res.redirect('/connexion/habilitation/requise');
}
if (e instanceof HttpForbiddenError) {
res.redirect('/connexion/echec-authorisation-requise');
res.redirect('/connexion/habilitation/refuse');
} else {
res.redirect('/connexion/echec-connexion');
}
}
});

const verifyAgentHabilitation = async (agent: IAgentInfo) => {
if (agent.belongToATeam) {
return;
}

const { isMCP } = agent;

// MCP should always return a siret
if (isMCP && !agent.siret) {
throw new HttpForbiddenError('MCP user must have a siret');
}

const siren = extractSirenFromSiret(agent.siret);
// This doesn't work because it uses { cookies } from 'next/headers';
// It doesn't work in pages/api
// const uniteLegale = await getUniteLegaleFromSlug(siren, {
// page: 0,
// isBot: false,
// });
const uniteLegale = await clientUniteLegaleRechercheEntreprise(siren, 0);

if (isServicePublic(uniteLegale)) {
return;
}

const couldBeServicePublic =
uniteLegale.natureJuridique.startsWith('4') ||
uniteLegale.natureJuridique.startsWith('8');

if (couldBeServicePublic) {
throw new CouldAServicePublicException({});
}

throw new HttpForbiddenError('Organization in not a service public');
};

class CouldAServicePublicException extends Exception {
constructor(args: { cause?: any }) {
super({
name: 'CouldAServicePublicException',
...args,
});
}
}

export class AgentConnectionFailedException extends Exception {
constructor(args: { cause?: any }) {
super({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,22 +1,27 @@
import { ReactElement } from 'react';
import connexionRefusedPicture from '#components-ui/illustrations/connexion-refused';
import { LayoutConnexion } from '#components/layouts/layout-connexion';
import Meta from '#components/meta/meta-client';
import constants from '#models/constants';
import { NextPageWithLayout } from 'pages/_app';
import { ReactElement } from 'react';

const ConnexionFailure: NextPageWithLayout = () => (
<>
<Meta
title="Vous n’êtes pas autorisé(e) à accéder à cette partie du site"
noIndex={true}
/>
<h1>Vous n’êtes pas autorisé(e) à accéder à cette partie du site</h1>
<p>Cet espace est réservé aux agents publics habilités.</p>
<Meta title="Accès à l’espace agent refusé" noIndex={true} />
<h1>L’accès à l’espace agent vous est refusé</h1>
<div>Seuls peuvent accéder à l’espace agent public :</div>
<ul>
<li>
les membres d’une administration, d’une collectivité ou d’un service
public
</li>
<li>
les membres d’une organisation privée dotée d’une mission de service
public
</li>
</ul>
<p>
Vous êtes agent(e) du service public et vous souhaiter accéder au
service&nbsp;:{' '}
<a href={constants.links.parcours.contact}>contactez-nous.</a>
Votre organisation n’est pas un service public et par conséquent, l’accès
à l’espace agent vous est refusé.
</p>
<a href="/">← Retourner au moteur de recherche</a>
</>
Expand Down
52 changes: 52 additions & 0 deletions pages/connexion/habilitation/requise.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import connexionRefusedPicture from '#components-ui/illustrations/connexion-refused';
import { LayoutConnexion } from '#components/layouts/layout-connexion';
import Meta from '#components/meta/meta-client';
import { NextPageWithLayout } from 'pages/_app';
import { ReactElement } from 'react';

const HabilitationRequise: NextPageWithLayout = () => (
<>
<Meta
title="Vous n’êtes pas autorisé(e) à accéder à l’espace agent"
noIndex={true}
/>
<h1>Vous n’êtes pas autorisé(e) à accéder à l’espace agent</h1>
<div>Seuls peuvent accéder à l’espace agent public :</div>
<ul>
<li>
les membres d’une administration, d’une collectivité ou d’un service
public
</li>
<li>
les membres d’une organisation privée dotée d’une mission de service
public
</li>
</ul>
<p>
Votre organisation{' '}
<strong>ne fait pas partie de la liste des services publics</strong>. Vous
pouvez{' '}
<a
href="https://www.demarches-simplifiees.fr/commencer/7991f7ad-97d9-4bf5-a326-ae37cc858081"
target="_blank"
rel="noopener noreferrer"
>
demander l’ajout de votre organisation
</a>{' '}
à la liste.
</p>
<p>
Si votre demande est acceptée, vous obtiendrez automatiquement l’accès à
l’espace agent.
</p>
<a href="/">← Retourner au moteur de recherche</a>
</>
);

HabilitationRequise.getLayout = function getLayout(page: ReactElement) {
return (
<LayoutConnexion img={connexionRefusedPicture}>{page}</LayoutConnexion>
);
};

export default HabilitationRequise;
Loading