-
Notifications
You must be signed in to change notification settings - Fork 429
/
Copy pathmiddleware.ts
47 lines (42 loc) · 1.36 KB
/
middleware.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import { getToken } from "next-auth/jwt";
import { NextRequestWithAuth, withAuth } from "next-auth/middleware";
import { NextMiddlewareResult } from "next/dist/server/web/types";
import { NextRequest, NextResponse } from "next/server";
export async function middleware(req: NextRequest) {
const response = NextResponse.next();
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS"
);
response.headers.set(
"Access-Control-Allow-Headers",
"Content-Type, Authorization"
);
if (req.method === "OPTIONS") {
return new Response(null, { status: 204 });
}
const token = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
const pathname = req.nextUrl.pathname;
const isAuthenticated = !!token;
const isLoginPage = pathname === "/login";
if (isAuthenticated && isLoginPage) {
return NextResponse.redirect(new URL("/", req.url));
}
return withAuth(
(authReq: NextRequestWithAuth): NextMiddlewareResult => {
return NextResponse.next();
},
{
pages: {
signIn: "/login",
},
callbacks: {
authorized: ({ token }) => !!token,
}
}
)(req as NextRequestWithAuth, {} as any);
}
export const config = {
matcher: ["/hackathons/registration-form/:path*","/login/:path*"],
};