Skip to content

Commit

Permalink
chore: redirerect to dashboard if user connected
Browse files Browse the repository at this point in the history
  • Loading branch information
LucasCharrier committed Jan 20, 2025
1 parent bac5a84 commit 012a452
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 28 deletions.
2 changes: 1 addition & 1 deletion .talismanrc
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ fileignoreconfig:
- filename: src/lib/sentry.ts
checksum: 035884bbbacf7746760dacc26669a3e4a4558ba2b88c0c7a38ec4327d25d0f3d
- filename: src/middleware.ts
checksum: 49bd32aabfde512674c57660edc4b286a423397c01100cd45fbf58791d7f300b
checksum: 0cfb47778eb5cebdd1353f3c2ce3c14f21c71e2343fb33a6914820d97726b49c
- filename: src/models/member.ts
checksum: 4d1a75e62ca805faf5bc5b7c83d03064171d4914e6d405a026c141b2ede9ca2c
- filename: src/server/config/index.ts
Expand Down
9 changes: 4 additions & 5 deletions src/app/(public)/signin/SiginClientPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,7 @@ export default function SignClientPage() {
// If the URL is absolute, replace its origin with the current hostname
const fullUrl = `${hostname}${parsedUrl.pathname}${parsedUrl.search}${parsedUrl.hash}`;
// Navigate to the constructed URL
// redirectionUrl = fullUrl;
console.log(fullUrl);
redirectionUrl = fullUrl;
} catch (e) {
// In case of any error, fallback to redirecting to a default page
console.error("Invalid URL provided:", e);
Expand Down Expand Up @@ -68,9 +67,9 @@ export default function SignClientPage() {
document.location = "/";
};

// React.useEffect(() => {
// if (typeof window !== "undefined") onSubmit();
// }, [onSubmit]);
React.useEffect(() => {
if (typeof window !== "undefined") onSubmit();
}, [onSubmit]);

return (
<div>
Expand Down
67 changes: 45 additions & 22 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 All @@ -98,6 +117,10 @@ export async function middleware(req: NextRequest) {
new URL(`/login?next=${req.url}`, req.url)
);
}
} else {
if (req.nextUrl.pathname === "/") {
return NextResponse.redirect(new URL("/dashboard", req.url));
}
}
}

Expand Down

0 comments on commit 012a452

Please sign in to comment.