-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmiddleware.ts
41 lines (37 loc) · 1.46 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
import authConfig from "@/auth.config";
import NextAuth from "next-auth";
import { DEFAULT_LOGIN_REDIRECT, forLoggedOutUsers, publicRoutes } from "@/routes";
import { NextResponse } from "next/server";
const { auth } = NextAuth(authConfig);
export default auth(async (req) => {
const { nextUrl } = req;
const isLoggedIn = !!req.auth;
const user = req.auth?.user;
const isPublicRoute = publicRoutes.some(route =>
typeof route === 'string' ? route === nextUrl.pathname : route.test(nextUrl.pathname)
);
const isOnlyLoggedOut = forLoggedOutUsers.includes(nextUrl.pathname);
const isApiRoute = nextUrl.pathname.startsWith("/api");
if(isApiRoute){
if(nextUrl.pathname.startsWith("/api/auth")) return;
else{
const token = req.headers.get('Authorization')?.split("Bearer ")[1];
if(!token) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
try{
if(token === process.env.API_TOKEN) return;
}
catch(e){
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
}
}
}
if(isOnlyLoggedOut){
if(isLoggedIn) return NextResponse.redirect(new URL(DEFAULT_LOGIN_REDIRECT, nextUrl))
}
if(!isLoggedIn && !isPublicRoute){
return NextResponse.redirect(new URL("/", nextUrl))
}
});
export const config = {
matcher: ["/((?!.+\\.[\\w]+$|_next).*)", "/", "/(api|trpc)(.*)"],
};