Skip to content

Commit

Permalink
fix: allow public /accessibilite (#759)
Browse files Browse the repository at this point in the history
  • Loading branch information
revolunet authored Jan 24, 2025
1 parent 2f3bdc7 commit a586bab
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 24 deletions.
2 changes: 1 addition & 1 deletion .talismanrc
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ fileignoreconfig:
- filename: src/lib/sentry.ts
checksum: 035884bbbacf7746760dacc26669a3e4a4558ba2b88c0c7a38ec4327d25d0f3d
- filename: src/middleware.ts
checksum: 49bd32aabfde512674c57660edc4b286a423397c01100cd45fbf58791d7f300b
checksum: 1ac7177d4d39cf4624f97642cea78396708e11e8e486874f1ff2c5928f017024
- filename: src/models/member.ts
checksum: 4d1a75e62ca805faf5bc5b7c83d03064171d4914e6d405a026c141b2ede9ca2c
- filename: src/server/config/index.ts
Expand Down
65 changes: 42 additions & 23 deletions src/middleware.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { HttpStatusCode } from 'axios';
import { HttpStatusCode } from "axios";
import { jwtVerify } from "jose";
import { NextRequest, NextResponse } from "next/server";

import { getArrayFromEnv } from './lib/env';
import { getArrayFromEnv } from "./lib/env";

interface UserJwtPayload {
jti: string;
Expand Down Expand Up @@ -35,45 +35,64 @@ export async function verifyAuth(req: NextRequest) {

// Allow having apex domain and subdomains
// e.g. https://ademe.fr, https://www.ademe.fr, https://subdomain.ademe.fr
const allowedOrigins = getArrayFromEnv('PROTECTED_API_ALLOWED_ORIGINS', ['gouv.fr', 'ademe.fr', 'incubateur.net']).flatMap((origin) => origin === '*' ? /https:\/\/.*/ : [
new RegExp(`https://.*\\.${origin}`),
new RegExp(`https://${origin}`),
]);
const allowedOrigins = getArrayFromEnv("PROTECTED_API_ALLOWED_ORIGINS", [
"gouv.fr",
"ademe.fr",
"incubateur.net",
]).flatMap((origin) =>
origin === "*"
? /https:\/\/.*/
: [
new RegExp(`https://.*\\.${origin}`),
new RegExp(`https://${origin}`),
]
);

const corsOptions = {
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': '*',
}
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
"Access-Control-Allow-Headers": "*",
};

function getCorsHeaders(req: NextRequest): Record<string, string> {
const origin = req.headers.get('origin') ?? '';
const isAllowedOrigin = allowedOrigins.some((allowedOrigin) => allowedOrigin.test(origin));
const origin = req.headers.get("origin") ?? "";
const isAllowedOrigin = allowedOrigins.some((allowedOrigin) =>
allowedOrigin.test(origin)
);

return {
...(isAllowedOrigin && { 'Access-Control-Allow-Origin': origin }),
...corsOptions,
};
...(isAllowedOrigin && { "Access-Control-Allow-Origin": origin }),
...corsOptions,
};
}

export async function middleware(req: NextRequest) {
// control protected routes
if (req.nextUrl.pathname.startsWith('/api/protected/')) {
if (req.nextUrl.pathname.startsWith("/api/protected/")) {
const headers = getCorsHeaders(req);
if (req.method === 'OPTIONS') { // preflight request
if (req.method === "OPTIONS") {
// preflight request
return NextResponse.json({}, { headers });
}

const PROTECTED_API_KEYS = getArrayFromEnv('PROTECTED_API_KEYS')
if (!req.headers.has('X-Api-Key')) {
return NextResponse.json({ error: { message: 'Api key is required.' }}, { status: HttpStatusCode.UnprocessableEntity, headers });
const PROTECTED_API_KEYS = getArrayFromEnv("PROTECTED_API_KEYS");
if (!req.headers.has("X-Api-Key")) {
return NextResponse.json(
{ error: { message: "Api key is required." } },
{ status: HttpStatusCode.UnprocessableEntity, headers }
);
}
const apiKey = req.headers.get('X-Api-Key') ?? '';
const apiKey = req.headers.get("X-Api-Key") ?? "";
if (!PROTECTED_API_KEYS.includes(apiKey)) {
return NextResponse.json({ error: { message: 'Invalid api key.' }}, { status: HttpStatusCode.Unauthorized, headers });
return NextResponse.json(
{ error: { message: "Invalid api key." } },
{ status: HttpStatusCode.Unauthorized, headers }
);
}

const response = NextResponse.next();
Object.entries(headers).forEach(([key, value]) => response.headers.set(key, value));
Object.entries(headers).forEach(([key, value]) =>
response.headers.set(key, value)
);
return response;
}

Expand Down Expand Up @@ -113,6 +132,6 @@ export const config = {
* - favicon.ico, sitemap.xml, robots.txt (metadata files)
*/
// "/dashboard",
"/((?!keskispasse|components|login|signin|api/hook|api/auth|api/public|static/|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
"/((?!accessibilite|keskispasse|components|login|signin|api/hook|api/auth|api/public|static/|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",
],
};

0 comments on commit a586bab

Please sign in to comment.